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
use core::fmt::{self, Debug, Formatter};
use aarch32_cpu::cache::clean_and_invalidate_data_cache_line_to_poc;
use arbitrary_int::*;
use gdbstub::target::{TargetResult, ext::breakpoints::HwBreakpoint};
use zynq7000::devcfg;
use crate::{
cpu::{
debug::{
BreakpointControl, BreakpointType, DEBUG_UNLOCK_MAGIC, DebugEventReason, DebugID,
DebugLogic, DebugROMAddress, DebugSelfAddressOffset, DebugValid, MmioDebugLogic,
PrivilegeModeFilter, SecureDebugEnable, SecurityFilter, WatchpointControl,
},
vmsa::with_manager_domain_access,
},
gdb_target::{V5Target, arch::ArmBreakpointKind, breakpoint::BreakpointError},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HardwareCapabilities {
pub num_breakpoints: u8,
pub num_watchpoints: u8,
}
pub struct HwBreakpointManager {
capabilities: HardwareCapabilities,
mmio: MmioDebugLogic<'static>,
used_breakpoints: [bool; 16],
}
impl HwBreakpointManager {
/// Sets up hardware debugging.
///
/// The returned breakpoint manager is software locked by default.
///
/// # Panics
///
/// A panic is triggered if:
///
/// - CPU debug features are hardware locked by the board.
/// - The device has no MMIO interface for debug registers.
pub fn setup(devcfg: &mut devcfg::MmioRegisters<'_>) -> Self {
// Enable access to the board's debug hardware. The devcfg registers are protected against
// accidental writes, so we have to do extra work to access them or else we get a data abort
// with "Permission fault (MMU)".
let enabled = critical_section::with(|_| {
with_manager_domain_access(|| {
clean_and_invalidate_data_cache_line_to_poc(devcfg.pointer_to_control() as u32);
// Code that runs before us might have disabled writes to the debug logic, so
// fail early if it's locked OFF.
let lock = devcfg.read_lock();
if lock.debug() {
let ctrl = devcfg.read_control();
return ctrl.invasive_debug_enable() && ctrl.secure_invasive_debug_enable();
}
// Enable the CPU's invasive debug features.
devcfg.modify_control(|ctrl| {
ctrl.with_invasive_debug_enable(true)
.with_secure_invasive_debug_enable(true)
});
true
})
});
assert!(
enabled,
"The operating system has disabled hardware debugging."
);
// Enable debugging in the Secure PL0 processor mode. (Secure PL1 is controlled by the
// Zynq's devcfg.CTRL.SPIDEN, we already enabled it.)
let secure_debug = SecureDebugEnable::read();
secure_debug.with_secure_user_invasive_debug(true).write();
// Look up where we will access debug MMIO from.
let rom_base = DebugROMAddress::read();
let self_address_offset = DebugSelfAddressOffset::read();
assert!(
rom_base.valid() == Ok(DebugValid::Valid)
&& self_address_offset.valid() == Ok(DebugValid::Valid),
"This device has no debug logic MMIO"
);
let mmio_base = rom_base
.value()
.wrapping_add_signed(self_address_offset.value());
let debug_id = DebugID::read();
let num_breakpoints = debug_id.brps().value() + 1;
let num_watchpoints = debug_id.wrps().value() + 1;
let mut manager = Self {
capabilities: HardwareCapabilities {
num_breakpoints,
num_watchpoints,
},
mmio: unsafe { DebugLogic::new_mmio_at(mmio_base) },
used_breakpoints: [false; _],
};
manager.set_locked(false);
manager.reset();
manager.set_locked(true);
manager
}
/// Disable all existing breakpoints and enable Monitor (debug exception) hardware debug mode.
pub fn reset(&mut self) {
// This doesn't have any meaning, it's just a value that clearly isn't random or a real
// address.
const RESET_SENTINEL: u32 = 0xf0f0f0f0;
assert!(!self.locked(), "Debug registers must be unlocked");
// Note: before enabling halt or monitor debug mode for the first time, all breakpoints and
// watchpoints need to be explicitly set as either enabled or disabled.
for idx in 0..self.capabilities.num_breakpoints {
self.mmio
.write_breakpoint_ctrl(idx.into(), BreakpointControl::DISABLED)
.unwrap();
self.mmio
.write_breakpoint_value(idx.into(), RESET_SENTINEL)
.unwrap();
}
self.used_breakpoints = [false; 16];
for idx in 0..self.capabilities.num_watchpoints {
self.mmio
.write_watchpoint_ctrl(idx.into(), WatchpointControl::DISABLED)
.unwrap();
self.mmio
.write_watchpoint_value(idx.into(), RESET_SENTINEL)
.unwrap();
}
aarch32_cpu::asm::dsb();
// Route breakpoint/watchpoint debug events to debug exceptions. This allows us to catch
// them at runtime as prefetch/data aborts instead of halting the processor.
// (see Table C3-1 Processor behavior on debug events)
self.mmio.modify_status_control_ext(|debug_ctrl| {
debug_ctrl
.with_halting_debug_mode(false)
.with_monitor_debug_mode(true)
});
aarch32_cpu::asm::dsb();
aarch32_cpu::asm::isb();
}
#[must_use]
pub const fn capabilities(&self) -> HardwareCapabilities {
self.capabilities
}
/// Registers and activates a hardware breakpoint matching the given address.
///
/// # Errors
///
/// An error is returned if there are no more hardware breakpoints available, or if the
/// breakpoint already exists.
pub fn add_breakpoint_at(
&mut self,
addr: u32,
specificity: Specificity,
kind: ArmBreakpointKind,
) -> Result<(), BreakpointError> {
assert!(!self.locked(), "Debug registers must be unlocked");
let (new_word, new_bas) = split_addr(addr, kind)?;
let mut next_disabled_idx = None;
// Check for duplicate breakpoint.
for idx in 0..self.capabilities.num_breakpoints {
let existing_bkpt = self.mmio.read_breakpoint_ctrl(idx as usize).unwrap();
let existing_word = self.mmio.read_breakpoint_value(idx as usize).unwrap();
// Look for breakpoints that are both paused (!enabled) and not in use.
// Breakpoints
if !existing_bkpt.enabled()
&& !self.used_breakpoints[idx as usize]
&& next_disabled_idx.is_none()
{
next_disabled_idx = Some(idx as usize);
}
if existing_bkpt.enabled()
&& existing_bkpt.breakpoint_type() == Ok(specificity.into())
&& new_word == existing_word
&& existing_bkpt.byte_address_select() == new_bas
{
return Err(BreakpointError::AlreadyExists);
}
}
// No duplicates, so now we insert a new breakpoint.
let Some(bkpt_index) = next_disabled_idx else {
return Err(BreakpointError::NoSpace);
};
// We set the breakpoint value to the 4-byte word containing the address because breakpoints
// look at regions 4 bytes large and must be aligned as such.
self.mmio
.write_breakpoint_value(bkpt_index, new_word)
.unwrap();
self.mmio
.modify_breakpoint_ctrl(bkpt_index, |bkpt| {
bkpt.with_enabled(true)
.with_byte_address_select(new_bas)
// No mask, match exact address
.with_address_range_mask(u5::new(0b00000))
// No linked Context ID breakpoint
.with_linked_breakpoint_index(u4::new(0))
.with_breakpoint_type(specificity.into())
// Don't trigger inside abort mode, and "step over" IRQs
.with_privileged_mode_ctrl(PrivilegeModeFilter::UserSystemSupervisorOnly)
.with_security_state_ctrl(SecurityFilter::All)
})
.unwrap();
aarch32_cpu::asm::dsb();
aarch32_cpu::asm::isb();
self.used_breakpoints[bkpt_index] = true;
Ok(())
}
/// Removes all breakpoints at the given address with the given kind and type.
///
/// Returns whether any changes were made.
pub fn remove_breakpoint_at(
&mut self,
addr: u32,
specificity: Specificity,
kind: ArmBreakpointKind,
) -> bool {
assert!(!self.locked(), "Debug registers must be unlocked");
let Ok((search_word, byte_address_select)) = split_addr(addr, kind) else {
return false;
};
let mut anything_removed = false;
for bkpt_index in 0..self.capabilities.num_breakpoints {
// First, is this breakpoint referring to the target address and enabled?
let bkpt = self.mmio.read_breakpoint_ctrl(bkpt_index as usize).unwrap();
let is_enabled_and_cfged = bkpt.enabled()
&& bkpt.breakpoint_type() == Ok(specificity.into())
&& bkpt.byte_address_select() == byte_address_select;
if !is_enabled_and_cfged {
continue;
}
let bkpt_word = self
.mmio
.read_breakpoint_value(bkpt_index as usize)
.unwrap();
if bkpt_word != search_word {
continue;
}
// It is, so remove it.
self.mmio
.write_breakpoint_ctrl(bkpt_index as usize, bkpt.with_enabled(false))
.unwrap();
anything_removed = true;
self.used_breakpoints[bkpt_index as usize] = false;
}
aarch32_cpu::asm::dsb();
aarch32_cpu::asm::isb();
anything_removed
}
#[must_use]
pub fn breakpoints_available(&self) -> u8 {
let breaks_used = self.used_breakpoints.iter().filter(|&&e| e).count() as u8;
let total_breaks = self.capabilities.num_breakpoints;
total_breaks - breaks_used
}
/// Returns the reason why the most recent debug event was triggered.
#[must_use]
pub fn last_break_reason(&self) -> Option<DebugEventReason> {
let status = self.mmio.read_status_control_ext();
status.method_of_entry().ok()
}
/// Indicates whether changes to hardware breakpoints (via MMIO) are disabled.
///
/// This breakpoint manager abstraction will panic if MMIO is locked and a caller attempts to
/// make changes.
pub fn locked(&self) -> bool {
self.mmio.read_lock_status().software_lock_status()
}
/// Sets whether changes to hardware breakpoints (via MMIO) are disabled.
pub fn set_locked(&mut self, locked: bool) {
if locked {
self.mmio.write_lock_access(0);
} else {
self.mmio.write_lock_access(DEBUG_UNLOCK_MAGIC);
}
debug_assert!(self.locked() == locked);
}
pub unsafe fn mmio(&self) -> &MmioDebugLogic<'_> {
&self.mmio
}
}
/// Controls a breakpoint or watchpoint's association with its address(es).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Specificity {
/// The breakpoint/watchpoint is triggered when the specified addresses are accessed.
Match,
/// The breakpoint/watchpoint is triggered when an address other than the ones specified
/// are accessed.
Mismatch,
}
impl From<Specificity> for BreakpointType {
fn from(value: Specificity) -> Self {
match value {
Specificity::Match => BreakpointType::UnlinkedInstrAddressMatch,
Specificity::Mismatch => BreakpointType::UnlinkedInstrAddressMismatch,
}
}
}
impl Debug for HwBreakpointManager {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut bkpt_values = [0; 16];
let mut bkpt_ctrls = [BreakpointControl::ZERO; 16];
for i in 0..self.capabilities.num_breakpoints.min(16) {
bkpt_values[i as usize] = self.mmio.read_breakpoint_value(i as usize).unwrap();
bkpt_ctrls[i as usize] = self.mmio.read_breakpoint_ctrl(i as usize).unwrap();
}
f.debug_struct("HwBreakpointManager")
.field("locked", &self.locked())
.field("capabilities", &self.capabilities)
.field("used_breakpoints", &self.used_breakpoints)
.field("mmio_ptr", &unsafe { self.mmio.ptr() })
.field(
"bkpt_values",
&&bkpt_values[..self.capabilities.num_breakpoints as usize],
)
.field(
"bkpt_ctrls",
&&bkpt_ctrls[..self.capabilities.num_breakpoints as usize],
)
.finish_non_exhaustive()
}
}
/// Splits an address into the word containing it and the byte-address-select that would match
/// the instruction's offset into the word.
fn split_addr(addr: u32, kind: ArmBreakpointKind) -> Result<(u32, u4), BreakpointError> {
let word = addr & !0b11;
// Specify which addresses inside the 4-byte breakpoint to match. Multi-byte instructions
// are considered to inhabit all of their addresses at once.
let byte_address_select = match kind {
// The instruction spans 4 bytes, so the breakpoint needs to match over its the entire
// 4-byte value: [0-3].
ArmBreakpointKind::Arm32 => {
if !addr.is_multiple_of(4) {
return Err(BreakpointError::NotAlignedCorrectly);
}
u4::new(0b1111)
}
// 16-bit Thumb address - match either addresses ending in [0-1] or [2-3], depending on
// which side of the word it's aligned to.
// (Although 4-byte Thumb instructions are a thing, we can treat them the same as 2-byte
// ones. See <Table C3-2> Effect of byte address selection on Breakpoint generation.)
ArmBreakpointKind::Thumb16 | ArmBreakpointKind::Thumb32 => {
if !addr.is_multiple_of(2) {
return Err(BreakpointError::NotAlignedCorrectly);
}
if addr.is_multiple_of(4) {
u4::new(0b0011)
} else {
u4::new(0b1100)
}
}
};
Ok((word, byte_address_select))
}
impl HwBreakpoint for V5Target {
fn add_hw_breakpoint(
&mut self,
addr: u32,
kind: ArmBreakpointKind,
) -> TargetResult<bool, Self> {
if self.hw_manager.breakpoints_available() <= 1 {
// One hardware breakpoint should be saved for single stepping.
return Ok(false);
}
let result = self
.hw_manager
.add_breakpoint_at(addr, Specificity::Match, kind);
Ok(result.is_ok())
}
fn remove_hw_breakpoint(
&mut self,
addr: u32,
kind: ArmBreakpointKind,
) -> TargetResult<bool, Self> {
let did_remove = self
.hw_manager
.remove_breakpoint_at(addr, Specificity::Match, kind);
Ok(did_remove)
}
}