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