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
//! All the interface bits for ARM.

pub mod ap;
pub(crate) mod communication_interface;
pub mod component;
pub(crate) mod core;
pub mod dp;
pub mod memory;
pub mod sequences;
pub mod swo;
mod traits;

pub use self::core::{armv6m, armv7a, armv7m, armv8a, armv8m, Dump};
use self::{
    ap::{AccessPort, AccessPortError},
    communication_interface::RegisterParseError,
    dp::DebugPortError,
    memory::romtable::RomTableError,
    sequences::ArmDebugSequenceError,
    {armv7a::Armv7aError, armv8a::Armv8aError},
};
use crate::probe::DebugProbeError;
pub use communication_interface::{
    ApInformation, ArmChipInfo, ArmCommunicationInterface, ArmProbeInterface, DapError,
    MemoryApInformation, Register,
};
pub use swo::{SwoAccess, SwoConfig, SwoMode, SwoReader};
pub use traits::*;

/// ARM-specific errors
#[derive(Debug, thiserror::Error)]
#[error("An ARM specific error occurred.")]
pub enum ArmError {
    /// The operation requires a specific architecture.
    #[error("The operation requires one of the following architectures: {0:?}")]
    ArchitectureRequired(&'static [&'static str]),
    /// A timeout occurred during an operation
    #[error("Timeout occurred during operation.")]
    Timeout,
    /// The address is too large for the 32 bit address space.
    #[error("Address is not in 32 bit address space.")]
    AddressOutOf32BitAddressSpace,
    /// The current target device is not an ARM device.
    #[error("Target device is not an ARM device.")]
    NoArmTarget,
    /// Error using a specific AP.
    #[error("Error using access port")]
    AccessPort {
        /// Address of the access port
        address: ApAddress,
        /// Source of the error.
        source: AccessPortError,
    },
    /// An error occurred while using a debug port.
    #[error("Error using a debug port.")]
    DebugPort(#[from] DebugPortError),
    /// The core has to be halted for the operation, but was not.
    #[error("The core needs to be halted for this operation but was not.")]
    CoreNotHalted,
    /// Performing certain operations (e.g device unlock or Chip-Erase) can leave the device in a state
    /// that requires a probe re-attach to resolve.
    #[error("Probe and device internal state mismatch. A probe re-attach is required")]
    ReAttachRequired,
    /// An operation was not performed because the required permissions were not given.
    ///
    /// This can for example happen when the core is locked and needs to be erased to be unlocked.
    /// Then the correct permission needs to be given to automatically unlock the core to prevent accidental erases.
    #[error("An operation could not be performed because it lacked the permission to do so: {0}")]
    MissingPermissions(String),

    /// An error occurred in the communication with an access port or debug port.
    #[error("An error occurred in the communication with an access port or debug port.")]
    Dap(#[from] DapError),

    /// The debug probe encountered an error.
    #[error("The debug probe encountered an error.")]
    Probe(#[from] DebugProbeError),

    /// The given register address to perform an access on was not memory aligned.
    /// Make sure it is aligned to the size of the access (`address & access_size == 0`).
    #[error("Failed to access address 0x{address:08x} as it is not aligned to the requirement of {alignment} bytes for this platform and API call.")]
    MemoryNotAligned {
        /// The address of the register.
        address: u64,
        /// The required alignment in bytes (address increments).
        alignment: usize,
    },
    /// A region outside of the AP address space was accessed.
    #[error("Out of bounds access")]
    OutOfBounds,
    /// The requested memory transfer width is not supported on the current core.
    #[error("{0} bit is not a supported memory transfer width on the current core")]
    UnsupportedTransferWidth(usize),

    /// The AP with the specified address does not exist.
    #[error("The AP with address {0:?} does not exist.")]
    ApDoesNotExist(ApAddress),

    /// The AP has the wrong type for the operation.
    WrongApType,

    /// It is not possible to create a breakpoint a the given address.
    #[error("Unable to create a breakpoint at address {0:#010X}. Hardware breakpoints are only supported at addresses < 0x2000'0000.")]
    UnsupportedBreakpointAddress(u32),

    /// ARMv8a specific error occurred.
    Armv8a(#[from] Armv8aError),

    /// ARMv7a specific error occurred.
    Armv7a(#[from] Armv7aError),

    /// Error occurred in a debug sequence.
    DebugSequence(#[from] ArmDebugSequenceError),

    /// Tracing has not been configured.
    TracingUnconfigured,

    /// Error parsing a register.
    RegisterParse(#[from] RegisterParseError),

    /// Error reading ROM table.
    RomTable(#[source] RomTableError),

    /// Failed to erase chip
    ChipEraseFailed,

    /// The operation requires a specific extension.
    #[error("The operation requires the following extension(s): {0:?}")]
    ExtensionRequired(&'static [&'static str]),

    /// Any other error occurred.
    Other(#[from] anyhow::Error),
}

impl ArmError {
    /// Constructs [`ArmError::MemoryNotAligned`] from the address and the required alignment.
    pub fn from_access_port(err: AccessPortError, ap: impl AccessPort) -> Self {
        ArmError::AccessPort {
            address: ap.ap_address(),
            source: err,
        }
    }

    /// Constructs a [`ArmError::MemoryNotAligned`] from the address and the required alignment.
    pub fn alignment_error(address: u64, alignment: usize) -> Self {
        ArmError::MemoryNotAligned { address, alignment }
    }
}

impl From<RomTableError> for ArmError {
    fn from(value: RomTableError) -> Self {
        match value {
            RomTableError::Memory(err) => *err,
            other => ArmError::RomTable(other),
        }
    }
}

/// Check if the address is a valid 32 bit address. This functions
/// is ARM specific for ease of use, so that a specific error code can be returned.
pub fn valid_32bit_arm_address(address: u64) -> Result<u32, ArmError> {
    address
        .try_into()
        .map_err(|_| ArmError::AddressOutOf32BitAddressSpace)
}