ch32rv 0.4.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! en: `target info` (docs/cli.ja.md §4.3): attach, read the chip signature and factory
//! UUID/flash size, and detach. Read-only: nothing is written to the target, and the core is
//! always released (detach) on drop of the session, on every path. The LinkE corrupted-readback
//! bug is detected and recovered inside the shared session (board-identify, measured).
//! ja: `target info`。attach → chip 署名と工場 UUID・flash 容量の読み取り → detach。
//! 読み取り専用で、session の drop 時に必ず detach する。LinkE の壊れ読み値バグは共通 session で復旧。

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

use ch32rv_contract::{ErrorKind, ProbeMode, ResultEnvelope, TargetReport, Warning};

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

const CMD: &str = "target.info";

pub fn info(cli: &Cli) -> ExitCode {
    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; attaching to a target requires RISC-V mode",
                mode_str(entry.mode)
            ),
            Some("switch to RISC-V mode with `ch32rv probe mode set riscv` (WCH-LinkE only)"),
        );
    }
    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(),
        &mut warnings,
    ) {
        Ok(s) => s,
        Err(e) => return crate::cmd_probe::session_error(cli, CMD, e),
    };

    let mut probe_report = base_report(&entry);
    apply_probe_info(&mut probe_report, &session.probe_info, &mut warnings);

    let family = session.family();
    if family.starts_with("unknown") {
        warnings.push(Warning {
            code: "family-unknown".to_owned(),
            msg: format!(
                "family byte 0x{:02x} is not in the known table (possibly a gap series) - worth recording for data request 0001",
                session.attach.family_byte
            ),
        });
    }
    // Resolve the SKU from the live chip_id against the generated DB (device_ids join, rev [7:4]
    // masked). Fail-closed: an unknown or cross-family-ambiguous id shows no SKU rather than a guess.
    let db = ch32rv_target::Db::builtin();
    let resolution = db.resolve_by_chip_id(session.attach.chip_id);
    let (sku, sku_verified, sku_line): (Option<String>, Option<bool>, String) = match &resolution {
        ch32rv_target::Resolution::Sku(s) => (
            Some(s.sku.clone()),
            Some(s.verified),
            format!(
                "{} ({})",
                s.sku,
                if s.verified {
                    "verified on silicon"
                } else {
                    "generated DB, datasheet reference"
                }
            ),
        ),
        ch32rv_target::Resolution::Family(fam, cands) => {
            let names: Vec<&str> = cands.iter().map(|c| c.sku.as_str()).collect();
            warnings.push(Warning {
                code: "sku-ambiguous".to_owned(),
                msg: format!(
                    "chip_id matches {} SKUs in family {fam}: {} - pass --chip to disambiguate",
                    cands.len(),
                    names.join(", ")
                ),
            });
            (
                None,
                None,
                format!("- ({} candidates in {fam})", cands.len()),
            )
        }
        ch32rv_target::Resolution::Unknown => {
            warnings.push(Warning {
                code: "sku-unknown".to_owned(),
                msg: format!(
                    "chip_id 0x{:08x} is not in the generated DB (a gap-series or new part) - worth recording for data request 0001",
                    session.attach.chip_id
                ),
            });
            (None, None, "- (chip_id not in DB)".to_owned())
        }
    };

    // Debug wiring (1-wire SWIO vs 2-wire RVSWD) for the resolved series (data request 0002).
    let wiring = match &resolution {
        ch32rv_target::Resolution::Sku(s) => ch32rv_target::debug_wiring(&s.series),
        _ => None,
    };

    let chip = session.chip;
    let target = TargetReport {
        sku,
        family: Some(family),
        chip_id: Some(format!("0x{:08x}", session.attach.chip_id)),
        uid: chip.as_ref().map(|c| hex(&c.uuid)),
        verified: sku_verified,
        provisional: None,
        protected: None,
        flash_bytes: chip.as_ref().map(|c| c.flash_bytes),
    };

    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.probe = Some(probe_report);
        env.result = Some(serde_json::json!({
            "protection_raw": chip.as_ref().map(|c| hex(&c.protection_raw)),
            "chip_id_echo": chip.as_ref().map(|c| format!("0x{:08x}", c.chip_id_echo)),
            "debug_wiring": wiring.as_ref().map(|w| serde_json::json!({
                "wire": w.wire, "swdio": w.swdio, "swclk": w.swclk,
            })),
        }));
        env.target = Some(target);
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        print_probe_human(&probe_report);
        println!("---");
        println!("family:   {}", target.family.as_deref().unwrap_or("-"));
        println!(
            "chip id:  {}  (bits [7:4] = silicon revision)",
            target.chip_id.as_deref().unwrap_or("-")
        );
        println!("uid:      {}", target.uid.as_deref().unwrap_or("-"));
        match target.flash_bytes {
            Some(b) => println!("flash:    {} KiB", b / 1024),
            None => println!("flash:    -"),
        }
        println!("sku:      {sku_line}");
        if let Some(w) = &wiring {
            println!(
                "debug:    {} (SWDIO/DAT={}{})",
                w.wire,
                w.swdio,
                if w.swclk == "-" {
                    String::new()
                } else {
                    format!(", SWCLK={}", w.swclk)
                }
            );
        }
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        ExitCode::SUCCESS
    }
}

