ch32rv 0.20.2

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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! en: `capabilities` (docs/cli.ja.md §4.10): the probe x firmware x target x operation matrix -
//! what this exact setup can do, and why. Attaches to read the live probe variant and target
//! family, then reports each operation as supported/unsupported with a reason. There is no
//! `tool supports LinkE` boolean; every operation carries its own gated reason.
//! ja: `capabilities`。probe × FW × target × operation の可否 matrix。attach して probe variant と
//! target family を読み、各 operation の可否と理由を出す。

use std::process::ExitCode;
use std::time::Duration;

use ch32rv_contract::{ErrorKind, ProbeMode, ResultEnvelope};
use ch32rv_wchlink::Variant;

use crate::args::Cli;
use crate::cmd_probe::{fail, mode_str, select_entry};
use crate::parse;
use crate::session::Session;

/// One capability row: an operation, whether it is supported here, and why.
struct Cap {
    op: &'static str,
    supported: bool,
    reason: String,
}

impl Cap {
    fn yes(op: &'static str, reason: impl Into<String>) -> Self {
        Cap {
            op,
            supported: true,
            reason: reason.into(),
        }
    }
    fn no(op: &'static str, reason: impl Into<String>) -> Self {
        Cap {
            op,
            supported: false,
            reason: reason.into(),
        }
    }
}

pub fn capabilities(cli: &Cli) -> ExitCode {
    const CMD: &str = "capabilities";
    match crate::oep::addr(cli, CMD) {
        Ok(Some(a)) => return oep_capabilities(cli, CMD, &a),
        Ok(None) => {}
        Err(c) => return c,
    }
    let entry = match select_entry(cli, CMD) {
        Ok(e) => e,
        Err(code) => return code,
    };
    if entry.mode != ProbeMode::Riscv {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!(
                "probe is in {} mode; the RISC-V capability matrix needs RISC-V mode",
                mode_str(entry.mode)
            ),
            None,
        );
    }
    // `--chip` plans statically (probe info + named chip, no target needed); otherwise attach and
    // read the live target.
    if let Some(chip) = cli.chip.as_deref() {
        static_capabilities(cli, CMD, &entry, chip)
    } else {
        live_capabilities(cli, CMD, &entry)
    }
}

