feat(cartridge): implement RTC calendar transfers and clock updates

This commit is contained in:
0xrsydn 2026-10-07 05:55:31 +07:00
commit fce222eea2
22 changed files with 1227 additions and 196 deletions

View file

@ -1,5 +1,6 @@
//! Host-only raw ROM loading, execution modes, and diagnostics.
pub(crate) mod rtc_clock;
pub mod suite;
pub mod window;
@ -13,7 +14,7 @@ use std::{
use gba_core::{
bios,
cartridge::CartridgeHardware,
cartridge::{CartridgeHardware, RtcError},
machine::{Machine, MachineError, StepKind},
memory::ROM_CAPACITY,
};
@ -176,9 +177,23 @@ struct Report {
reason: Reason,
}
#[cfg(test)]
fn run_bounded(machine: &mut Machine, limit: u64) -> Report {
run_bounded_with_clock(machine, limit, None).unwrap()
}
fn run_bounded_with_clock(
machine: &mut Machine,
limit: u64,
mut clock: Option<&mut rtc_clock::RtcHostClock>,
) -> Result<Report, RtcError> {
let mut stats = Stats::default();
let reason = loop {
if stats.steps % 4096 == 0 {
if let Some(clock) = clock.as_deref_mut() {
clock.sync(machine.memory_mut())?;
}
}
// STOP has no host input source here. Do not spin with a frozen clock.
// Check before the budget so STOP on the last step is reported correctly.
if machine.stopped() {
@ -193,7 +208,10 @@ fn run_bounded(machine: &mut Machine, limit: u64) -> Report {
Err(error) => break Reason::Diagnostic(error),
}
};
Report { stats, reason }
if let Some(clock) = clock {
clock.sync(machine.memory_mut())?;
}
Ok(Report { stats, reason })
}
fn write_report(writer: &mut impl Write, machine: &Machine, report: &Report) -> io::Result<()> {
@ -244,7 +262,7 @@ pub fn execute(options: Options, writer: &mut impl Write) -> Result<(), Box<dyn
"Original BIOS replacement; no commercial-game compatibility claim."
)?;
if options.hardware == CartridgeHardware::Rtc {
writeln!(writer, "RTC selected: GPIO and command/control only; calendar and IRQ commands remain diagnostic.")?;
writeln!(writer, "RTC selected: UTC at startup, then host elapsed time; no persistence or RTC interrupts.")?;
}
let steps = match options.mode {
Mode::Terminal { steps } => steps,
@ -257,7 +275,12 @@ pub fn execute(options: Options, writer: &mut impl Write) -> Result<(), Box<dyn
machine
.memory_mut()
.set_cartridge_hardware(options.hardware);
let report = run_bounded(&mut machine, steps);
let mut clock = if options.hardware == CartridgeHardware::Rtc {
Some(rtc_clock::RtcHostClock::new(machine.memory_mut())?)
} else {
None
};
let report = run_bounded_with_clock(&mut machine, steps, clock.as_mut())?;
write_report(writer, &machine, &report)?;
writer.flush()?;
if let Reason::Diagnostic(error) = report.reason {

View file

@ -0,0 +1,122 @@
//! Host-only clock adapter. UTC is sampled once; later changes use monotonic elapsed seconds.
use gba_core::{
cartridge::{RtcDateTime, RtcError},
memory::Memory,
};
use std::{
io,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
const UNIX_2000: u64 = 946_684_800;
pub(crate) struct RtcHostClock {
started: Instant,
supplied: u64,
}
impl RtcHostClock {
pub(crate) fn new(memory: &mut Memory) -> io::Result<Self> {
let unix = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(io::Error::other)?
.as_secs();
Self::from_unix_seconds(memory, unix).map_err(io::Error::other)
}
fn from_unix_seconds(memory: &mut Memory, unix: u64) -> Result<Self, RtcError> {
let seconds = unix
.checked_sub(UNIX_2000)
.ok_or(RtcError::InvalidDateTime)?;
memory.set_rtc_datetime(RtcDateTime::from_seconds_since_2000(seconds)?)?;
Ok(Self {
started: Instant::now(),
supplied: 0,
})
}
pub(crate) fn sync(&mut self, memory: &mut Memory) -> Result<(), RtcError> {
self.supply(memory, self.started.elapsed())
}
fn supply(&mut self, memory: &mut Memory, elapsed: Duration) -> Result<(), RtcError> {
let seconds = elapsed.as_secs();
// Ignore a backwards test/source sample without moving the high-water mark.
if seconds > self.supplied {
memory.advance_rtc_seconds(seconds - self.supplied)?;
self.supplied = seconds;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use gba_core::{cartridge::CartridgeHardware, io::HALTCNT};
fn memory() -> Memory {
let mut memory = Memory::new(vec![0; 4]).unwrap();
memory.set_cartridge_hardware(CartridgeHardware::Rtc);
memory
}
#[test]
fn epoch_seed_is_utc_and_range_checked_without_changing_state_on_error() {
let mut memory = memory();
RtcHostClock::from_unix_seconds(&mut memory, UNIX_2000).unwrap();
assert_eq!(
memory.rtc_datetime().unwrap().components(),
[0, 1, 1, 6, 0, 0, 0]
);
for invalid in [UNIX_2000 - 1, UNIX_2000 + 3_155_760_000, u64::MAX] {
assert!(RtcHostClock::from_unix_seconds(&mut memory, invalid).is_err());
assert_eq!(
memory.rtc_datetime().unwrap().components(),
[0, 1, 1, 6, 0, 0, 0]
);
}
}
#[test]
fn elapsed_seconds_are_supplied_once_preserve_guest_time_and_continue_in_stop() {
let mut memory = memory();
let mut clock = RtcHostClock::from_unix_seconds(&mut memory, UNIX_2000).unwrap();
for ms in [999, 1000, 1000, 700, 1999, 2000] {
clock
.supply(&mut memory, Duration::from_millis(ms))
.unwrap();
}
assert_eq!(
memory.rtc_datetime().unwrap().components(),
[0, 1, 1, 6, 0, 0, 2]
);
memory
.set_rtc_datetime(RtcDateTime::new([24, 2, 29, 3, 23, 59, 59]).unwrap())
.unwrap();
memory.write8(HALTCNT, 128).unwrap();
clock.supply(&mut memory, Duration::from_secs(3)).unwrap();
assert_eq!(
memory.rtc_datetime().unwrap().components(),
[24, 3, 1, 4, 0, 0, 0]
);
assert!(memory.stopped());
assert_eq!(memory.cycles(), 0);
}
#[test]
fn failed_tick_does_not_lose_elapsed_seconds() {
let mut memory = memory();
let mut clock = RtcHostClock::from_unix_seconds(&mut memory, UNIX_2000).unwrap();
memory.set_cartridge_hardware(CartridgeHardware::None);
assert_eq!(
clock.supply(&mut memory, Duration::from_secs(5)),
Err(RtcError::NotAttached)
);
memory.set_cartridge_hardware(CartridgeHardware::Rtc);
clock.supply(&mut memory, Duration::from_secs(5)).unwrap();
assert_eq!(
memory.rtc_datetime().unwrap().components(),
[0, 1, 1, 0, 0, 0, 5]
);
}
}

View file

@ -50,6 +50,11 @@ impl Session {
self.machine.memory_mut().set_cartridge_hardware(hardware);
}
/// Host adapters may supply independent cartridge time between execution slices.
pub fn memory_mut(&mut self) -> &mut gba_core::memory::Memory {
self.machine.memory_mut()
}
pub fn frame(&self) -> &Framebuffer {
&self.frame
}

View file

@ -13,6 +13,13 @@ pub fn run(
) -> Result<(), Box<dyn Error>> {
let mut session = Session::new(bytes)?;
session.set_cartridge_hardware(hardware);
let mut rtc_clock = if hardware == gba_core::cartridge::CartridgeHardware::Rtc {
Some(crate::cartridge::rtc_clock::RtcHostClock::new(
session.memory_mut(),
)?)
} else {
None
};
writeln!(
writer,
"ROM window: Arrows=D-pad; Z/X=A/B; Q/W=L/R; Enter=Start; Backspace=Select; Escape exits."
@ -38,6 +45,9 @@ pub fn run(
// Show a black buffer and pump initial events before boot starts.
window.update_with_buffer(session.frame().pixels(), WIDTH, HEIGHT)?;
while window.is_open() && !window.is_key_down(Key::Escape) {
if let Some(clock) = rtc_clock.as_mut() {
clock.sync(session.memory_mut())?;
}
let buttons = read_buttons(window.is_active(), |key| window.is_key_down(key));
let update = session.update(buttons)?;
let stopped = update == Update::Stopped;

View file

@ -125,7 +125,7 @@ fn run() -> Result<(), Box<dyn Error>> {
--rom PATH --steps COUNT Run a raw ROM in the terminal (1..=100000000 steps)\n\
--rom PATH --window Open a raw ROM with keyboard input\n\
--frames COUNT Exit ROM window after 1..=100000 captured frames\n\
--rtc Select RTC GPIO/control subset for --rom (no calendar yet)\n\
--rtc Select cartridge RTC (UTC startup, host elapsed time)\n\
--test-suite PATH.json Run bounded ROM assertions; write a JSON report\n\
--cpu-demo Run the terminal-only ARM/Thumb instruction demo\n\
--timer-demo Run the timer IRQ demo with nominal cycle costs\n\

View file

@ -84,6 +84,64 @@ fn rtc_setup() -> Vec<u32> {
]
}
fn rtc_calendar_setup() -> Vec<u32> {
// Original unrolled ARM GPIO driver. Write 2024-02-29 12:34:56, then read the hour.
// Keep executable instructions past the GPIO overlay at ROM offsets c4..c9.
let mut code = vec![0xe1a00000; 64];
code[0] = 0xea00003e; // B 0x08000100
code.extend([0xe59f1000, 0xea000000, 0x080000c4]); // LDR r1; skip literal.
fn store(code: &mut Vec<u32>, value: u32, offset: u32) {
code.extend([0xe3a00000 | value, 0xe1c100b0 | offset]);
}
fn send(code: &mut Vec<u32>, byte: u8, command: bool) {
for bit in 0..8 {
let shift = if command { 7 - bit } else { bit };
let pins = 4 | (u32::from((byte >> shift) & 1) << 1);
store(code, pins, 0);
store(code, pins | 1, 0);
}
}
store(&mut code, 1, 4); // Read enable.
store(&mut code, 1, 0);
store(&mut code, 7, 2);
store(&mut code, 5, 0);
send(&mut code, 0x64, true);
for byte in [0x24, 2, 0x29, 4, 0x12, 0x34, 0x56] {
send(&mut code, byte, false);
}
store(&mut code, 1, 0); // End write and begin time read.
store(&mut code, 5, 0);
send(&mut code, 0x67, true);
store(&mut code, 5, 2);
code.push(0xe3a02000); // MOV r2,#0
for bit in 0..8 {
store(&mut code, 4, 0);
store(&mut code, 5, 0);
code.extend([0xe1d130b0, 0xe1a030a3, 0xe2033001, 0xe1822003 | (bit << 7)]);
}
store(&mut code, 1, 0); // Aborting the remaining read bytes preserves calendar state.
code.push(0xeafffffe);
code
}
#[test]
fn rtc_calendar_commands_run_through_original_arm_code_with_host_clock_enabled() {
let fixture = Fixture::new();
let path = fixture.rom(&rtc_calendar_setup());
let output = command()
.arg("--rom")
.arg(&path)
.args(["--rtc", "--steps", "5000"])
.output()
.unwrap();
assert!(output.status.success(), "{}", stderr(&output));
assert!(
stdout(&output).contains("r2=0x00000092"),
"{}",
stdout(&output)
);
}
#[test]
fn rtc_selection_is_explicit_and_does_not_modify_the_rom_file() {
let fixture = Fixture::new();
@ -100,7 +158,7 @@ fn rtc_selection_is_explicit_and_does_not_modify_the_rom_file() {
.output()
.unwrap();
assert!(selected.status.success(), "{}", stderr(&selected));
assert!(stdout(&selected).contains("RTC selected: GPIO and command/control only"));
assert!(stdout(&selected).contains("RTC selected: UTC at startup"));
assert!(stdout(&selected).contains("r2=0x00000001"));
assert_eq!(fs::read(&path).unwrap(), original);
let duplicate = command()
@ -298,6 +356,15 @@ fn native_rom_window_presents_file_bytes_and_reports_stop_cpu_and_video_errors()
assert!(rtc_output.status.success(), "{}", stderr(&rtc_output));
assert!(stdout(&rtc_output).contains("Captured ROM frames: 3"));
assert!(stdout(&rtc_output).contains("r2=0x00000001"));
let calendar_path = fixture.rom(&rtc_calendar_setup());
let calendar_output = window(&calendar_path, true);
assert!(
calendar_output.status.success(),
"{}",
stderr(&calendar_output)
);
assert!(stdout(&calendar_output).contains("Captured ROM frames: 3"));
assert!(stdout(&calendar_output).contains("r2=0x00000092"));
for (code, error) in [
(vec![0xef03_0000, 0xeaff_fffe], "entered STOP"),
(vec![0xee00_0000], "instruction"),