/// en: `target option get` (docs/cli.ja.md §4.3): read the option bytes (0x1FFF_F800, 16 bytes)
/// over DMI and decode the common fields (read protection, the USER byte's IWDG/STOP/STANDBY
/// bits, the Data0/Data1 user bytes, and the WRP write-protect mask). Read-only. Family-specific
/// USER bits need the generated target DB, so the raw bytes are always shown and the structured
/// decode is marked interim.
/// ja: `target option get`。option bytes(0x1FFF_F800、16 byte)を DMI で読み、共通フィールド
/// (読み出し保護・USER の IWDG/STOP/STANDBY・Data0/Data1・WRP)を復号。読み取り専用。family 固有の
/// USER ビットは DB 生成後。生バイトは常に表示し、構造化復号は暫定扱い。
pub fn option_get(cli: &Cli) -> ExitCode {
    const CMD: &str = "target.option.get";
    const OPTION_BASE: u32 = 0x1FFF_F800;
    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; attaching to a target requires RISC-V mode",
                mode_str(entry.mode)
            ),
            None,
        );
    }
    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 mut session = match Session::attach(
        &entry,
        speed,
        timeout,
        Duration::from_secs(cli.lock_timeout),
        cli.chip.as_deref(),
        &mut warnings,
    ) {
        Ok(s) => s,
        Err(e) => return crate::cmd_probe::session_error(cli, CMD, e),
    };

    let family = session.family();
    // Resolve the DB family from the live chip_id (e.g. family_byte 0x06 -> "CH32V30x", but the DB
    // and option-field tables key on "CH32V307"): use the DB family when a SKU resolves.
    let db = ch32rv_target::Db::builtin();
    let db_family = match db.resolve_by_chip_id(session.attach.chip_id) {
        ch32rv_target::Resolution::Sku(s) => s.family.clone(),
        ch32rv_target::Resolution::Family(fam, _) => fam,
        ch32rv_target::Resolution::Unknown => family.clone(),
    };
    let user_fields = ch32rv_target::option_user_fields(&db_family);
    let mut dm = session.dm();
    if let Err(e) = dm.halt() {
        return fail(
            cli,
            CMD,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        );
    }
    let raw = match dm.read_mem(OPTION_BASE, 16) {
        Ok(v) => v,
        Err(e) => {
            return fail(
                cli,
                CMD,
                ErrorKind::TransferFailed,
                format!("reading option bytes failed: {e}"),
                None,
            );
        }
    };

    // Layout (STM32F1-style, shared by CH32V0/V1/V2/V3/X0): each logical byte is stored with its
    // complement. [0]=RDPR [2]=USER [4]=Data0 [6]=Data1 [8/10/12/14]=WRPR0..3.
    let rdpr = raw[0];
    let user = raw[2];
    let data0 = raw[4];
    let data1 = raw[6];
    let wrpr = u32::from(raw[8])
        | u32::from(raw[10]) << 8
        | u32::from(raw[12]) << 16
        | u32::from(raw[14]) << 24;
    // RDPR == 0xA5 means read-out protection disabled (the factory/unprotected value).
    let unprotected = rdpr == 0xA5;

    // USER byte: decode per the family's named bits from the generated DB (request 0003). When the
    // family is not in the DB, fall back to the common STM32F1-style bits and flag it interim.
    let user_bits: Vec<(String, u8)> = if user_fields.is_empty() {
        [(0u8, "IWDGSW"), (1, "nRST_STOP"), (2, "nRST_STDBY")]
            .iter()
            .map(|(bit, name)| ((*name).to_owned(), (user >> bit) & 1))
            .collect()
    } else {
        user_fields
            .iter()
            .map(|f| (f.field.clone(), (user >> f.bit) & 1))
            .collect()
    };
    if user_fields.is_empty() {
        warnings.push(Warning {
            code: "option-decode-interim".to_owned(),
            msg: format!(
                "USER-byte fields for {db_family} are not in the DB; decoded with the common STM32F1-style bits only (data request 0003)"
            ),
        });
    }
    let user_str = user_bits
        .iter()
        .map(|(name, v)| format!("{name}={v}"))
        .collect::<Vec<_>>()
        .join("  ");

    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        let user_json: serde_json::Map<String, serde_json::Value> = user_bits
            .iter()
            .map(|(name, v)| (name.clone(), serde_json::json!(*v == 1)))
            .collect();
        env.result = Some(serde_json::json!({
            "family": family,
            "db_family": db_family,
            "raw": hex(&raw),
            "read_protected": !unprotected,
            "rdpr": format!("0x{rdpr:02x}"),
            "user": format!("0x{user:02x}"),
            "user_bits": user_json,
            "data0": format!("0x{data0:02x}"),
            "data1": format!("0x{data1:02x}"),
            "wrpr": format!("0x{wrpr:08x}"),
            "write_protected": wrpr != 0xFFFF_FFFF,
        }));
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        println!("family:          {family}");
        println!("raw:             {}", hex(&raw));
        println!(
            "read protection: {}  (RDPR=0x{rdpr:02x}{})",
            if unprotected { "off" } else { "ON" },
            if unprotected {
                ", 0xA5=unprotected"
            } else {
                ""
            }
        );
        println!("user (0x{user:02x}):     {user_str}");
        println!("data0/data1:     0x{data0:02x} / 0x{data1:02x}");
        println!(
            "write protect:   0x{wrpr:08x}  ({})",
            if wrpr == 0xFFFF_FFFF {
                "none (all pages writable)"
            } else {
                "some pages write-protected"
            }
        );
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        ExitCode::SUCCESS
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