/// en: The matrix for an OEP probe: attach without halting, then read what the probe declares
/// (riscv-dm ops, console mechanisms, a fixture UART, port_speed) and what ch32rv builds on
/// them. ja: OEP の probe の表。止めずに attach し、probe の宣言(riscv-dm の ops、console の
/// mechanism、fixture UART、port_speed)と ch32rv がその上で組むものを出す。
fn oep_capabilities(cli: &Cli, cmd: &str, a: &crate::oep::OepAddr) -> ExitCode {
    use ch32rv_oep::registry::{core as oep_core, target_console, target_riscv_dm};
    crate::oep::with_attached(cli, cmd, a, false, |x| {
        let family = x.family.clone().unwrap_or_else(|| "unknown".to_owned());
        let sku =
            x.chip_id.and_then(
                |id| match ch32rv_target::Db::builtin().resolve_by_chip_id(id) {
                    ch32rv_target::Resolution::Sku(s) => Some(s.sku.clone()),
                    _ => None,
                },
            );
        let p = x.t.probe();
        let text = |tlvs: &[ch32rv_oep::codec::Tlv], tag: u8| {
            tlvs.iter()
                .find(|t| t.tag == tag)
                .map(|t| String::from_utf8_lossy(&t.value).into_owned())
        };
        let core = p.describe(oep_core::FN).unwrap_or_default();
        let model = text(&core, oep_core::tlvs::describe::MODEL).unwrap_or_else(|| "OEP".into());
        let fw = text(&core, oep_core::tlvs::describe::FIRMWARE).unwrap_or_default();
        // Optional ops are declared by each fn's ops tag (core §1.2, §7.4).
        let port_speed = p
            .interface(ch32rv_oep::registry::probe_link::NAME)
            .and_then(|i| p.ops(i.func))
            .ok()
            .flatten()
            .is_some_and(|o| o.contains(&ch32rv_oep::registry::probe_link::op::PORT_SPEED));
        let dm_ops = p
            .interface(target_riscv_dm::NAME)
            .and_then(|i| p.ops(i.func))
            .ok()
            .flatten()
            .unwrap_or_default();
        let blocks = [
            target_riscv_dm::op::READ_BLOCK,
            target_riscv_dm::op::WRITE_BLOCK,
        ]
        .iter()
        .all(|op| dm_ops.contains(op));
        let run = dm_ops.contains(&target_riscv_dm::op::RUN);
        let mechanisms: Vec<u8> = p
            .interface(target_console::NAME)
            .and_then(|i| p.describe(i.func))
            .ok()
            .and_then(|d| {
                d.iter()
                    .find(|t| t.tag == target_console::tlvs::describe::MECHANISMS)
                    .map(|t| t.value.clone())
            })
            .unwrap_or_default();
        let fixture_uart = p
            .interface(ch32rv_oep::registry::fixture_uart::NAME)
            .is_ok();
        let profile = ch32rv_flash::flash_controller_profile_for(&family);
        let mech = |m: u8, op: &'static str, what: &str| {
            if mechanisms.contains(&m) {
                Cap::yes(op, format!("the probe's console carries {what}"))
            } else {
                Cap::no(op, format!("the probe's console does not declare {what}"))
            }
        };
        let mut caps = vec![
            Cap::yes("connect", "attached through the probe (its slot or wire)"),
            if blocks && run {
                Cap::yes(
                    "flash",
                    "ch32rv's RAM loader through the probe's block and run ops",
                )
            } else {
                Cap::no(
                    "flash",
                    "the probe declares no read_block / write_block / run",
                )
            },
            match profile {
                Some(pr) => Cap::yes(
                    "erase / option bytes / recover unprotect",
                    format!(
                        "the FLASH controller over the Debug Module ({}-byte page)",
                        pr.page_size
                    ),
                ),
                None => Cap::no(
                    "erase / option bytes / recover unprotect",
                    "no FLASH-controller profile for this family",
                ),
            },
            Cap::yes(
                "gdb HW breakpoints",
                "detected at gdb attach (V4C/V4F have 4 trigger slots; V2/V3/V4B have 0)",
            ),
            mech(
                target_console::enums::mechanism::DMSEQ,
                "monitor dmseq",
                "dmseq",
            ),
            mech(
                target_console::enums::mechanism::DMDATA,
                "monitor dmdata",
                "dmdata",
            ),
            mech(target_console::enums::mechanism::SDI, "monitor sdi", "SDI"),
            if blocks {
                Cap::yes("monitor rtt", "host-side RTT over the probe's block ops")
            } else {
                Cap::no("monitor rtt", "the probe declares no block ops")
            },
            if fixture_uart {
                Cap::yes("monitor fixture-uart", "the probe has oep.fixture.uart")
            } else {
                Cap::no("monitor fixture-uart", "the probe has no oep.fixture.uart")
            },
            Cap::no(
                "recover power-off / nrst / unbrick",
                "WCH-Link commands; an OEP probe has no target power switch or NRST erase for ch32rv yet",
            ),
        ];
        if port_speed {
            caps.push(Cap::yes(
                "port_speed",
                "the broker raises a UART bridge's link (921600, 750000, 500000)",
            ));
        }
        report(
            cli,
            cmd,
            &model,
            &fw,
            &family,
            sku.as_deref(),
            &caps,
            false,
            Vec::new(),
        )
    })
}

/// Attach and report the matrix for the connected target.
fn live_capabilities(cli: &Cli, cmd: &str, entry: &crate::cmd_probe::Entry) -> ExitCode {
    let (speed, mut warnings) = match parse::speed(&cli.speed) {
        Ok(v) => v,
        Err(msg) => return fail(cli, cmd, ErrorKind::Usage, msg, None),
    };
    let timeout = Duration::from_millis(cli.timeout.map(|s| s * 1000).unwrap_or(3000));
    let session = match Session::attach(
        entry,
        speed,
        timeout,
        Duration::from_secs(cli.lock_timeout),
        cli.chip.as_deref(),
        cli.db.as_deref(),
        &mut warnings,
    ) {
        Ok(s) => s,
        Err(e) => return crate::cmd_probe::session_error(cli, cmd, e),
    };
    let fw = format!(
        "{}.{:02}",
        session.probe_info.fw_major, session.probe_info.fw_minor
    );
    let db = ch32rv_target::Db::builtin();
    let (sku, series) = match db.resolve_by_chip_id(session.attach.chip_id) {
        ch32rv_target::Resolution::Sku(s) => (Some(s.sku.clone()), Some(s.series.clone())),
        _ => (None, None),
    };
    let wiring = series.as_deref().and_then(ch32rv_target::debug_wiring);
    let caps = build_matrix(
        &session.probe_info.variant,
        session.attach.family_byte,
        wiring.as_ref(),
    );
    report(
        cli,
        cmd,
        &session.probe_info.variant.name(),
        &fw,
        &session.family(),
        sku.as_deref(),
        &caps,
        false,
        warnings,
    )
}

