ch32rv 0.48.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! 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::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
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 shutdown = target.shutdown_flag();
    let gdb = GdbStub::new(Conn {
        inner: conn,
        shutdown: shutdown.clone(),
    });
    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
        }
        // `monitor shutdown` ends the session once its answer is out.
        Err(e) if shutdown.load(Ordering::SeqCst) && e.is_connection_error() => {
            eprintln!("gdb: shutdown (monitor shutdown)");
            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,
        }
    }
}

/// en: The connection the stub uses: GDB's, ended by `monitor shutdown` (the read after the
/// answer reports the connection closed). ja: stub が使う接続。`monitor shutdown` の答えの後の
/// 読みで「閉じた」と返して session を終える。
struct Conn {
    inner: GdbConn,
    shutdown: Arc<AtomicBool>,
}

impl Conn {
    fn ended(&self) -> Result<(), std::io::Error> {
        if self.shutdown.load(Ordering::SeqCst) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::ConnectionAborted,
                "monitor shutdown",
            ));
        }
        Ok(())
    }
}

impl Connection for Conn {
    type Error = std::io::Error;

    fn write(&mut self, byte: u8) -> Result<(), Self::Error> {
        self.inner.write(byte)
    }
    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        self.inner.write_all(buf)
    }
    fn flush(&mut self) -> Result<(), Self::Error> {
        self.inner.flush()
    }
}

impl ConnectionExt for Conn {
    fn read(&mut self) -> Result<u8, Self::Error> {
        self.ended()?;
        self.inner.read()
    }
    fn peek(&mut self) -> Result<Option<u8>, Self::Error> {
        self.ended()?;
        self.inner.peek()
    }
}

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 = Conn;
    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,
        )))
    }
}