v5gdb 0.1.0-alpha.2

GDB-compatible debugger backend for the VEX V5 platform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Access to system debug registers.

#![allow(non_upper_case_globals)]

use aarch32_cpu::register::{SysReg, SysRegRead, SysRegWrite};
use arbitrary_int::*;
use bitbybit::{bitenum, bitfield};

/// Returns the (CRn, CRm, opc2) arguments that would be required to access the given debug register
/// via the CPU's CP14 interface.
///
/// See "C6.4.1 Using CP14 to access debug registers" in the ARMv7-A manual.
#[must_use]
pub const fn get_cp14_encoding(register: DebugRegister) -> (u32, u32, u32) {
    let regnum = register.to_raw();

    (
        (regnum >> 7) & 0b111,
        regnum & 0b1111,
        (regnum >> 4) & 0b111,
    )
}

/// Read the given debug register.
#[macro_export]
macro_rules! read_dbgreg {
    ($reg:expr) => {
        unsafe {
            const ENCODING: (u32, u32, u32) = $crate::cpu::debug::get_cp14_encoding($reg);
            let value: u32;
            core::arch::asm!(
                "mrc p14, 0, {value}, c{CRn}, c{CRm}, {opc2}",
                value = out(reg) value,
                CRn = const ENCODING.0,
                CRm = const ENCODING.1,
                opc2 = const ENCODING.2,
                options(nostack, preserves_flags),
            );
            value
        }
    };
}

/// Write the given value to the debug register.
#[macro_export]
macro_rules! write_dbgreg {
    ($reg:expr, $value:expr) => {
        {
            const ENCODING: (u32, u32, u32) = $crate::cpu::debug::get_cp14_encoding($reg);
            let value: u32 = $value;
            core::arch::asm!(
                "mcr p14, 0, {value}, c{CRn}, c{CRm}, {opc2}",
                value = in(reg) value,
                CRn = const ENCODING.0,
                CRm = const ENCODING.1,
                opc2 = const ENCODING.2,
                options(nostack, preserves_flags),
            );
        }
    };
}

/// A debug register that can be read or written to with [`write_dbgreg`] or [`read_dbgreg`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DebugRegister(u32);

impl DebugRegister {
    pub const fn to_raw(self) -> u32 {
        self.0
    }
}

/// The raw version of [`DebugID`].
pub const DBGDIDR: DebugRegister = DebugRegister(0);
/// The raw version of [`DebugStatusControl`] (internal view).
pub const DBGDSCRint: DebugRegister = DebugRegister(1);
/// The raw version of [`DebugStatusControl`] (external view).
pub const DBGDSCRext: DebugRegister = DebugRegister(34);
pub const DBGDRAR: DebugRegister = DebugRegister(128);
pub const DBGDSAR: DebugRegister = DebugRegister(256);

/// The DBGDIDR register.
#[bitfield(u32, debug)]
pub struct DebugID {
    #[bits(28..=31, r)]
    wrps: u4,
    #[bits(24..=27, r)]
    brps: u4,
    #[bits(16..=19, r)]
    version: Option<DebugVersion>,
}

impl DebugID {
    /// Read the current value.
    pub fn read() -> Self {
        Self::new_with_raw_value(read_dbgreg!(DBGDIDR))
    }
}

/// A version of the debug architecture.
#[derive(Debug, PartialEq, Eq)]
#[bitenum(u4, exhaustive = false)]
pub enum DebugVersion {
    V6 = 0b0001,
    V6_1 = 0b0010,
    V7Full = 0b0011,
    V7Minimal = 0b0100,
    V7_1 = 0b0101,
}

/// The DBGDSCR register.
#[bitfield(u32, debug)]
pub struct DebugStatusControl {
    #[bit(16, r)]
    secure_pl1_invasive_debug_disabled: bool,
    #[bit(15, rw)]
    monitor_debug_mode: bool,
    #[bit(14, rw)]
    halting_debug_mode: bool,
    #[bits(2..=5, r)]
    method_of_entry: Option<DebugEventReason>,
}