const OPTION_BASE: u32 = 0x1FFF_F800;

/// Confirm a destructive option-byte write: `--yes` skips it, `--non-interactive` without `--yes`
/// refuses, otherwise prompt on the terminal.
fn ob_confirm(cli: &Cli, prompt: &str) -> bool {
    use std::io::Write;
    if cli.yes {
        return true;
    }
    if cli.non_interactive {
        return false;
    }
    eprint!("{prompt} [y/N] ");
    let _ = std::io::stderr().flush();
    let mut s = String::new();
    let _ = std::io::stdin().read_line(&mut s);
    matches!(s.trim(), "y" | "Y" | "yes" | "YES")
}

/// Parse exactly 16 hex bytes (optionally space/`:`-separated) for `option write-raw`.
fn parse_hex16(s: &str) -> Result<[u8; 16], String> {
    let clean: String = s
        .chars()
        .filter(|c| !c.is_whitespace() && *c != ':' && *c != '_')
        .collect();
    if clean.len() != 32 || !clean.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(format!(
            "expected 16 hex bytes (32 hex digits), got {} digit(s)",
            clean.len()
        ));
    }
    let mut out = [0u8; 16];
    for (i, byte) in out.iter_mut().enumerate() {
        *byte = u8::from_str_radix(&clean[i * 2..i * 2 + 2], 16).map_err(|e| e.to_string())?;
    }
    Ok(out)
}

/// en: Read the 16 option bytes plus the DB family string (for USER-field names) - attach, halt,
/// read, detach. ja: 16 byte の option bytes と DB family(USER field 名用)を読む。
fn read_option_bytes(cli: &Cli, cmd: &str) -> Result<(String, [u8; 16]), ExitCode> {
    let mut session = crate::cmd_probe::attach(cli, cmd)?;
    let db = ch32rv_target::Db::builtin();
    let db_family = match db.resolve_by_chip_id(session.attach.chip_id) {
        ch32rv_target::Resolution::Sku(s) => s.family.clone(),
        ch32rv_target::Resolution::Family(fam, _) => fam,
        ch32rv_target::Resolution::Unknown => session.family(),
    };
    let mut dm = session.dm();
    dm.halt().map_err(|e| {
        fail(
            cli,
            cmd,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        )
    })?;
    let v = dm.read_mem(OPTION_BASE, 16).map_err(|e| {
        fail(
            cli,
            cmd,
            ErrorKind::TransferFailed,
            format!("reading option bytes failed: {e}"),
            None,
        )
    })?;
    let mut a = [0u8; 16];
    a.copy_from_slice(&v[..16]);
    Ok((db_family, a))
}

