Skip to main content

ch32rv_debug/
server.rs

1//! en: A gdbstub `Target` for a CH32 RISC-V core reached over a [`DtmAccess`] transport.
2//! Supports registers, memory read/write, halt/continue/single-step, and breakpoints. A `break`
3//! GDB requests as software (Z0) is placed by the cheapest working mechanism, in order: a RAM
4//! `ebreak` memory-patch; else a hardware execute trigger when the core has a free slot (no
5//! wear); else a flash software breakpoint that rewrites the containing flash page (works on
6//! triggerless cores, at the cost of flash wear). Hardware breakpoints use the RISC-V trigger
7//! module (measured: 4 slots on QingKe V4F/CH32V307 and V4C/CH32X035, live-fire confirmed; 0 on
8//! V4B/CH32V203, V2A/CH32V003, V3/CH32V103 - detected dynamically). Flash software breakpoints
9//! need a verified FLASH-controller page profile; a family without one refuses them. Attach does not modify flash; flash breakpoints are removed and pages restored on
10//! detach (docs/cli.ja.md §4.6).
11//! ja: [`DtmAccess`] 上の CH32 RISC-V core 用 gdbstub Target。register・memory R/W・
12//! halt/continue/step・breakpoint。GDB が software(Z0)で要求した `break` は、動く中で最も安い
13//! 手段の順(RAM `ebreak` patch → 空き HW trigger〔摩耗なし〕→ flash page 書き換えの flash SW
14//! breakpoint〔trigger 無し core でも効くが flash 摩耗あり〕)で張る。hardware breakpoint は
15//! RISC-V trigger module(実測: V4F/V307・V4C/X035 は 4 slot 実発火、V4B/V203・V2A/V003・V3/V103 は
16//! 0。動的検出)。flash SW breakpoint は検証済み FLASH-controller profile が必要(無い family では
17//! 断る)。attach で flash を書き換えず、flash breakpoint は detach 時に外して
18//! page を復元する。
19
20use ch32rv_dmi::{DebugModule, DmiError, DtmAccess, FlashProgMode, RegName};
21use gdbstub::common::Signal;
22use gdbstub::target::ext::base::singlethread::{
23    SingleThreadBase, SingleThreadResume, SingleThreadResumeOps, SingleThreadSingleStep,
24    SingleThreadSingleStepOps,
25};
26use gdbstub::target::ext::breakpoints::{
27    Breakpoints, BreakpointsOps, HwBreakpoint, HwBreakpointOps, SwBreakpoint, SwBreakpointOps,
28};
29use gdbstub::target::ext::flash::{Flash, FlashOps};
30use gdbstub::target::ext::memory_map::{MemoryMap, MemoryMapOps};
31use gdbstub::target::ext::monitor_cmd::{ConsoleOutput, MonitorCmd, MonitorCmdOps, outputln};
32use gdbstub::target::ext::target_description_xml_override::{
33    TargetDescriptionXmlOverride, TargetDescriptionXmlOverrideOps,
34};
35use gdbstub::target::{Target, TargetError, TargetResult};
36
37use crate::arch::{Rv32, Rv32CoreRegs};
38
39/// A software breakpoint: the address and the original bytes we overwrote with `ebreak`.
40struct SwBp {
41    addr: u32,
42    original: Vec<u8>,
43}
44
45/// A hardware breakpoint: the trigger slot it occupies and the address it watches.
46struct HwBp {
47    slot: u32,
48    addr: u32,
49}
50
51/// A flash software breakpoint: an `ebreak` patched into flash-resident code by rewriting its
52/// page. `len` is the patched instruction size (2 for RVC, 4 otherwise).
53struct FlashBp {
54    addr: u32,
55    len: usize,
56}
57
58/// A flash page we manage: its pristine content (before any breakpoint) and what we last
59/// programmed into it, so repeated set/clear that yields identical content skips the rewrite.
60struct FlashPage {
61    page_addr: u32,
62    pristine: Vec<u8>,
63    current: Vec<u8>,
64}
65
66/// en: What only the session's owner can do to the target: reset it and write code flash. With
67/// one ([`Ch32Target::with_host`]) the server offers `load` (vFlash, with a memory map) and the
68/// `monitor` commands GDB front ends send to OpenOCD (`reset halt`, `halt`, `reset`, `resume`,
69/// `gdb_sync`).
70/// ja: session の持ち主にしかできないこと(target の reset と code flash の書き込み)。これがあると
71/// `load`(vFlash と memory map)と、GDB の front end が OpenOCD に送る `monitor` コマンドを受ける。
72pub trait Host<T> {
73    /// en: Reset the target; with `halt`, hold it at its reset vector. ja: reset。`halt` なら reset vector で止める。
74    fn reset(&mut self, dtm: &mut T, halt: bool) -> Result<(), String>;
75    /// en: Write `segments` (physical code-flash addresses, sorted, not overlapping) into code
76    /// flash, erasing the pages they touch. The hart is halted. ja: code flash へ書く(hart は停止中)。
77    fn program(&mut self, dtm: &mut T, segments: &[(u32, Vec<u8>)]) -> Result<(), String>;
78}
79
80/// en: Code flash as GDB's memory map shows it: `size` bytes at 0x0800_0000 and at its alias
81/// 0x0000_0000, erased in `block`-byte pages; everything else is RAM to GDB (SRAM, peripherals).
82/// ja: GDB の memory map での code flash。0x0800_0000 と別名の 0x0000_0000 に `size` バイト、消去単位は
83/// `block`。ほかは GDB には RAM(SRAM、周辺)。
84#[derive(Debug, Clone, Copy)]
85pub struct FlashMap {
86    pub size: u32,
87    pub block: u32,
88}
89
90/// en: gdbstub target that OWNS its transport `T` (owning, not borrowing, keeps the type free
91/// of a lifetime so it fits `BlockingEventLoop::Target`). Recover the transport with
92/// [`Ch32Target::into_inner`] to detach cleanly afterwards.
93/// ja: transport `T` を所有する gdbstub target(所有にすることでライフタイムが付かず
94/// `BlockingEventLoop::Target` に収まる)。後始末は [`Ch32Target::into_inner`] で回収する。
95pub struct Ch32Target<T: DtmAccess> {
96    dtm: T,
97    breakpoints: Vec<SwBp>,
98    hw_breakpoints: Vec<HwBp>,
99    hw_trigger_count: u32,
100    /// Number of integer GPRs the core exposes: 16 on RV32E (misa.E, e.g. CH32V003), else 32.
101    /// Reading a non-existent GPR via an abstract command raises cmderr, so we must not touch
102    /// x16..x31 on an RV32E hart.
103    gpr_count: u8,
104    /// Fast-page size for flash software breakpoints, or None when this family's FLASH-controller
105    /// profile is not verified (so a flash breakpoint is refused rather than risked).
106    flash_page_size: Option<u32>,
107    /// The family's fast-program mechanism (meaningful only when `flash_page_size` is Some).
108    flash_prog_mode: FlashProgMode,
109    flash_bps: Vec<FlashBp>,
110    flash_pages: Vec<FlashPage>,
111    /// en: DATA0 / DATA1 as the hart left them when it stopped. Register and memory access go
112    /// through DATA0, which is also a DM console's mailbox (dmdata / dmseq): a value left there
113    /// with bit 7 set reads to a dmseq target as its own frame still posted and to the host as an
114    /// invalid word, and the console stops for good (measured on a CH32X035 behind an OEP probe).
115    /// Put back just before the hart runs again.
116    /// ja: hart が止まった時の DATA0 / DATA1。register と memory は DATA0 を通すが、DATA0 は DM の
117    /// console の mailbox でもあり、bit 7 の立った値が残ると dmseq の target は自分のフレームがまだ
118    /// あると読み、host は無効な語と読んで、console が止まったままになる(OEP の probe の X035 で実測)。
119    /// 走らせる直前に戻す。
120    mailbox: Option<(u32, u32)>,
121    host: Option<(Box<dyn Host<T>>, FlashMap)>,
122    /// vFlashWrite data waiting for vFlashDone (physical addresses).
123    pending_flash: Vec<(u32, Vec<u8>)>,
124    /// `monitor gdb_sync`: the next step reports a stop without stepping (as OpenOCD does).
125    sync: bool,
126}
127
128impl<T: DtmAccess> Ch32Target<T> {
129    /// en: Find a free hardware trigger slot (none used twice). Returns None when the core has
130    /// no trigger module or all slots are taken.
131    /// ja: 空いている HW trigger slot を探す。trigger 無し/全 slot 使用中なら None。
132    fn alloc_hw_slot(&self) -> Option<u32> {
133        (0..self.hw_trigger_count).find(|s| !self.hw_breakpoints.iter().any(|b| b.slot == *s))
134    }
135
136    /// en: Wrap a transport and halt the core so GDB attaches to a stopped target. `flash` is the
137    /// FLASH-controller profile for this family (fast-page size + program mode, from
138    /// `ch32rv_flash::flash_controller_profile`), or None to refuse flash software breakpoints.
139    /// ja: transport を包んで halt。`flash` はこの family の FLASH-controller profile(fast page
140    /// サイズ + program mode。None なら flash SW breakpoint を拒否)。
141    pub fn new(dtm: T, flash: Option<(u32, FlashProgMode)>) -> Result<Self, DmiError> {
142        let mut t = Self {
143            dtm,
144            breakpoints: Vec::new(),
145            hw_breakpoints: Vec::new(),
146            hw_trigger_count: 0,
147            gpr_count: 32,
148            flash_page_size: flash.map(|(p, _)| p),
149            flash_prog_mode: flash.map(|(_, m)| m).unwrap_or(FlashProgMode::PgStart),
150            flash_bps: Vec::new(),
151            flash_pages: Vec::new(),
152            mailbox: None,
153            host: None,
154            pending_flash: Vec::new(),
155            sync: false,
156        };
157        t.dm().halt()?;
158        t.save_mailbox();
159        // Make `ebreak` halt into debug mode so software breakpoints stop the core.
160        let _ = t.dm().enable_ebreak_debug();
161        t.hw_trigger_count = t.dm().hw_trigger_count();
162        // misa.E (bit 4) marks RV32E: only x0..x15 exist. Reading x16.. would raise cmderr.
163        const MISA: u16 = 0x301;
164        const MISA_E: u32 = 1 << 4;
165        if let Ok(misa) = t.dm().read_reg(RegName::Csr(MISA))
166            && misa & MISA_E != 0
167        {
168            t.gpr_count = 16;
169        }
170        Ok(t)
171    }
172
173    /// en: Give the server its owner's reset and flash write, and the code flash's map: `load`
174    /// (vFlash) and the `monitor` commands are then offered. ja: reset と flash の書き込みと map を渡す。
175    pub fn with_host(mut self, host: Box<dyn Host<T>>, map: FlashMap) -> Self {
176        self.host = Some((host, map));
177        self
178    }
179
180    /// en: After a reset or a flash write the core lost what we set in it (dcsr.ebreakm, the
181    /// triggers) and DATA0 holds no console word worth putting back: set them again, and leave the
182    /// mailbox silent (0 is silence to every framing). ja: reset や書き込みの後に、設定し直す。
183    fn after_reset(&mut self) {
184        let _ = self.dm().enable_ebreak_debug();
185        let hw: Vec<(u32, u32)> = self
186            .hw_breakpoints
187            .iter()
188            .map(|b| (b.slot, b.addr))
189            .collect();
190        for (slot, addr) in hw {
191            let _ = self.dm().set_hw_breakpoint(slot, addr);
192        }
193        self.mailbox = Some((0, 0));
194    }
195
196    /// en: Reset through the host; `halt` holds the core at its reset vector.
197    /// ja: host で reset。`halt` なら reset vector で止める。
198    fn host_reset(&mut self, halt: bool) -> Result<(), String> {
199        let Some((mut host, map)) = self.host.take() else {
200            return Err("this session cannot reset the target".to_owned());
201        };
202        // Breakpoints stay: those in flash are still there, and GDB still counts them all.
203        let r = host.reset(&mut self.dtm, halt);
204        self.host = Some((host, map));
205        r?;
206        if halt {
207            self.after_reset();
208        } else {
209            self.mailbox = None;
210            let _ = self.dm().enable_ebreak_debug();
211        }
212        Ok(())
213    }
214
215    /// Number of hardware trigger slots the core exposes (0 on V003/V2A).
216    pub fn hw_trigger_count(&self) -> u32 {
217        self.hw_trigger_count
218    }
219
220    fn dm(&mut self) -> DebugModule<'_, T> {
221        DebugModule::new(&mut self.dtm)
222    }
223
224    /// True if the core is halted right now.
225    pub fn is_halted(&mut self) -> Result<bool, DmiError> {
226        let halted = self.dm().is_halted()?;
227        if halted {
228            self.save_mailbox();
229        }
230        Ok(halted)
231    }
232
233    /// Request a halt (used for Ctrl-C).
234    pub fn halt(&mut self) -> Result<(), DmiError> {
235        self.dm().halt()?;
236        self.save_mailbox();
237        Ok(())
238    }
239
240    /// en: Keep DATA0 / DATA1 the first time the hart is seen stopped (before any register
241    /// access overwrites them). Best-effort: a failed read keeps nothing to put back.
242    /// ja: 止まった hart を最初に見た時(register に触れる前)に DATA0 / DATA1 を覚える。
243    fn save_mailbox(&mut self) {
244        const DATA0: u8 = 0x04;
245        const DATA1: u8 = 0x05;
246        if self.mailbox.is_none()
247            && let (Ok(d0), Ok(d1)) = (self.dtm.dmi_read(DATA0), self.dtm.dmi_read(DATA1))
248        {
249            self.mailbox = Some((d0, d1));
250        }
251    }
252
253    /// Resume through the probe's run control when it has one ([`DtmAccess::resume_hart`]).
254    fn resume_hart(&mut self) -> Result<(), DmiError> {
255        match self.dtm.resume_hart() {
256            Some(r) => r,
257            None => self.dm().resume(),
258        }
259    }
260
261    /// en: Resume the hart if it is halted, with the console mailbox put back first: the end of a
262    /// session whose transport does not resume on detach.
263    /// ja: 止まっていれば(mailbox を戻してから)走らせる。detach で走らない transport の session の最後。
264    pub fn resume_if_halted(&mut self) -> Result<(), DmiError> {
265        if self.dm().is_halted()? {
266            self.restore_mailbox();
267            self.resume_hart()?;
268        }
269        Ok(())
270    }
271
272    /// Put DATA0 / DATA1 back as the hart left them (right before it runs again).
273    fn restore_mailbox(&mut self) {
274        if let Some((d0, d1)) = self.mailbox.take() {
275            let _ = self.dtm.dmi_write(0x05, d1);
276            let _ = self.dtm.dmi_write(0x04, d0);
277        }
278    }
279
280    /// en: Recover the owned transport (to detach after the session). The console mailbox is put
281    /// back first, since the caller's detach resumes the hart.
282    /// ja: transport を返す(後で detach するため)。detach で hart が走るので、先に mailbox を戻す。
283    pub fn into_inner(mut self) -> T {
284        self.restore_mailbox();
285        self.dtm
286    }
287
288    /// True if this core supports flash software breakpoints (verified FLASH-controller profile).
289    pub fn flash_breakpoints_supported(&self) -> bool {
290        self.flash_page_size.is_some()
291    }
292
293    /// en: Restore every managed flash page to its pristine content (removing any `ebreak` still
294    /// patched in). Call before detaching so an interrupted session never leaves a breakpoint
295    /// baked into flash. The session can end with the hart running (GDB gone mid-`continue`, a
296    /// fatal error), and the page rewrite needs it halted, so it is halted for the rewrite and
297    /// resumed after. Returns the pages it could not restore (they may still hold an `ebreak`).
298    /// ja: 管理中の flash page をすべて pristine に戻す(残った `ebreak` を消す)。detach 前に呼ぶ。
299    /// session は hart が走ったまま終わることがあり(continue 中に GDB が消えた、致命的な error)、
300    /// page の書き直しには止まった hart が要るので、止めて書き直し、走らせ直す。戻せなかった page を返す
301    /// (`ebreak` が残っているかもしれない)。
302    pub fn restore_flash_breakpoints(&mut self) -> Vec<u32> {
303        let Some(page) = self.flash_page_size else {
304            return Vec::new();
305        };
306        self.flash_bps.clear();
307        if self.flash_pages.is_empty() {
308            return Vec::new();
309        }
310        let running = !self.dm().is_halted().unwrap_or(true);
311        if running && self.halt().is_err() {
312            let left = self.flash_pages.iter().map(|p| p.page_addr).collect();
313            self.flash_pages.clear();
314            return left;
315        }
316        let addrs: Vec<u32> = self.flash_pages.iter().map(|p| p.page_addr).collect();
317        let mut left = Vec::new();
318        for page_addr in addrs {
319            if self.reprogram_flash_page(page, page_addr).is_err() {
320                left.push(page_addr);
321            }
322        }
323        self.flash_pages.clear();
324        if running {
325            self.restore_mailbox();
326            let _ = self.resume_hart();
327        }
328        left
329    }
330
331    /// en: Map a code address into the physical code-flash window. Programs run from the low
332    /// alias (0x0000_0000 mirrors flash), but the FLASH controller must be given the real flash
333    /// address (0x0800_0000+off). Reads work through either mirror; writes must use the physical.
334    /// ja: コード番地を物理 code-flash 窓へ写す。実行は低位 alias(0x0000_0000=flash の鏡)だが、
335    /// FLASH controller には実 flash 番地(0x0800_0000+off)を渡す必要がある。
336    fn flash_phys(addr: u32) -> u32 {
337        const FLASH_BASE: u32 = 0x0800_0000;
338        if addr < FLASH_BASE {
339            FLASH_BASE + addr
340        } else {
341            addr
342        }
343    }
344
345    /// The `ebreak` patch bytes for an instruction of size `len` (2 = RVC c.ebreak, else ebreak).
346    fn ebreak_patch(len: usize) -> &'static [u8] {
347        if len == 2 {
348            &[0x02, 0x90] // c.ebreak (0x9002, little-endian)
349        } else {
350            &[0x73, 0x00, 0x10, 0x00] // ebreak (0x00100073)
351        }
352    }
353
354    /// en: Rewrite `page_addr` to hold its pristine content plus every currently-active flash
355    /// breakpoint in that page. Skips the erase/program when the page already matches (so a
356    /// redundant set/clear round-trip costs no flash wear). Returns Ok(true) if it wrote.
357    /// ja: `page_addr` を「pristine + その page の全 flash breakpoint」の内容に書き直す。既に一致
358    /// なら erase/program を省く(無駄な書き換え=摩耗を避ける)。書いたら Ok(true)。
359    fn reprogram_flash_page(&mut self, page: u32, page_addr: u32) -> Result<bool, DmiError> {
360        let Some(idx) = self
361            .flash_pages
362            .iter()
363            .position(|p| p.page_addr == page_addr)
364        else {
365            return Ok(false);
366        };
367        let mut desired = self.flash_pages[idx].pristine.clone();
368        for bp in &self.flash_bps {
369            if bp.addr & !(page - 1) == page_addr {
370                let off = (bp.addr - page_addr) as usize;
371                let patch = Self::ebreak_patch(bp.len);
372                if off + bp.len <= desired.len() {
373                    desired[off..off + bp.len].copy_from_slice(patch);
374                }
375            }
376        }
377        if self.flash_pages[idx].current == desired {
378            return Ok(false); // no net change: skip the flash write
379        }
380        let phys = Self::flash_phys(page_addr);
381        let mode = self.flash_prog_mode;
382        {
383            let mut dm = self.dm();
384            dm.flash_page_erase(phys, mode)?;
385            dm.flash_program_page(phys, &desired, mode)?;
386        }
387        self.flash_pages[idx].current = desired;
388        Ok(true)
389    }
390
391    /// en: Add a flash software breakpoint by rewriting the containing page. Returns Ok(false)
392    /// if this family has no verified flash profile. The hart must be halted.
393    /// ja: 該当 page を書き換えて flash SW breakpoint を張る。未対応 family は Ok(false)。
394    fn add_flash_breakpoint(&mut self, addr: u32, len: usize) -> TargetResult<bool, Self> {
395        let Some(page) = self.flash_page_size else {
396            return Ok(false);
397        };
398        let page_addr = addr & !(page - 1);
399        // Load the pristine page the first time we touch it (it has no breakpoint yet).
400        if !self.flash_pages.iter().any(|p| p.page_addr == page_addr) {
401            let content = self
402                .dm()
403                .read_mem(page_addr, page)
404                .map_err(TargetError::Fatal)?;
405            self.flash_pages.push(FlashPage {
406                page_addr,
407                pristine: content.clone(),
408                current: content,
409            });
410        }
411        self.flash_bps.push(FlashBp { addr, len });
412        self.reprogram_flash_page(page, page_addr)
413            .map_err(TargetError::Fatal)?;
414        // Verify the ebreak actually landed (flash programming can silently fail on protect).
415        let back = self
416            .dm()
417            .read_mem(addr, len as u32)
418            .map_err(TargetError::Fatal)?;
419        if back != Self::ebreak_patch(len) {
420            // Roll back: drop this bp and restore the page.
421            self.flash_bps.pop();
422            let _ = self.reprogram_flash_page(page, page_addr);
423            return Ok(false);
424        }
425        Ok(true)
426    }
427
428    /// en: Remove a flash software breakpoint, restoring the page (dropping the managed page once
429    /// it holds no more breakpoints). Returns Ok(false) if `addr` was not a flash breakpoint.
430    /// ja: flash SW breakpoint を外して page を復元(その page の breakpoint が無くなれば管理解除)。
431    fn remove_flash_breakpoint(&mut self, addr: u32) -> TargetResult<bool, Self> {
432        let Some(page) = self.flash_page_size else {
433            return Ok(false);
434        };
435        let Some(pos) = self.flash_bps.iter().position(|b| b.addr == addr) else {
436            return Ok(false);
437        };
438        let page_addr = addr & !(page - 1);
439        self.flash_bps.remove(pos);
440        self.reprogram_flash_page(page, page_addr)
441            .map_err(TargetError::Fatal)?;
442        // If nothing else lives in this page, stop managing it (it is now pristine again).
443        if !self
444            .flash_bps
445            .iter()
446            .any(|b| b.addr & !(page - 1) == page_addr)
447        {
448            self.flash_pages.retain(|p| p.page_addr != page_addr);
449        }
450        Ok(true)
451    }
452}
453
454impl<T: DtmAccess> Target for Ch32Target<T> {
455    type Arch = Rv32;
456    type Error = DmiError;
457
458    #[inline(always)]
459    fn base_ops(&mut self) -> gdbstub::target::ext::base::BaseOps<'_, Self::Arch, Self::Error> {
460        gdbstub::target::ext::base::BaseOps::SingleThread(self)
461    }
462
463    #[inline(always)]
464    fn support_breakpoints(&mut self) -> Option<BreakpointsOps<'_, Self>> {
465        Some(self)
466    }
467
468    fn support_target_description_xml_override(
469        &mut self,
470    ) -> Option<TargetDescriptionXmlOverrideOps<'_, Self>> {
471        // Only an RV32E hart differs from the Arch's default (x0..x31 and pc).
472        (self.gpr_count == 16).then_some(self)
473    }
474
475    fn support_monitor_cmd(&mut self) -> Option<MonitorCmdOps<'_, Self>> {
476        Some(self)
477    }
478
479    fn support_memory_map(&mut self) -> Option<MemoryMapOps<'_, Self>> {
480        self.host.is_some().then_some(self)
481    }
482
483    fn support_flash_operations(&mut self) -> Option<FlashOps<'_, Self>> {
484        self.host.is_some().then_some(self)
485    }
486}
487
488/// en: The memory map GDB gets: code flash at its alias and at 0x0800_0000, RAM elsewhere (GDB
489/// refuses access outside the map, so the gaps are RAM too).
490/// ja: GDB に渡す memory map。code flash は別名と 0x0800_0000、間と残りは RAM(map の外は GDB が読まない)。
491fn memory_map_xml(map: FlashMap) -> String {
492    const FLASH: u64 = 0x0800_0000;
493    let size = u64::from(map.size);
494    let mut x = String::from(
495        "<?xml version=\"1.0\"?>\n<!DOCTYPE memory-map PUBLIC \"+//IDN gnu.org//DTD GDB Memory Map V1.0//EN\" \"http://sourceware.org/gdb/gdb-memory-map.dtd\">\n<memory-map>\n",
496    );
497    let flash = |x: &mut String, at: u64| {
498        x.push_str(&format!(
499            "<memory type=\"flash\" start=\"0x{at:x}\" length=\"0x{size:x}\"><property name=\"blocksize\">0x{:x}</property></memory>\n",
500            map.block
501        ));
502    };
503    let ram = |x: &mut String, from: u64, to: u64| {
504        if to > from {
505            x.push_str(&format!(
506                "<memory type=\"ram\" start=\"0x{from:x}\" length=\"0x{:x}\"/>\n",
507                to - from
508            ));
509        }
510    };
511    flash(&mut x, 0);
512    ram(&mut x, size, FLASH);
513    flash(&mut x, FLASH);
514    ram(&mut x, FLASH + size, 0x1_0000_0000);
515    x.push_str("</memory-map>\n");
516    x
517}
518
519impl<T: DtmAccess> MemoryMap for Ch32Target<T> {
520    fn memory_map_xml(
521        &self,
522        offset: u64,
523        length: usize,
524        buf: &mut [u8],
525    ) -> TargetResult<usize, Self> {
526        let Some((_, map)) = &self.host else {
527            return Ok(0);
528        };
529        let xml = memory_map_xml(*map);
530        let xml = xml.as_bytes();
531        let start = usize::try_from(offset).unwrap_or(usize::MAX).min(xml.len());
532        let n = (xml.len() - start).min(length).min(buf.len());
533        buf[..n].copy_from_slice(&xml[start..start + n]);
534        Ok(n)
535    }
536}
537
538impl<T: DtmAccess> Flash for Ch32Target<T> {
539    /// en: The erase is the write's: `flash_done` erases the pages the data touches.
540    /// ja: 消去は書き込みの側(`flash_done` が書く page を消す)。
541    fn flash_erase(&mut self, _start_addr: u32, _length: u32) -> TargetResult<(), Self> {
542        Ok(())
543    }
544
545    fn flash_write(&mut self, start_addr: u32, data: &[u8]) -> TargetResult<(), Self> {
546        let at = Self::flash_phys(start_addr);
547        match self.pending_flash.last_mut() {
548            Some((a, d)) if *a + d.len() as u32 == at => d.extend_from_slice(data),
549            _ => self.pending_flash.push((at, data.to_vec())),
550        }
551        Ok(())
552    }
553
554    fn flash_done(&mut self) -> TargetResult<(), Self> {
555        let mut segs = std::mem::take(&mut self.pending_flash);
556        if segs.is_empty() {
557            return Ok(());
558        }
559        segs.sort_by_key(|(a, _)| *a);
560        // Joined where one ends where the next starts (GDB writes a section in several packets).
561        let mut joined: Vec<(u32, Vec<u8>)> = Vec::new();
562        for (a, d) in segs {
563            match joined.last_mut() {
564                Some((b, e)) if *b + e.len() as u32 == a => e.extend_from_slice(&d),
565                _ => joined.push((a, d)),
566            }
567        }
568        let Some((mut host, map)) = self.host.take() else {
569            return Err(TargetError::NonFatal);
570        };
571        // Breakpoints patched into flash are part of the old image: forget them (the write
572        // replaces those pages); GDB inserts its breakpoints again before it runs the target.
573        self.flash_bps.clear();
574        self.flash_pages.clear();
575        let total: usize = joined.iter().map(|(_, d)| d.len()).sum();
576        eprintln!("gdb: load: writing {total} bytes to code flash");
577        let r = host.program(&mut self.dtm, &joined);
578        self.host = Some((host, map));
579        self.after_reset();
580        match r {
581            Ok(()) => {
582                eprintln!("gdb: load: written and verified");
583                Ok(())
584            }
585            Err(e) => {
586                eprintln!("gdb: load failed: {e}");
587                Err(TargetError::NonFatal)
588            }
589        }
590    }
591}
592
593impl<T: DtmAccess> MonitorCmd for Ch32Target<T> {
594    /// en: The `monitor` commands GDB front ends send to OpenOCD (cortex-debug, Arduino IDE 2):
595    /// `reset halt` / `reset init`, `reset` / `reset run`, `halt`, `resume`, `gdb_sync`. An
596    /// unknown one is answered with the list (GDB shows it), not an error.
597    /// ja: GDB の front end が OpenOCD に送る `monitor` コマンド。知らないものには一覧を返す。
598    fn handle_monitor_cmd(
599        &mut self,
600        cmd: &[u8],
601        mut out: ConsoleOutput<'_>,
602    ) -> Result<(), Self::Error> {
603        let cmd = String::from_utf8_lossy(cmd);
604        let words: Vec<&str> = cmd.split_whitespace().collect();
605        let said = |r: Result<(), String>, out: &mut ConsoleOutput<'_>, done: &str| match r {
606            Ok(()) => outputln!(out, "{done}"),
607            Err(e) => outputln!(out, "error: {e}"),
608        };
609        match words.as_slice() {
610            ["reset", "halt"] | ["reset", "init"] => {
611                let r = self.host_reset(true);
612                said(r, &mut out, "target halted at its reset vector");
613            }
614            ["reset"] | ["reset", "run"] => {
615                let r = self.host_reset(false);
616                said(r, &mut out, "target reset and running");
617            }
618            ["halt"] => {
619                let r = self.halt().map_err(|e| e.to_string());
620                said(r, &mut out, "target halted");
621            }
622            ["resume"] => {
623                self.restore_mailbox();
624                let r = self.resume_hart().map_err(|e| e.to_string());
625                said(r, &mut out, "target running");
626            }
627            ["gdb_sync"] => self.sync = true,
628            [] => {}
629            _ => outputln!(
630                out,
631                "ch32rv: monitor commands: reset halt | reset init | reset [run] | halt | resume | gdb_sync"
632            ),
633        }
634        Ok(())
635    }
636}
637
638impl<T: DtmAccess> TargetDescriptionXmlOverride for Ch32Target<T> {
639    fn target_description_xml(
640        &self,
641        _annex: &[u8],
642        offset: u64,
643        length: usize,
644        buf: &mut [u8],
645    ) -> TargetResult<usize, Self> {
646        let xml = crate::arch::RV32E_TARGET_XML.as_bytes();
647        let start = usize::try_from(offset).unwrap_or(usize::MAX).min(xml.len());
648        let n = (xml.len() - start).min(length).min(buf.len());
649        buf[..n].copy_from_slice(&xml[start..start + n]);
650        Ok(n)
651    }
652}
653
654impl<T: DtmAccess> SingleThreadBase for Ch32Target<T> {
655    fn read_registers(&mut self, regs: &mut Rv32CoreRegs) -> TargetResult<(), Self> {
656        let gpr_count = self.gpr_count;
657        let mut dm = self.dm();
658        regs.x = [0; 32];
659        regs.rv32e = gpr_count == 16;
660        // On RV32E only x0..x15 exist; leave x16..x31 as zero (touching them raises cmderr).
661        for i in 1..gpr_count {
662            regs.x[i as usize] = dm.read_reg(RegName::Gpr(i)).map_err(TargetError::Fatal)?;
663        }
664        regs.pc = dm.read_reg(RegName::Pc).map_err(TargetError::Fatal)?;
665        Ok(())
666    }
667
668    fn write_registers(&mut self, regs: &Rv32CoreRegs) -> TargetResult<(), Self> {
669        let gpr_count = self.gpr_count;
670        let mut dm = self.dm();
671        for i in 1..gpr_count {
672            dm.write_reg(RegName::Gpr(i), regs.x[i as usize])
673                .map_err(TargetError::Fatal)?;
674        }
675        dm.write_reg(RegName::Pc, regs.pc)
676            .map_err(TargetError::Fatal)?;
677        Ok(())
678    }
679
680    fn read_addrs(&mut self, start: u32, data: &mut [u8]) -> TargetResult<usize, Self> {
681        let bytes = self
682            .dm()
683            .read_mem(start, data.len() as u32)
684            .map_err(TargetError::Fatal)?;
685        let n = bytes.len().min(data.len());
686        data[..n].copy_from_slice(&bytes[..n]);
687        Ok(n)
688    }
689
690    fn write_addrs(&mut self, start: u32, data: &[u8]) -> TargetResult<(), Self> {
691        self.dm()
692            .write_mem(start, data)
693            .map_err(TargetError::Fatal)?;
694        Ok(())
695    }
696
697    #[inline(always)]
698    fn support_resume(&mut self) -> Option<SingleThreadResumeOps<'_, Self>> {
699        Some(self)
700    }
701}
702
703impl<T: DtmAccess> SingleThreadResume for Ch32Target<T> {
704    fn resume(&mut self, _signal: Option<Signal>) -> Result<(), Self::Error> {
705        self.restore_mailbox();
706        self.resume_hart()
707    }
708
709    #[inline(always)]
710    fn support_single_step(&mut self) -> Option<SingleThreadSingleStepOps<'_, Self>> {
711        Some(self)
712    }
713}
714
715impl<T: DtmAccess> SingleThreadSingleStep for Ch32Target<T> {
716    fn step(&mut self, _signal: Option<Signal>) -> Result<(), Self::Error> {
717        // `monitor gdb_sync`: report the stop GDB has not seen (after a `monitor reset halt`)
718        // without stepping; the halted core reads as stopped at once.
719        if std::mem::take(&mut self.sync) {
720            return Ok(());
721        }
722        self.dm().step()
723    }
724}
725
726impl<T: DtmAccess> Breakpoints for Ch32Target<T> {
727    #[inline(always)]
728    fn support_sw_breakpoint(&mut self) -> Option<SwBreakpointOps<'_, Self>> {
729        Some(self)
730    }
731
732    #[inline(always)]
733    fn support_hw_breakpoint(&mut self) -> Option<HwBreakpointOps<'_, Self>> {
734        // en: With a memory map GDB asks for a hardware breakpoint (Z1) at every flash address by
735        // itself ("automatically using hardware breakpoints for read-only addresses"), so a core
736        // without triggers takes them too, as flash software breakpoints. Without a map, only a
737        // core with trigger slots advertises them.
738        // ja: memory map があると GDB は flash の番地に自分で Z1 を使うので、trigger の無い core も
739        // 受けて flash の SW breakpoint で張る。map が無ければ trigger のある core だけ。
740        if self.hw_trigger_count > 0 || self.host.is_some() {
741            Some(self)
742        } else {
743            None
744        }
745    }
746}
747
748impl<T: DtmAccess> HwBreakpoint for Ch32Target<T> {
749    fn add_hw_breakpoint(&mut self, addr: u32, kind: usize) -> TargetResult<bool, Self> {
750        let Some(slot) = self.alloc_hw_slot() else {
751            // Out of trigger slots (or none): a flash breakpoint, when the address is in flash.
752            if self.host.is_some() && Self::flash_phys(addr) >= 0x0800_0000 && addr < 0x1000_0000 {
753                return self.add_flash_breakpoint(addr, if kind == 2 { 2 } else { 4 });
754            }
755            return Ok(false);
756        };
757        self.dm()
758            .set_hw_breakpoint(slot, addr)
759            .map_err(TargetError::Fatal)?;
760        self.hw_breakpoints.push(HwBp { slot, addr });
761        Ok(true)
762    }
763
764    fn remove_hw_breakpoint(&mut self, addr: u32, _kind: usize) -> TargetResult<bool, Self> {
765        if let Some(pos) = self.hw_breakpoints.iter().position(|b| b.addr == addr) {
766            let bp = self.hw_breakpoints.remove(pos);
767            self.dm()
768                .clear_hw_breakpoint(bp.slot)
769                .map_err(TargetError::Fatal)?;
770            Ok(true)
771        } else {
772            self.remove_flash_breakpoint(addr)
773        }
774    }
775}
776
777impl<T: DtmAccess> SwBreakpoint for Ch32Target<T> {
778    /// en: Set a breakpoint GDB asked for as "software" (Z0). We first try a RAM memory-patch
779    /// (`ebreak`); if the write does not stick - the classic case being a flash address, where
780    /// the DM `sw` silently no-ops - we transparently fall back to a hardware execute trigger
781    /// when the core has a free slot. That makes plain `break` work on flash-resident code for
782    /// V4-class cores (which expose triggers) without the risk of rewriting flash. Cores with no
783    /// trigger module (V003/V103) can still set RAM breakpoints; a flash breakpoint there returns
784    /// unsupported (a flash-patch approach is a follow-up).
785    /// ja: GDB が Z0(software)で要求した breakpoint。まず RAM の memory patch(`ebreak`)を
786    /// 試し、書き込みが定着しない(典型は flash 番地。DM の `sw` が無反応)場合は、空き HW slot が
787    /// あれば HW execute trigger へ透過的にフォールバックし(flash 書き換えの危険なし)、trigger が
788    /// 無ければ page 書き換えの flash software breakpoint へフォールバックする。これで trigger を
789    /// 持たない core(V203 等)でも flash 上のコードに通常 `break` が効く(flash 書き換えの摩耗あり)。
790    /// 順序は RAM → HW trigger → flash-patch。どれも不可なら未対応を返す。
791    fn add_sw_breakpoint(&mut self, addr: u32, kind: usize) -> TargetResult<bool, Self> {
792        // kind is the instruction size GDB expects (2 for RVC, 4 otherwise).
793        let (patch, len): (&[u8], usize) = if kind == 2 {
794            (&[0x02, 0x90], 2) // c.ebreak (0x9002, little-endian)
795        } else {
796            (&[0x73, 0x00, 0x10, 0x00], 4) // ebreak (0x00100073)
797        };
798        // Try a RAM memory-patch first. Scope the DM borrow so we can touch other fields after.
799        let (stuck, original) = {
800            let mut dm = self.dm();
801            let original = dm.read_mem(addr, len as u32).map_err(TargetError::Fatal)?;
802            dm.write_mem(addr, patch).map_err(TargetError::Fatal)?;
803            // The patch lands only in writable memory; a flash `sw` silently no-ops.
804            let back = dm.read_mem(addr, len as u32).map_err(TargetError::Fatal)?;
805            let stuck = back == patch;
806            if !stuck {
807                let _ = dm.write_mem(addr, &original); // restore best-effort
808            }
809            (stuck, original)
810        };
811        if stuck {
812            self.breakpoints.push(SwBp { addr, original });
813            return Ok(true);
814        }
815        // Flash (or otherwise unwritable): prefer a free hardware trigger (no wear)...
816        if let Some(slot) = self.alloc_hw_slot() {
817            self.dm()
818                .set_hw_breakpoint(slot, addr)
819                .map_err(TargetError::Fatal)?;
820            self.hw_breakpoints.push(HwBp { slot, addr });
821            return Ok(true);
822        }
823        // ...otherwise fall back to a flash software breakpoint (page rewrite) when supported.
824        self.add_flash_breakpoint(addr, len)
825    }
826
827    fn remove_sw_breakpoint(&mut self, addr: u32, _kind: usize) -> TargetResult<bool, Self> {
828        if let Some(pos) = self.breakpoints.iter().position(|b| b.addr == addr) {
829            let bp = self.breakpoints.remove(pos);
830            self.dm()
831                .write_mem(addr, &bp.original)
832                .map_err(TargetError::Fatal)?;
833            return Ok(true);
834        }
835        // It may have been satisfied by a hardware-trigger fallback (flash address).
836        if let Some(pos) = self.hw_breakpoints.iter().position(|b| b.addr == addr) {
837            let bp = self.hw_breakpoints.remove(pos);
838            self.dm()
839                .clear_hw_breakpoint(bp.slot)
840                .map_err(TargetError::Fatal)?;
841            return Ok(true);
842        }
843        // Or by a flash software breakpoint (page rewrite).
844        self.remove_flash_breakpoint(addr)
845    }
846}