/// Report the matrix for a `--chip`-named target from the probe info alone (no attach).
fn static_capabilities(
    cli: &Cli,
    cmd: &str,
    entry: &crate::cmd_probe::Entry,
    chip: &str,
) -> ExitCode {
    let info = match ch32rv_wchlink::WchLink::open(&entry.dev).and_then(|mut l| l.probe_info()) {
        Ok(i) => i,
        Err(e) => {
            return fail(
                cli,
                cmd,
                ErrorKind::DeviceOpenFailed,
                format!("reading probe info failed: {e}"),
                None,
            );
        }
    };
    let Some(family_byte) = crate::cmd_flash::family_byte_from_name(chip) else {
        return fail(
            cli,
            cmd,
            ErrorKind::Usage,
            format!("unknown --chip {chip:?} (not a known family)"),
            Some("see `ch32rv db list` for known SKUs/families"),
        );
    };
    // A representative SKU (for the series' debug wiring).
    let db = ch32rv_target::Db::builtin();
    let (sku, series) = db
        .skus()
        .iter()
        .find(|s| {
            s.sku.eq_ignore_ascii_case(chip)
                || s.family.eq_ignore_ascii_case(chip)
                || s.series.eq_ignore_ascii_case(chip)
        })
        .map(|s| (Some(s.sku.clone()), Some(s.series.clone())))
        .unwrap_or((None, None));
    let wiring = series.as_deref().and_then(ch32rv_target::debug_wiring);
    let caps = build_matrix(&info.variant, family_byte, wiring.as_ref());
    let family = ch32rv_wchlink::family_name(family_byte)
        .unwrap_or(chip)
        .to_owned();
    let fw = format!("{}.{:02}", info.fw_major, info.fw_minor);
    report(
        cli,
        cmd,
        &info.variant.name(),
        &fw,
        &family,
        sku.as_deref(),
        &caps,
        true,
        Vec::new(),
    )
}

/// Print/emit the capability report (shared by the live and static paths).
#[allow(clippy::too_many_arguments)]
fn report(
    cli: &Cli,
    cmd: &str,
    probe_name: &str,
    fw: &str,
    family: &str,
    sku: Option<&str>,
    caps: &[Cap],
    static_mode: bool,
    warnings: Vec<ch32rv_contract::Warning>,
) -> ExitCode {
    if cli.json {
        let mut env = ResultEnvelope::success(cmd);
        env.result = Some(serde_json::json!({
            "probe": probe_name,
            "firmware": fw,
            "family": family,
            "sku": sku,
            "planned": static_mode,
            "capabilities": caps.iter().map(|c| serde_json::json!({
                "op": c.op, "supported": c.supported, "reason": c.reason,
            })).collect::<Vec<_>>(),
        }));
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        println!("probe:   {probe_name} (fw {fw})");
        println!(
            "target:  {family}{}{}",
            sku.map(|s| format!(" / {s}")).unwrap_or_default(),
            if static_mode {
                "  (planned from --chip)"
            } else {
                ""
            }
        );
        println!("---");
        for c in caps {
            println!(
                "  [{}] {:<28} {}",
                if c.supported { "yes" } else { "NO " },
                c.op,
                c.reason
            );
        }
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        ExitCode::SUCCESS
    }
}