/// en: Erase + program the 16 option bytes to `new` (value+complement pairs, as `option get`
/// returns), then read back and verify. `new[0]` (RDPR) is programmed first so read protection is
/// re-established immediately. The bytes take effect after a system reset. ja: option bytes を
/// `new` へ erase+program し read-back で検証。RDPR を最初に書く。反映は system reset 後。
fn program_option(cli: &Cli, cmd: &str, new: &[u8; 16]) -> ExitCode {
    let mut session = match crate::cmd_probe::attach(cli, cmd) {
        Ok(s) => s,
        Err(c) => return c,
    };
    let family = session.family();
    let mut dm = session.dm();
    if let Err(e) = dm.halt() {
        return fail(
            cli,
            cmd,
            ErrorKind::AttachFailed,
            format!("halt failed: {e}"),
            None,
        );
    }
    let before = match dm.read_mem(OPTION_BASE, 16) {
        Ok(v) => v,
        Err(e) => {
            return fail(
                cli,
                cmd,
                ErrorKind::TransferFailed,
                format!("reading option bytes failed: {e}"),
                None,
            );
        }
    };
    if let Err(e) = dm.flash_program_option_bytes(new) {
        return fail(
            cli,
            cmd,
            ErrorKind::TransferFailed,
            format!(
                "programming option bytes failed: {e} - the target may be left with erased (read-protected) option bytes; recover with `ch32rv recover`"
            ),
            None,
        );
    }
    let after = match dm.read_mem(OPTION_BASE, 16) {
        Ok(v) => v,
        Err(e) => {
            return fail(
                cli,
                cmd,
                ErrorKind::TransferFailed,
                format!("verify read failed: {e}"),
                None,
            );
        }
    };
    // Verify the value bytes (even indices) we asked for actually landed. The flash write itself
    // lands immediately (the values only *take effect* after a reset), so a readback mismatch is a
    // genuine write failure - fail with verify-mismatch (exit 30), like flash/verify/write.
    if let Some(i) = (0..16).step_by(2).find(|&i| after[i] != new[i]) {
        return fail(
            cli,
            cmd,
            ErrorKind::VerifyMismatch,
            format!(
                "option byte {i} reads back 0x{:02x}, not the requested 0x{:02x} (before={}, after={})",
                after[i],
                new[i],
                hex(&before),
                hex(&after)
            ),
            Some("the write did not take; check the target is not write-protected"),
        );
    }
    if cli.json {
        let mut env = ResultEnvelope::success(cmd);
        env.result = Some(serde_json::json!({
            "family": family,
            "before": hex(&before),
            "after": hex(&after),
            "verified": true,
            "note": "option bytes take effect after a power-on / system reset",
        }));
        crate::print_envelope(&env)
    } else {
        println!(
            "option bytes: {} -> {} ({family})",
            hex(&before),
            hex(&after)
        );
        println!("note: option bytes take effect after a power-on / system reset");
        ExitCode::SUCCESS
    }
}

/// `target option write-raw <hex>`: overwrite the 16 option bytes with a raw value (expert).
pub fn option_write_raw(cli: &Cli, hexstr: &str) -> ExitCode {
    const CMD: &str = "target.option.write-raw";
    let bytes = match parse_hex16(hexstr) {
        Ok(b) => b,
        Err(m) => {
            return fail(
                cli,
                CMD,
                ErrorKind::Usage,
                m,
                Some("e.g. a55aff00ff00ff00ff00ff00ff00ff00 (16 bytes: RDPR nRDPR USER nUSER ...)"),
            );
        }
    };
    if bytes[0] != 0xA5
        && !ob_confirm(
            cli,
            &format!(
                "RDPR byte is 0x{:02x} (not 0xA5): this ENABLES read protection - flash becomes unreadable until you unprotect (which erases it). Continue?",
                bytes[0]
            ),
        )
    {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            "aborted: RDPR would enable read protection (pass --yes to force)",
            None,
        );
    }
    if !ob_confirm(cli, "Overwrite the target's option bytes?") {
        return fail(cli, CMD, ErrorKind::Usage, "aborted (no --yes)", None);
    }
    program_option(cli, CMD, &bytes)
}