#[bitenum(u4, exhaustive = false)]
#[derive(Debug, PartialEq, Eq)]
pub enum DebugEventReason {
    HaltReq = 0b0000,
    Breakpoint = 0b0001,
    AsyncWatchpoint = 0b0010,
    BkptInstr = 0b0011,
    ExtDebugReq = 0b0100,
    VectorCatch = 0b0101,
    OSUnlock = 0b1000,
    SyncWatchpoint = 0b1010,
}

#[derive(Debug, PartialEq, Eq)]
#[bitenum(u2, exhaustive = false)]
pub enum DebugValid {
    Invalid = 0b00,
    Valid = 0b11,
}

#[bitfield(u32, debug)]
pub struct DebugROMAddress {
    #[bits(12..=31, r)]
    romaddr: u20,
    #[bits(0..=1, r)]
    valid: Option<DebugValid>,
}

impl DebugROMAddress {
    pub fn read() -> Self {
        Self::new_with_raw_value(read_dbgreg!(DBGDRAR))
    }

    #[must_use]
    pub const fn value(self) -> usize {
        (self.romaddr().value() << 12) as usize
    }
}

#[bitfield(u32, debug)]
pub struct DebugSelfAddressOffset {
    #[bits(12..=31, r)]
    selfoffset: u20,
    #[bits(0..=1, r)]
    valid: Option<DebugValid>,
}

impl DebugSelfAddressOffset {
    pub fn read() -> Self {
        Self::new_with_raw_value(read_dbgreg!(DBGDSAR))
    }

    #[must_use]
    pub const fn value(self) -> isize {
        (self.selfoffset().value() << 12) as isize
    }
}

/// The SDER register.
#[bitfield(u32, debug)]
pub struct SecureDebugEnable {
    #[bit(0, rw)]
    secure_user_invasive_debug: bool,
    #[bit(1, rw)]
    secure_user_noninvasive_debug: bool,
}

impl SysReg for SecureDebugEnable {
    const CP: u32 = 15;
    const CRN: u32 = 1;
    const OP1: u32 = 0;
    const CRM: u32 = 1;
    const OP2: u32 = 1;
}

impl SysRegRead for SecureDebugEnable {}
impl SysRegWrite for SecureDebugEnable {}

impl SecureDebugEnable {
    /// Read the current value.
    pub fn read() -> Self {
        Self::new_with_raw_value(Self::read_raw())
    }

    /// Update the current value.
    pub fn write(self) {
        // SAFETY: This is a valid register access.
        unsafe {
            Self::write_raw(self.raw_value());
        }
    }
}

