Skip to main content

esp_hal/
debugger.rs

1//! Debugger utilities
2
3/// Returns whether a debugger is connected.
4#[inline(always)]
5pub fn debugger_connected() -> bool {
6    cfg_select! {
7        xtensa => xtensa_lx::is_debugger_attached(),
8        all(riscv, soc_has_assist_debug) => crate::peripherals::ASSIST_DEBUG::regs()
9            .cpu(0)
10            .debug_mode()
11            .read()
12            .debug_module_active()
13            .bit_is_set(),
14        _ => false,
15    }
16}
17
18/// Sets a word-sized data breakpoint at the given address.
19/// No breakpoint will be set when a debugger is currently attached if
20/// the `stack_guard_monitoring_with_debugger_connected` option is false.
21///
22/// Breakpoint 0 is used.
23///
24/// # Safety
25/// The address must be word aligned.
26pub unsafe fn set_stack_watchpoint(addr: usize) {
27    assert!(addr.is_multiple_of(4));
28
29    if cfg!(stack_guard_monitoring_with_debugger_connected)
30        || !crate::debugger::debugger_connected()
31    {
32        cfg_select! {
33            xtensa => {
34                let addr = addr & !0b11;
35                let dbreakc = 0b1111100 | (1 << 31); // bit 31 = STORE
36
37                unsafe {
38                    core::arch::asm!(
39                        "
40                        wsr {addr}, 144 // 144 = dbreaka0
41                        wsr {dbreakc}, 160 // 160 = dbreakc0
42                        ",
43                        addr = in(reg) addr,
44                        dbreakc = in(reg) dbreakc,
45                    );
46                }
47            }
48            _ => unsafe {
49                set_watchpoint(0, addr, 4);
50            },
51        }
52    }
53}
54
55#[cfg(riscv)]
56pub(crate) static DEBUGGER_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new();
57
58#[cfg(riscv)]
59const NAPOT_MATCH: u8 = 1;
60
61#[cfg(riscv)]
62bitfield::bitfield! {
63    /// Only match type (0x2) triggers are supported.
64    #[derive(Clone, Copy, Default)]
65    pub(crate) struct Tdata1(u32);
66
67    /// Sets this for configuring the selected trigger to fire right before a load operation with matching
68    /// data address is executed by the CPU.
69    pub bool, load, set_load: 0;
70
71    /// Sets this for configuring the selected trigger to fire right before a store operation with matching
72    /// data address is executed by the CPU.
73    pub bool, store, set_store: 1;
74
75    /// Sets this for configuring the selected trigger to fire right before an instruction with matching
76    /// virtual address is executed by the CPU.
77    pub bool, execute, set_execute: 2;
78
79    /// Sets this for enabling selected trigger to operate in user mode.
80    pub bool, u, set_u: 3;
81
82    /// Sets this for enabling selected trigger to operate in machine mode.
83    pub bool, m, set_m: 6;
84
85    /// Configures the selected trigger to perform one of the available matching operations on a
86    /// data/instruction address. Valid options are:
87    /// 0x0: exact byte match, i.e. address corresponding to one of the bytes in an access must match
88    /// the value of maddress exactly.
89    /// 0x1: NAPOT match, i.e. at least one of the bytes of an access must lie in the NAPOT region
90    /// specified in maddress.
91    /// Writing a larger value clips it to the largest possible value 0x1.
92    pub u8, _match, set_match: 10, 7;
93
94    /// Configures the selected trigger to perform one of the available actions when firing. Valid
95    /// options are:
96    /// 0x0: cause breakpoint exception.
97    /// 0x1: enter debug mode (only valid when dmode = 1)
98    /// Writing an invalid value sets this to the default value 0x0.
99    pub u8, action, set_action: 15, 12;
100
101    /// This is found to be 1 if the selected trigger had fired previously. This bit is to be cleared manually.
102    pub bool, hit, set_hit: 20;
103
104    /// 0: Both Debug and M mode can write the tdata1 and tdata2 registers at the selected tselect.
105    /// 1: Only Debug Mode can write the tdata1 and tdata2 registers at the selected tselect. Writes from
106    /// other modes are ignored.
107    /// Only writable from debug mode.
108    pub bool, dmode, set_dmode: 27;
109}
110
111#[cfg(riscv)]
112bitfield::bitfield! {
113    /// Only match type (0x2) triggers are supported.
114    #[derive(Clone, Copy, Default)]
115    pub(crate) struct Tcontrol(u32);
116
117    /// Current M mode trigger enable bit
118    pub bool, mte, set_mte: 3;
119
120    /// Previous M mode trigger enable bit
121    pub bool, mpte, set_mpte: 7;
122
123}
124
125/// Whether `mret` enables the triggers: `tcontrol.mpte`.
126#[cfg(interrupt_controller = "clic")]
127#[inline(always)]
128pub(crate) fn triggers_enabled_on_mret() -> bool {
129    let tcontrol: u32;
130    unsafe { core::arch::asm!("csrr {}, 0x7a5", out(reg) tcontrol) };
131    Tcontrol(tcontrol).mpte()
132}
133
134/// Makes `mret` enable the triggers: sets `tcontrol.mpte`.
135#[cfg(interrupt_controller = "clic")]
136#[inline(always)]
137pub(crate) unsafe fn enable_triggers_on_mret() {
138    let mut tcontrol = Tcontrol::default();
139    tcontrol.set_mpte(true);
140    unsafe { core::arch::asm!("csrs 0x7a5, {}", in(reg) tcontrol.0) };
141}
142
143#[cfg(riscv)]
144pub(crate) struct WatchPoint {
145    tdata1: u32,
146    tdata2: u32,
147}
148
149/// Clears the watchpoint.
150#[cfg(riscv)]
151pub(crate) unsafe fn clear_watchpoint(id: u8) -> WatchPoint {
152    assert!(id < 4);
153
154    // tdata1 is a WARL(write any read legal) register. We can just write 0 to it.
155    let mut tdata1 = 0;
156    let mut tdata2 = 0;
157
158    DEBUGGER_LOCK.lock(|| unsafe {
159        core::arch::asm!(
160            "
161            csrw 0x7a0, {id} // tselect
162            csrrw {tdata1}, 0x7a1, {tdata2} // tdata1
163            csrr {tdata2}, 0x7a2 // tdata2
164            ", id = in(reg) id,
165            tdata1 = inout(reg) tdata1,
166            tdata2 = out(reg) tdata2,
167        );
168    });
169
170    WatchPoint { tdata1, tdata2 }
171}
172
173/// Clears the watchpoint.
174#[cfg(riscv)]
175pub(crate) unsafe fn restore_watchpoint(id: u8, watchpoint: WatchPoint) {
176    DEBUGGER_LOCK.lock(|| unsafe {
177        core::arch::asm!(
178            "
179            csrw 0x7a0, {id} // tselect
180            csrw 0x7a1, {tdata1} // tdata1
181            csrw 0x7a2, {tdata2} // tdata2
182            ", id = in(reg) id,
183            tdata1 = in(reg) watchpoint.tdata1,
184            tdata2 = in(reg) watchpoint.tdata2,
185        );
186    });
187}
188
189/// Clears the watchpoint.
190#[cfg(all(riscv, feature = "exception-handler"))]
191pub(crate) unsafe fn watchpoint_hit(id: u8) -> bool {
192    assert!(id < 4);
193    let mut tdata = Tdata1::default();
194
195    DEBUGGER_LOCK.lock(|| unsafe {
196        core::arch::asm!(
197            "
198            csrw 0x7a0, {id} // tselect
199            csrr {tdata}, 0x7a1 // tdata1
200            ", id = in(reg) id,
201            tdata = out(reg) tdata.0,
202        );
203    });
204
205    tdata.hit()
206}
207
208/// Sets the watchpoint and enables triggers.
209#[cfg(riscv)]
210pub(crate) unsafe fn set_watchpoint(id: u8, addr: usize, len: usize) {
211    assert!(id < 4);
212    assert!(len.is_power_of_two());
213    assert!(addr.is_multiple_of(len));
214
215    let z = len.trailing_zeros();
216    let mask = {
217        let mut mask: usize = 0;
218        for i in 0..z {
219            mask |= 1 << i;
220        }
221        mask
222    };
223
224    let napot_encoding = { mask & !(1 << (z - 1)) };
225    let addr = (addr & !mask) | napot_encoding;
226
227    let mut tdata = Tdata1::default();
228    tdata.set_m(true);
229    tdata.set_store(true);
230    tdata.set_match(NAPOT_MATCH);
231    let tdata: u32 = tdata.0;
232
233    // A trap moves `mte` into `mpte` and clears it, and `mret` moves it back: setting `mpte` too
234    // keeps the trigger enabled when this runs in a trap handler, e.g. esp-rtos's scheduler.
235    let mut tcontrol = Tcontrol::default();
236    tcontrol.set_mte(true);
237    tcontrol.set_mpte(true);
238    let tcontrol: u32 = tcontrol.0;
239
240    DEBUGGER_LOCK.lock(|| unsafe {
241        core::arch::asm!(
242            "
243            csrw 0x7a0, {id} // tselect
244            csrw 0x7a5, {tcontrol} // tcontrol
245            csrw 0x7a1, {tdata} // tdata1
246            csrw 0x7a2, {addr} // tdata2
247            ", id = in(reg) id,
248            addr = in(reg) addr,
249            tdata = in(reg) tdata,
250            tcontrol = in(reg) tcontrol,
251        );
252    });
253}