/// `target option reset`: restore factory-default option bytes (RDPR off, USER/Data/WRP cleared).
pub fn option_reset(cli: &Cli) -> ExitCode {
    const CMD: &str = "target.option.reset";
    // RDPR=0xA5 (unprotected), USER/Data0/Data1/WRPR0..3 = 0xff, each followed by its complement.
    let defaults: [u8; 16] = [
        0xA5, 0x5A, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
        0x00,
    ];
    if !ob_confirm(
        cli,
        "Restore factory-default option bytes (RDPR off, USER/Data/WRP cleared)?",
    ) {
        return fail(cli, CMD, ErrorKind::Usage, "aborted (no --yes)", None);
    }
    program_option(cli, CMD, &defaults)
}

/// en: `target option set <key=value ...>`: read-modify-write named option fields. Keys: a USER
/// bit field name from the DB (per family, e.g. `IWDGSW=0`), `rdp=on|off`, `data0=<hex>`,
/// `data1=<hex>`. Complement bytes are recomputed. `rdp=off` triggers a full mass erase.
/// ja: `target option set <key=value ...>`。DB の USER bit 名(family 別)/`rdp`/`data0`/`data1` を
/// read-modify-write。補数は再計算。`rdp=off` は全消去を伴う。
pub fn option_set(cli: &Cli, kv: &[String]) -> ExitCode {
    const CMD: &str = "target.option.set";
    let (db_family, mut ob) = match read_option_bytes(cli, CMD) {
        Ok(v) => v,
        Err(c) => return c,
    };
    let fields = ch32rv_target::option_user_fields(&db_family);
    let mut changes: Vec<String> = Vec::new();
    let mut mass_erase = false;
    let mut protect_on = false;

    for pair in kv {
        let Some((key, val)) = pair.split_once('=') else {
            return fail(
                cli,
                CMD,
                ErrorKind::Usage,
                format!("expected key=value, got {pair:?}"),
                Some("e.g. IWDGSW=0 rdp=off data0=0x42"),
            );
        };
        let key_l = key.to_ascii_lowercase();
        match key_l.as_str() {
            "rdp" | "protect" => match val.to_ascii_lowercase().as_str() {
                "off" | "0" | "none" => {
                    if ob[0] != 0xA5 {
                        mass_erase = true;
                    }
                    ob[0] = 0xA5;
                    changes.push("rdp=off".to_owned());
                }
                "on" | "1" => {
                    ob[0] = 0xFF;
                    protect_on = true;
                    changes.push("rdp=on".to_owned());
                }
                other => {
                    return fail(
                        cli,
                        CMD,
                        ErrorKind::Usage,
                        format!("rdp must be on/off, got {other:?}"),
                        None,
                    );
                }
            },
            "data0" | "data1" => {
                let Some(byte) = parse_u8(val) else {
                    return fail(
                        cli,
                        CMD,
                        ErrorKind::Usage,
                        format!("{key}: expected a byte 0..255 (e.g. 0x42), got {val:?}"),
                        None,
                    );
                };
                let idx = if key_l == "data0" { 4 } else { 6 };
                ob[idx] = byte;
                changes.push(format!("{key_l}=0x{byte:02x}"));
            }
            _ => {
                // A named USER-byte bit for this family.
                let Some(f) = fields.iter().find(|f| f.field.eq_ignore_ascii_case(key)) else {
                    let names: Vec<&str> = fields.iter().map(|f| f.field.as_str()).collect();
                    return fail(
                        cli,
                        CMD,
                        ErrorKind::Usage,
                        format!("unknown option field {key:?} for {db_family}"),
                        Some(&format!(
                            "known USER fields: {} (plus rdp, data0, data1)",
                            names.join(", ")
                        )),
                    );
                };
                let bit = match val {
                    "0" => 0u8,
                    "1" => 1,
                    other => {
                        return fail(
                            cli,
                            CMD,
                            ErrorKind::Usage,
                            format!("{key}: expected 0 or 1, got {other:?}"),
                            None,
                        );
                    }
                };
                if bit == 1 {
                    ob[2] |= 1 << f.bit;
                } else {
                    ob[2] &= !(1 << f.bit);
                }
                changes.push(format!("{}={bit}", f.field));
            }
        }
    }

    if changes.is_empty() {
        return fail(
            cli,
            CMD,
            ErrorKind::Usage,
            "no key=value pairs given".to_owned(),
            None,
        );
    }
    // Recompute every complement byte so the halfwords are valid regardless of what we touched.
    for i in (0..16).step_by(2) {
        ob[i + 1] = 0xFF ^ ob[i];
    }

    let prompt = if mass_erase {
        format!(
            "Apply option changes [{}]? rdp=off ERASES ALL FLASH (mass erase).",
            changes.join(", ")
        )
    } else if protect_on {
        format!(
            "Apply option changes [{}]? rdp=on makes the flash unreadable/undebuggable.",
            changes.join(", ")
        )
    } else {
        format!("Apply option changes [{}]?", changes.join(", "))
    };
    if !ob_confirm(cli, &prompt) {
        return fail(cli, CMD, ErrorKind::Usage, "aborted (no --yes)", None);
    }
    program_option(cli, CMD, &ob)
}

