ch32rv 0.44.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
//! en: `gdb` (docs/cli.ja.md §4.6): a GDB Remote Serial Protocol server, on TCP or on
//! stdin/stdout (`--pipe`). It is one of the probe's broker's clients (a monitor open on the same
//! probe keeps streaming), attaches without modifying flash, and offers `load` (vFlash) and the
//! `monitor` commands GDB front ends send to OpenOCD. Started with OpenOCD's arguments it acts as
//! OpenOCD's GDB server (see [`crate::openocd`]).
//! ja: `gdb`。TCP か stdin/stdout(`--pipe`)の GDB Remote Serial Protocol server。probe の
//! ブローカーの client(同じ probe の monitor は流れ続ける)。attach で flash を書き換えず、`load`
//! (vFlash)と GDB の front end が OpenOCD に送る `monitor` コマンドを受ける。OpenOCD の引数で
//! 起動すると OpenOCD の GDB server として動く。

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 {
    // en: Always a broker's client - an OEP probe's, or the WCH-Link's (started when none runs) -
    // so that a monitor on the same probe (the IDE keeps one open while debugging) and the
    // session share it.
    // ja: 常にブローカーの client(OEP の probe か WCH-Link。無ければ起動)。同じ probe の monitor
    // (IDE はデバッグ中も開いたまま)と共有する。
    let a = match route(cli) {
        Ok(a) => a,
        Err(c) => return c,
    };
    crate::oep::gdb(cli, args, &a)
}

/// en: The probe the session goes to. With no `--probe`, the only debug probe there is, of
/// either kind (a WCH-Link in RISC-V mode, or an OEP probe on USB); several are refused with the
/// list. ja: 行き先の probe。`--probe` が無ければ、ある debug probe が 1 つならそれ(WCH-Link か OEP)。
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();
        // The OEP probes are the project's VID:PID only (oep-transports §3), one line each.
        let oep: Vec<String> = crate::oep::oep_devices()
            .iter()
            .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)))
}

/// en: Where GDB is: one TCP connection, or the pipe GDB started us on (stdin/stdout).
/// ja: GDB の居場所。TCP の接続 1 つか、GDB が起動したパイプ(stdin/stdout)。
pub(crate) enum Peer {
    Tcp(TcpStream),
    Pipe,
}

/// en: Bind `--listen`, say where, and wait for the one GDB connection; with `--pipe`, GDB is on
/// stdin/stdout already. With `--reset-halt` the caller then resets the target and holds it at
/// its reset vector before serving GDB.
/// ja: `--listen` で待ち受け、場所を出し、GDB の接続を 1 つ待つ。`--pipe` なら GDB は既に
/// stdin/stdout に居る。`--reset-halt` なら呼び出し側が reset して止めてから相手をする。
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 {
        // en: The line OpenOCD prints, which GDB front ends (cortex-debug) wait for.
        // ja: OpenOCD が出す行。GDB の front end(cortex-debug)はこれを待つ。
        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))
}

/// en: Serve one GDB session on `stream` until the client leaves, then take out every flash
/// breakpoint (so an interrupted session never leaves an `ebreak` in flash). The caller detaches.
/// ja: `stream` で GDB の session を 1 つ、client が抜けるまで。最後に flash の breakpoint を
/// すべて外す(途中で切れても flash に `ebreak` を残さない)。detach は呼び出し側。
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
        }
        // GDB that started us on a pipe leaves by closing it.
        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,
        ),
    }
}

/// en: A gdbstub Connection over a TCP stream, or over stdin/stdout (a reader thread feeds stdin
/// in, so that a peek does not block). ja: TCP か stdin/stdout の Connection(stdin は読む thread 経由)。
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),
                }
            }
        }
    }
}

/// The blocking event loop: after `resume`, poll the core's halt state while watching for
/// incoming GDB data (Ctrl-C). When the core halts (an `ebreak` breakpoint, or a step
/// completing), report a SwBreak/DoneStep stop.
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 {
            // Incoming data (e.g. Ctrl-C) takes priority.
            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)),
            }
            // Poll the core.
            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> {
        // Halt the running core in response to Ctrl-C, then report SIGINT.
        target.halt()?;
        Ok(Some(SingleThreadStopReason::Signal(
            gdbstub::common::Signal::SIGINT,
        )))
    }
}