#![cfg(any(
feature = "esp32",
feature = "esp32c3",
feature = "esp32c6",
feature = "esp32s3",
feature = "esp32p4",
feature = "esp32s31"
))]
use crate::backend::EspChip;
use esp_soc::{Soc, Stop};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DebugStop {
Running,
Stepped,
Halted,
Breakpoint(u32),
Trapped,
Reset,
Stopped,
}
impl From<Stop> for DebugStop {
fn from(stop: Stop) -> Self {
match stop {
Stop::MaxInsns => DebugStop::Running,
Stop::Halted => DebugStop::Halted,
Stop::Breakpoint(pc) => DebugStop::Breakpoint(pc),
Stop::SwReset => DebugStop::Reset,
Stop::Unimplemented(..) | Stop::Ebreak(_) => DebugStop::Trapped,
_ => DebugStop::Stopped,
}
}
}
pub trait Rv32Chip: Soc + Sized {
fn register_file(machine: &esp_soc::Machine<Self>) -> Option<[u32; 33]>;
fn call_state(machine: &mut esp_soc::Machine<Self>) -> Option<(&mut [u32; 32], &mut u32)>;
}
#[cfg(any(
feature = "esp32c3",
feature = "esp32c6",
feature = "esp32p4",
feature = "esp32s31"
))]
macro_rules! rv32_registers {
($chip:ty) => {
impl Rv32Chip for $chip {
fn register_file(machine: &esp_soc::Machine<Self>) -> Option<[u32; 33]> {
let core = machine.cores.first()?;
let mut file = [0u32; 33];
file[..32].copy_from_slice(&core.x);
file[32] = core.pc;
Some(file)
}
fn call_state(
machine: &mut esp_soc::Machine<Self>,
) -> Option<(&mut [u32; 32], &mut u32)> {
let core = machine.cores.first_mut()?;
Some((&mut core.x, &mut core.pc))
}
}
};
}
#[cfg(feature = "esp32c3")]
rv32_registers!(esp32c3::C3);
#[cfg(feature = "esp32c6")]
rv32_registers!(esp32c6::C6);
#[cfg(feature = "esp32p4")]
rv32_registers!(esp32p4::P4);
#[cfg(feature = "esp32s31")]
rv32_registers!(esp32s31::S31);
pub trait GdbTarget {
fn pc(&self) -> Option<u32>;
fn register_file(&self) -> Option<[u32; 33]> {
None
}
fn read_memory(&mut self, addr: u32, len: usize) -> Vec<u8>;
fn arm_breakpoint(&mut self, addr: u32);
fn run_batch(&mut self, steps: u64) -> DebugStop;
fn step_once(&mut self) -> DebugStop;
}
impl<S: Rv32Chip> GdbTarget for EspChip<S> {
fn pc(&self) -> Option<u32> {
S::register_file(self.machine_ref()).map(|file| file[32])
}
fn register_file(&self) -> Option<[u32; 33]> {
S::register_file(self.machine_ref())
}
fn read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
if len == 0 {
return Vec::new();
}
let start = addr & !3;
let skip = (addr - start) as usize;
let words = (skip + len).div_ceil(4);
let text = self.machine_mut().peek(start, words);
let mut bytes = Vec::with_capacity(words * 4);
for line in text.lines() {
let Some((_, word)) = line.split_once(": ") else {
break;
};
let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
break;
};
bytes.extend_from_slice(&word.to_le_bytes());
}
if bytes.len() < skip {
return Vec::new();
}
let end = (skip + len).min(bytes.len());
bytes[skip..end].to_vec()
}
fn arm_breakpoint(&mut self, addr: u32) {
self.break_at(addr);
}
fn run_batch(&mut self, steps: u64) -> DebugStop {
EspChip::run(self, steps).into()
}
fn step_once(&mut self) -> DebugStop {
match EspChip::run(self, 1) {
Stop::MaxInsns => DebugStop::Stepped,
other => other.into(),
}
}
}
pub struct DebugSession<'a, S: Soc> {
chip: &'a mut EspChip<S>,
last_stop: Option<DebugStop>,
}
impl<'a, S: Soc> DebugSession<'a, S> {
pub fn new(chip: &'a mut EspChip<S>) -> Self {
Self {
chip,
last_stop: None,
}
}
pub fn report(&mut self) -> String {
let mut out = String::new();
for line in self.chip.reports() {
out.push_str(&line);
if !line.ends_with('\n') {
out.push('\n');
}
}
out.push_str(&self.chip.registers());
out.push_str(&format!("last stop: {}\n", self.stop_label()));
out
}
pub fn peek(&mut self, addr: u32, words: usize) -> String {
self.chip.machine_mut().peek(addr, words)
}
pub fn disasm(&mut self, addr: u32, count: usize) -> String {
self.chip.disassemble(addr, count)
}
pub fn run(&mut self, steps: u64) -> DebugStop {
let stop = EspChip::run(self.chip, steps).into();
self.last_stop = Some(stop);
stop
}
pub fn break_at(&mut self, addr: u32) {
self.chip.break_at(addr);
}
fn stop_label(&self) -> String {
match self.last_stop {
None => "not run".into(),
Some(DebugStop::Running) => "still running (step budget spent)".into(),
Some(DebugStop::Stepped) => "single step".into(),
Some(DebugStop::Halted) => "halted".into(),
Some(DebugStop::Breakpoint(pc)) => format!("breakpoint at {pc:#010x}"),
Some(DebugStop::Trapped) => "trap".into(),
Some(DebugStop::Reset) => "chip reset".into(),
Some(DebugStop::Stopped) => "stopped".into(),
}
}
}
#[cfg(any(feature = "esp32", feature = "esp32s3"))]
pub(crate) trait XtensaChip: Soc + Sized {
fn call_guest(chip: &mut EspChip<Self>, address: u32) -> Result<u32, String>;
}
#[cfg(any(feature = "esp32", feature = "esp32s3"))]
macro_rules! xtensa_call_guest {
($chip:ty) => {
impl XtensaChip for $chip {
fn call_guest(chip: &mut EspChip<Self>, address: u32) -> Result<u32, String> {
const SENTINEL: u32 = 0x4000_0000;
const CALLINC: u32 = 2 << 16;
const CALLINC_MASK: u32 = 3 << 16;
const WOE: u32 = 1 << 18;
const RETURN_TAG: u32 = 2 << 30;
const BUDGET: u64 = 2_000_000;
let machine = chip.machine_mut();
let Some(core) = machine.cores.first_mut() else {
return Err("this chip has no core to call into".into());
};
let saved = core.clone();
core.ps = (core.ps & !CALLINC_MASK) | CALLINC | WOE;
core.waiting = false;
core.set_ar(8, RETURN_TAG | (SENTINEL & 0x3fff_ffff));
core.pc = address;
let mark = machine.observers.len();
machine.add_observer(Box::new(esp_soc::observers::Breakpoints {
pcs: vec![SENTINEL],
}));
let stop = machine.run(BUDGET);
machine.observers.truncate(mark);
let value = machine.cores.first().map(|core| core.get_ar(10));
if let Some(core) = machine.cores.first_mut() {
*core = saved;
}
match stop {
Stop::Breakpoint(pc) if pc == SENTINEL => {
value.ok_or_else(|| "the core disappeared during the call".to_string())
}
other => Err(format!(
"the call at 0x{address:08x} did not return: {other:?}"
)),
}
}
}
};
}
#[cfg(feature = "esp32")]
xtensa_call_guest!(esp32::Esp32);
#[cfg(feature = "esp32s3")]
xtensa_call_guest!(esp32s3::S3);
#[cfg(any(
feature = "esp32c3",
feature = "esp32c6",
feature = "esp32p4",
feature = "esp32s31"
))]
pub(crate) fn rv32_call_guest<S: Rv32Chip>(
chip: &mut EspChip<S>,
address: u32,
) -> Result<u32, String> {
const BUDGET: u64 = 2_000_000;
let machine = chip.machine_mut();
let (saved, sentinel) = match S::call_state(machine) {
Some((registers, pc)) => (registers.to_owned(), *pc),
None => return Err("this chip has no RV32 core to call into".into()),
};
{
let (registers, pc) = S::call_state(machine).expect("checked above");
registers[1] = sentinel; *pc = address;
}
let mark = machine.observers.len();
machine.add_observer(Box::new(esp_soc::observers::Breakpoints {
pcs: vec![sentinel],
}));
let stop = machine.run(BUDGET);
machine.observers.truncate(mark);
let value = S::call_state(machine).map(|(registers, _)| registers[10]);
if let Some((registers, pc)) = S::call_state(machine) {
registers.copy_from_slice(&saved);
*pc = sentinel;
}
match stop {
esp_soc::soc::Stop::Breakpoint(_) => {
value.ok_or_else(|| "the core disappeared during the call".to_string())
}
other => Err(format!(
"the call at 0x{address:08x} did not return: {other:?}"
)),
}
}