/// Parse a byte as decimal or `0x`-hex.
fn parse_u8(s: &str) -> Option<u8> {
    let s = s.trim();
    if let Some(h) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        u8::from_str_radix(h, 16).ok()
    } else {
        s.parse().ok()
    }
}

/// `target protect on|off`: enable/disable flash read protection (RDPR). Turning it OFF triggers a
/// full mass erase of the target's flash.
/// Emit a no-op success ("read protection is already <state>") that still produces a JSON envelope.
fn already_in_state(cli: &Cli, cmd: &str, protected: bool) -> ExitCode {
    if cli.json {
        let mut env = ResultEnvelope::success(cmd);
        env.result = Some(serde_json::json!({ "changed": false, "read_protected": protected }));
        crate::print_envelope(&env)
    } else {
        println!(
            "read protection is already {}",
            if protected { "ON" } else { "OFF" }
        );
        ExitCode::SUCCESS
    }
}

pub fn protect(cli: &Cli, state: SwitchState) -> ExitCode {
    const CMD: &str = "target.protect";
    let mut ob = match read_option_bytes(cli, CMD) {
        Ok((_family, b)) => b,
        Err(c) => return c,
    };
    match state {
        SwitchState::On => {
            if ob[0] != 0xA5 {
                return already_in_state(cli, CMD, true);
            }
            if !ob_confirm(
                cli,
                "Enable read protection? The flash becomes unreadable/undebuggable until you turn it OFF (which ERASES all flash).",
            ) {
                return fail(cli, CMD, ErrorKind::Usage, "aborted (no --yes)", None);
            }
            ob[0] = 0xFF;
            ob[1] = 0x00;
        }
        SwitchState::Off => {
            if ob[0] == 0xA5 {
                return already_in_state(cli, CMD, false);
            }
            if !ob_confirm(
                cli,
                "Disable read protection? This ERASES ALL FLASH (mass erase) on the target.",
            ) {
                return fail(cli, CMD, ErrorKind::Usage, "aborted (no --yes)", None);
            }
            ob[0] = 0xA5;
            ob[1] = 0x5A;
        }
    }
    program_option(cli, CMD, &ob)
}

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

    #[test]
    fn parses_16_contiguous_bytes() {
        let b = parse_hex16("a55aff00ff00ff00ff00ff00ff00ff00").unwrap();
        assert_eq!(b[0], 0xA5);
        assert_eq!(b[1], 0x5A);
        assert_eq!(b[15], 0x00);
    }

    #[test]
    fn accepts_separators() {
        let a = parse_hex16("a5:5a:ff:00:ff:00:ff:00:ff:00:ff:00:ff:00:ff:00").unwrap();
        let b = parse_hex16("a5 5a ff 00 ff 00 ff 00 ff 00 ff 00 ff 00 ff 00").unwrap();
        assert_eq!(a, b);
        assert_eq!(a[0], 0xA5);
    }

    #[test]
    fn rejects_wrong_length() {
        assert!(parse_hex16("abcd").is_err());
        assert!(parse_hex16("a55aff00ff00ff00ff00ff00ff00ff0000").is_err()); // 17 bytes
    }

    #[test]
    fn rejects_non_hex() {
        assert!(parse_hex16("zz5aff00ff00ff00ff00ff00ff00ff00").is_err());
    }
}