#[derive(derive_mmio::Mmio)]
#[repr(C)]
pub struct DebugLogic {
    // Fields prefixed with an underscore cannot be accessed via MMIO on our target device.
    #[mmio(PureRead)]
    id: DebugID,
    _status_control_int: DebugStatusControl,
    _reserved0: [u32; 3],
    _data_transfer_int: u32,
    /// Available, but deprecated. Instead, read LR_abt to determine the PC of the watchpoint hit.
    _watchpoint_fault_addr: u32,
    vector_catch: u32,
    _reserved1: u32,
    event_catch: u32,
    debug_cache_ctrl: u32,
    debug_mmu_ctrl: u32,
    _reserved2: [u32; 20],
    host_to_target_data_transfer_ext: u32,
    #[mmio(Write)]
    instr_tx: u32,
    status_control_ext: DebugStatusControl,
    target_to_host_data_transfer_ext: u32,
    #[mmio(Write)]
    run_ctrl: u32,
    ext_auxiliary_ctrl: u32,
    _reserved3: [u32; 2],
    #[mmio(PureRead)]
    pc_sample: u32,
    #[mmio(PureRead)]
    context_id_sample: u32,
    _virt_id_sample: u32,
    _reserved4: [u32; 21],
    /// When matching instructions, value & 0b11 must be 0
    breakpoint_value: [u32; 16],
    breakpoint_ctrl: [BreakpointControl; 16],
    /// `value` & 0b11 must be 0.
    watchpoint_value: [u32; 16],
    watchpoint_ctrl: [WatchpointControl; 16],
    _debug_rom_addr: u32,
    _reserved5: [u32; 15],
    _breakpoint_extd_value: [u32; 16],
    _reserved6: [u32; 32],
    _os_lock_access: u32,
    #[mmio(PureRead)]
    os_lock_status: u32,
    _os_save_restore: u32,
    _os_double_lock: u32,
    powerdown_reset_ctrl: u32,
    #[mmio(PureRead)]
    powerdown_reset_status: u32,
    _reserved7: [u32; 58],
    _debug_self_addr_offset: u32,
    _reserved8: [u32; 255],
    _impl_defined0: [u32; 64],
    _reserved9: [u32; 256],
    #[mmio(PureRead)]
    processor_id: [u32; 64],
    _reserved10: [u32; 32],
    _integration: [u32; 32],
    _integration_mode_ctrl: u32,
    _reserved11: [u32; 39],
    claim_tag_set: u32,
    claim_tag_clear: u32,
    _reserved12: [u32; 2],
    /// Writing [`DEBUG_UNLOCK_MAGIC`] to this field disables the [software
    /// lock](Self::lock_status) on debug register writes.
    ///
    /// If any other value is written, the lock is re-enabled.
    #[mmio(Write)]
    lock_access: u32,
    /// Indicates whether the debug software lock is active, which prevents accidental damage to
    /// the debug registers by disabling writes. It is on by default.
    #[mmio(PureRead)]
    lock_status: SoftwareLock,
    #[mmio(PureRead)]
    authentication_status: u32,
    _reserved13: u32,
    _debug_device_id_2: u32,
    _debug_device_id_1: u32,
    #[mmio(PureRead)]
    device_type: u32,
    #[mmio(PureRead)]
    peripheral_id_4: u32,
    #[mmio(PureRead)]
    peripheral_ids: [u32; 4],
    #[mmio(PureRead)]
    component_ids: [u32; 4],
}

/// Writing this value to [`DebugLogic::lock_access`] enables writing to debug registers.
pub const DEBUG_UNLOCK_MAGIC: u32 = 0xC5ACCE55;

#[bitfield(u32, debug)]
pub struct BreakpointControl {
    // Set a breakpoint on a range of addresses by excluding some lower bits from the comparison.
    #[bits(24..=28, rw)]
    address_range_mask: u5,
    #[bits(20..=23, rw)]
    breakpoint_type: Option<BreakpointType>,
    #[bits(16..=19, rw)]
    linked_breakpoint_index: u4,
    /// Controls which security states the breakpoint filters for.
    #[bits(14..=15, rw)]
    security_state_ctrl: Option<SecurityFilter>,
    /// A bitfield that controls which addresses inside the 4-byte breakpoint value will cause a
    /// hit.
    ///
    /// Setting any number bit will enable hits on an addresses ending in that number. For
    /// instance, setting bit zero (0bxxx1) will enable hits on addresses ending with 0 (i.e.
    /// 0bxx…xx00), whereas setting bit three (0b1xxx) will enable hits on addresses ending
    /// with 3 (i.e. 0bxx…xx11).
    ///
    /// For the purposes of this field, instructions are considered to take up multiple addresses
    /// at once depending on their size. It's not possible to set a breakpoint on half an
    /// instruction, so, for instance, 0b0011 is invalid in ARM and 0b0001 is invalid in both
    /// Thumb and ARM.
    #[bits(5..=8, rw)]
    byte_address_select: u4,
    #[bits(1..=2, rw)]
    privileged_mode_ctrl: PrivilegeModeFilter,
    #[bit(0, rw)]
    enabled: bool,
}

