use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::ExitCode;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::time::Duration;
use ch32rv_contract::ErrorKind;
use ch32rv_debug::Ch32Target;
use gdbstub::conn::{Connection, ConnectionExt};
use gdbstub::stub::run_blocking::{BlockingEventLoop, Event, WaitForStopReasonError};
use gdbstub::stub::{DisconnectReason, GdbStub, SingleThreadStopReason};
use gdbstub::target::Target;
use crate::args::{Cli, GdbArgs};
use crate::cmd_probe::{fail, fail_with_candidates, mode_str, select_entry};
use crate::oep::OepAddr;
pub fn gdb(cli: &Cli, args: &GdbArgs) -> ExitCode {
let a = match route(cli) {
Ok(a) => a,
Err(c) => return c,
};
crate::oep::gdb(cli, args, &a)
}
fn route(cli: &Cli) -> Result<OepAddr, ExitCode> {
const CMD: &str = "gdb";
if let Some(a) = crate::oep::addr(cli, CMD)? {
return Ok(a);
}
if cli.probe.is_none() {
let wch: Vec<_> = crate::cmd_probe::wch_devices()
.unwrap_or_default()
.into_iter()
.filter(|e| e.mode == ch32rv_contract::ProbeMode::Riscv)
.collect();
let oep: Vec<String> = ch32rv_usb::enumerate()
.unwrap_or_default()
.iter()
.filter(|d| crate::oep::oep_port(d).is_some())
.map(|d| format!("oep://{}", crate::oep::probe_id(d)))
.collect();
match (wch.len(), oep.as_slice()) {
(0, [one]) => {
return crate::oep::resolve_oep_url(one)
.map_err(|m| fail(cli, CMD, ErrorKind::DeviceNotFound, m, None));
}
(0, []) => {
return Err(fail(
cli,
CMD,
ErrorKind::DeviceNotFound,
"no debug probe found (a WCH-Link in RISC-V mode, or an OEP probe)",
Some("run `ch32rv probe list` to see available probes"),
));
}
(1, []) => {}
_ => {
let mut candidates: Vec<serde_json::Value> = wch
.iter()
.map(|e| {
serde_json::json!({
"address": format!("wchlink://{}", e.dev.serial().unwrap_or_default()),
})
})
.collect();
candidates.extend(oep.iter().map(|a| serde_json::json!({ "address": a })));
return Err(fail_with_candidates(
cli,
CMD,
ErrorKind::DeviceAmbiguous,
"more than one debug probe is connected; name one",
Some("give --probe <address> (one of the candidates)"),
candidates,
));
}
}
}
let entry = select_entry(cli, CMD)?;
if entry.mode != ch32rv_contract::ProbeMode::Riscv {
return Err(fail(
cli,
CMD,
ErrorKind::CapabilityUnsupported,
format!(
"gdb needs a RISC-V-mode probe (this is {})",
mode_str(entry.mode)
),
None,
));
}
Ok(OepAddr::Wch(crate::broker::BrokerTarget::wch(&entry)))
}
pub(crate) enum Peer {
Tcp(TcpStream),
Pipe,
}
pub(crate) fn listen(cli: &Cli, args: &GdbArgs) -> Result<Peer, ExitCode> {
const CMD: &str = "gdb";
if args.no_flash {
eprintln!("gdb: --no-flash: vFlash (load) is not offered");
}
if args.pipe {
eprintln!("gdb: serving GDB on stdin/stdout");
return Ok(Peer::Pipe);
}
let listener = TcpListener::bind(&args.listen).map_err(|e| {
fail(
cli,
CMD,
ErrorKind::Usage,
format!("bind {}: {e}", args.listen),
None,
)
})?;
let local = listener
.local_addr()
.map(|a| a.to_string())
.unwrap_or_else(|_| args.listen.clone());
if args.openocd {
let port = listener.local_addr().map(|a| a.port()).unwrap_or(0);
eprintln!("Info : Listening on port {port} for gdb connections");
}
eprintln!("gdb: listening on {local} (connect with: target remote {local})");
let (stream, peer) = listener
.accept()
.map_err(|e| fail(cli, CMD, ErrorKind::Usage, format!("accept: {e}"), None))?;
eprintln!("gdb: client connected from {peer}");
Ok(Peer::Tcp(stream))
}
pub(crate) fn run_session<T: ch32rv_dmi::DtmAccess>(
cli: &Cli,
target: &mut Ch32Target<T>,
peer: Peer,
) -> ExitCode {
const CMD: &str = "gdb";
let hw = target.hw_trigger_count();
let flash_bp = target.flash_breakpoints_supported();
eprintln!(
"gdb: attached, {hw} hardware breakpoint slot(s){}",
if hw > 0 {
" (plain `break` on flash auto-uses a hardware trigger)".to_owned()
} else if flash_bp {
" (no trigger module; plain `break` on flash rewrites the flash page - flash wear; \
`set breakpoint always-inserted on` reduces it; one page rewrite takes about 2 s, \
so give GDB `set remotetimeout 10`)"
.to_owned()
} else {
" (no trigger module and no verified flash profile; RAM software breakpoints only)"
.to_owned()
}
);
let conn = match peer {
Peer::Tcp(s) => GdbConn::Tcp(s),
Peer::Pipe => GdbConn::pipe(),
};
let piped = matches!(conn, GdbConn::Pipe { .. });
let gdb = GdbStub::new(conn);
let outcome = gdb.run_blocking::<Ch32EventLoop<T>>(target);
for page in target.restore_flash_breakpoints() {
eprintln!(
"gdb: warning: could not restore the flash page at 0x{page:08x}; it may still hold a \
breakpoint (an `ebreak`) - flash the image again"
);
}
match outcome {
Ok(reason) => {
match reason {
DisconnectReason::Disconnect => eprintln!("gdb: client disconnected"),
DisconnectReason::TargetExited(c) => eprintln!("gdb: target exited ({c})"),
DisconnectReason::TargetTerminated(s) => {
eprintln!("gdb: target terminated (signal {s:?})")
}
DisconnectReason::Kill => eprintln!("gdb: session killed"),
}
ExitCode::SUCCESS
}
Err(e) if piped && e.is_connection_error() => {
eprintln!("gdb: GDB closed the pipe");
ExitCode::SUCCESS
}
Err(e) => fail(
cli,
CMD,
ErrorKind::Internal,
format!("gdb session error: {e}"),
None,
),
}
}
enum GdbConn {
Tcp(TcpStream),
Pipe {
rx: Receiver<Vec<u8>>,
buf: VecDeque<u8>,
closed: bool,
},
}
impl GdbConn {
fn pipe() -> Self {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut stdin = std::io::stdin();
let mut b = [0u8; 4096];
loop {
match stdin.read(&mut b) {
Ok(0) | Err(_) => break,
Ok(n) => {
if tx.send(b[..n].to_vec()).is_err() {
break;
}
}
}
}
});
GdbConn::Pipe {
rx,
buf: VecDeque::new(),
closed: false,
}
}
}
fn eof() -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "GDB closed the pipe")
}
impl Connection for GdbConn {
type Error = std::io::Error;
fn write(&mut self, byte: u8) -> Result<(), Self::Error> {
self.write_all(&[byte])
}
fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
match self {
GdbConn::Tcp(s) => Write::write_all(s, buf),
GdbConn::Pipe { .. } => std::io::stdout().lock().write_all(buf),
}
}
fn flush(&mut self) -> Result<(), Self::Error> {
match self {
GdbConn::Tcp(s) => Write::flush(s),
GdbConn::Pipe { .. } => std::io::stdout().lock().flush(),
}
}
}
impl ConnectionExt for GdbConn {
fn read(&mut self) -> Result<u8, Self::Error> {
match self {
GdbConn::Tcp(s) => {
s.set_nonblocking(false)?;
let mut b = [0u8; 1];
s.read_exact(&mut b)?;
Ok(b[0])
}
GdbConn::Pipe { rx, buf, closed } => loop {
if let Some(b) = buf.pop_front() {
return Ok(b);
}
if *closed {
return Err(eof());
}
match rx.recv() {
Ok(v) => buf.extend(v),
Err(_) => *closed = true,
}
},
}
}
fn peek(&mut self) -> Result<Option<u8>, Self::Error> {
match self {
GdbConn::Tcp(s) => {
s.set_nonblocking(true)?;
let mut b = [0u8; 1];
let r = match TcpStream::peek(s, &mut b) {
Ok(0) => Ok(None),
Ok(_) => Ok(Some(b[0])),
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(None),
Err(e) => Err(e),
};
let _ = s.set_nonblocking(false);
r
}
GdbConn::Pipe { rx, buf, closed } => {
loop {
match rx.try_recv() {
Ok(v) => buf.extend(v),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => {
*closed = true;
break;
}
}
}
match buf.front() {
Some(b) => Ok(Some(*b)),
None if *closed => Err(eof()),
None => Ok(None),
}
}
}
}
}
enum Ch32EventLoop<T: ch32rv_dmi::DtmAccess> {
_Never(core::convert::Infallible, core::marker::PhantomData<T>),
}
impl<T: ch32rv_dmi::DtmAccess> BlockingEventLoop for Ch32EventLoop<T> {
type Target = Ch32Target<T>;
type Connection = GdbConn;
type StopReason = SingleThreadStopReason<u32>;
fn wait_for_stop_reason(
target: &mut Self::Target,
conn: &mut Self::Connection,
) -> Result<
Event<Self::StopReason>,
WaitForStopReasonError<
<Self::Target as Target>::Error,
<Self::Connection as Connection>::Error,
>,
> {
loop {
match conn.peek() {
Ok(Some(_)) => {
let b =
ConnectionExt::read(conn).map_err(WaitForStopReasonError::Connection)?;
return Ok(Event::IncomingData(b));
}
Ok(None) => {}
Err(e) => return Err(WaitForStopReasonError::Connection(e)),
}
match target.is_halted() {
Ok(true) => return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(()))),
Ok(false) => std::thread::sleep(Duration::from_millis(5)),
Err(e) => return Err(WaitForStopReasonError::Target(e)),
}
}
}
fn on_interrupt(
target: &mut Self::Target,
) -> Result<Option<Self::StopReason>, <Self::Target as Target>::Error> {
target.halt()?;
Ok(Some(SingleThreadStopReason::Signal(
gdbstub::common::Signal::SIGINT,
)))
}
}