/// Compute the operation matrix from the probe variant + target family/wiring.
fn build_matrix(
    variant: &Variant,
    family_byte: u8,
    wiring: Option<&ch32rv_target::DebugWiring>,
) -> Vec<Cap> {
    let is_linke = matches!(variant, Variant::LinkE);
    let is_linke_or_w = matches!(variant, Variant::LinkE | Variant::LinkW);
    let one_wire = wiring.map(|w| w.wire == "1-wire").unwrap_or(false);
    let flash_ok = ch32rv_flash::params_for_family(family_byte).is_some();
    let ctrl = ch32rv_flash::flash_controller_profile(family_byte);

    let mut caps = Vec::new();

    // connect: the CH549 WCH-Link cannot drive a 1-wire SWIO target.
    if one_wire && !is_linke {
        caps.push(Cap::no(
            "connect",
            "target is 1-wire SWIO; only WCH-LinkE drives a single-wire target",
        ));
    } else {
        caps.push(Cap::yes(
            "connect",
            "the probe supports this target's debug wiring",
        ));
    }

    // flash: WCH's loader stub, or - for a family that has none - the FLASH controller over DMI.
    caps.push(if flash_ok {
        Cap::yes("flash", "a flash loader stub is available for this family")
    } else if ctrl.is_some() {
        Cap::yes(
            "flash",
            "no stub for this family - programmed via the direct FLASH controller (slower)",
        )
    } else {
        Cap::no(
            "flash",
            "no flash stub and no FLASH-controller profile for this family",
        )
    });

    // erase --range / --sector / gdb flash software breakpoints (direct FLASH controller).
    caps.push(match &ctrl {
        Some(p) => Cap::yes(
            "erase --range / flash-bp",
            format!(
                "direct FLASH controller ({}-byte page, {:?})",
                p.page_size, p.mode
            ),
        ),
        None => Cap::no(
            "erase --range / flash-bp",
            "no capture-verified FLASH-controller profile for this family",
        ),
    });

    // gdb HW breakpoints are detected live at attach (V4C/V4F expose 4 triggers, older cores 0).
    caps.push(Cap::yes(
        "gdb HW breakpoints",
        "detected at gdb attach (V4C/V4F have 4 trigger slots; V2/V3/V4B have 0)",
    ));

    // SDI print forwarding is a WCH-LinkE feature.
    caps.push(if is_linke {
        Cap::yes("monitor sdi", "SDI print forwarding (WCH-LinkE)")
    } else {
        Cap::no(
            "monitor sdi",
            "SDI print forwarding is WCH-LinkE only; use `monitor --source dmdata`",
        )
    });

    // dmdata/rtt monitoring is host-side over DMI - any probe.
    caps.push(Cap::yes(
        "monitor dmdata",
        "host polls the DM data mailbox over DMI (any probe)",
    ));

    // power-off / nrst recovery erase needs target-power control (LinkE/LinkW).
    caps.push(if is_linke_or_w {
        Cap::yes("recover power-off", "target-power erase (WCH-LinkE/LinkW)")
    } else {
        Cap::no(
            "recover power-off",
            "power-off erase needs a probe that controls target power (LinkE/LinkW)",
        )
    });

    caps
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    use super::*;

    fn wiring(wire: &str) -> ch32rv_target::DebugWiring {
        ch32rv_target::DebugWiring {
            wire: wire.to_owned(),
            swdio: "PD1".to_owned(),
            swclk: "-".to_owned(),
        }
    }
    fn cap<'a>(caps: &'a [Cap], op: &str) -> &'a Cap {
        caps.iter().find(|c| c.op == op).expect("cap present")
    }

    #[test]
    fn ch549_cannot_drive_1wire_target() {
        // CH32V003 (0x09) is 1-wire; on a CH549 probe, connect must be unsupported.
        let caps = build_matrix(&Variant::Ch549, 0x09, Some(&wiring("1-wire")));
        assert!(!cap(&caps, "connect").supported);
        // ...but a LinkE drives it fine.
        let caps = build_matrix(&Variant::LinkE, 0x09, Some(&wiring("1-wire")));
        assert!(cap(&caps, "connect").supported);
    }

    #[test]
    fn sdi_and_poweroff_are_linke_only() {
        let ch549 = build_matrix(&Variant::Ch549, 0x01, Some(&wiring("2-wire")));
        assert!(!cap(&ch549, "monitor sdi").supported);
        assert!(!cap(&ch549, "recover power-off").supported);
        let linke = build_matrix(&Variant::LinkE, 0x01, Some(&wiring("2-wire")));
        assert!(cap(&linke, "monitor sdi").supported);
        assert!(cap(&linke, "recover power-off").supported);
    }

    #[test]
    fn erase_range_follows_the_controller_profile() {
        // L103 (0x0E) has a profile; an unsupported family (0x00) does not.
        assert!(
            cap(
                &build_matrix(&Variant::LinkE, 0x0E, None),
                "erase --range / flash-bp"
            )
            .supported
        );
        assert!(
            !cap(
                &build_matrix(&Variant::LinkE, 0x00, None),
                "erase --range / flash-bp"
            )
            .supported
        );
    }
}