impl BreakpointControl {
    pub const DISABLED: Self = BreakpointControl::new_with_raw_value(0).with_enabled(false);
}

#[bitenum(u4, exhaustive = false)]
#[derive(Debug, PartialEq, Eq)]
pub enum BreakpointType {
    /// A breakpoint that triggers when the PC matches an address.
    UnlinkedInstrAddressMatch = 0b0000,
    /// The address part of a linked breakpoint that triggers on both an address match and a
    /// context-id match.
    LinkedInstrAddressMatch = 0b0001,
    /// A breakpoint that triggers on context-id (CONTEXTIDR) match.
    UnlinkedContextIDMatch = 0b0010,
    /// The context-id part of a linked breakpoint that triggers on both an address (mis)match and a
    /// context-id match.
    LinkedContextIDMatch = 0b0011,
    /// A breakpoint that triggers when the PC doesn't match an address.
    UnlinkedInstrAddressMismatch = 0b0100,
    /// The address part of a linked breakpoint that triggers on both an address mismatch and a
    /// context-id match.
    LinkedInstrAddressMismatch = 0b0101,
}

#[bitenum(u2, exhaustive = false)]
#[derive(Debug, PartialEq, Eq)]
pub enum SecurityFilter {
    All = 0b00,
    NotSecureOnly = 0b01,
    SecureOnly = 0b10,
}

#[bitenum(u2, exhaustive = true)]
#[derive(Debug, PartialEq, Eq)]
pub enum PrivilegeModeFilter {
    UserSystemSupervisorOnly = 0b00,
    Level1Only = 0b01,
    UserOnly = 0b10,
    All = 0b11,
}

#[bitfield(u32, debug)]
pub struct WatchpointControl {
    #[bit(20, rw)]
    watchpoint_type: WatchpointType,
    #[bits(16..=19, rw)]
    linked_breakpoint_index: u4,
    /// Controls which security states the watchpoint filters for.
    #[bits(14..=15, rw)]
    security_state_ctrl: Option<SecurityFilter>,
    /// See [`BreakpointControl::byte_address_select`].
    #[bits(5..=8, rw)]
    byte_address_select: u4,
    #[bits(3..=4, rw)]
    load_store_ctrl: Option<LoadStoreFilter>,
    #[bits(1..=2, rw)]
    privileged_access_ctrl: Option<PrivilegedAccessFilter>,
    #[bit(0, rw)]
    enabled: bool,
}

impl WatchpointControl {
    pub const DISABLED: Self = WatchpointControl::new_with_raw_value(0).with_enabled(false);
}

#[bitenum(u1, exhaustive = true)]
#[derive(Debug, PartialEq, Eq)]
pub enum WatchpointType {
    /// A watchpoint that triggers when an address is accessed as data.
    UnlinkedDataAddressMatch = 0,
    /// The address part of a watchpoint that triggers on both an address match and a context-id
    /// match. It is linked to a context-id breakpoint.
    LinkedDataAddressMatch = 1,
}

#[bitenum(u2, exhaustive = false)]
#[derive(Debug, PartialEq, Eq)]
pub enum LoadStoreFilter {
    LoadSwapOnly = 0b01,
    StoreSwapOnly = 0b10,
    All = 0b11,
}

#[bitenum(u2, exhaustive = false)]
#[derive(Debug, PartialEq, Eq)]
pub enum PrivilegedAccessFilter {
    Level1Only = 0b01,
    UserOnly = 0b10,
    All = 0b11,
}

#[bitfield(u32)]
pub struct SoftwareLock {
    /// Always false, indicates whether the unlock register can be written to as a non-32-bit
    /// value.
    #[bit(2, r)]
    not_32bit_access: bool,
    /// Indicates whether the software lock is enabled.
    #[bit(1, r)]
    software_lock_status: bool,
    /// Always true, indicates whether the software lock is implemented.
    #[bit(0, r)]
    software_lock_implemented: bool,
}