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
use crate::{
    architecture::{
        arm::{
            ap::MemoryAp,
            core::{CortexAState, CortexMState},
            ApAddress, ArmProbeInterface, DpAddress,
        },
        riscv::{communication_interface::RiscvCommunicationInterface, RiscVState},
        xtensa::{communication_interface::XtensaCommunicationInterface, XtensaState},
    },
    Core, CoreType, Error, Target,
};

use super::ResolvedCoreOptions;

#[derive(Debug)]
pub(crate) struct CombinedCoreState {
    pub(crate) core_state: CoreState,

    pub(crate) specific_state: SpecificCoreState,

    pub(crate) id: usize,
}

impl CombinedCoreState {
    pub fn id(&self) -> usize {
        self.id
    }

    pub fn core_type(&self) -> CoreType {
        self.specific_state.core_type()
    }

    pub(crate) fn attach_arm<'probe>(
        &'probe mut self,
        target: &'probe Target,
        arm_interface: &'probe mut Box<dyn ArmProbeInterface>,
    ) -> Result<Core<'probe>, Error> {
        let memory_regions = &target.memory_map;

        let name = &target.cores[self.id].name;

        let memory = arm_interface.memory_interface(self.arm_memory_ap())?;

        let (options, debug_sequence) = match &self.core_state.core_access_options {
            ResolvedCoreOptions::Arm { options, sequence } => (options, sequence.clone()),
            _ => {
                return Err(Error::UnableToOpenProbe(
                    "Core architecture and Probe mismatch.",
                ))
            }
        };

        Ok(match &mut self.specific_state {
            SpecificCoreState::Armv6m(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::arm::armv6m::Armv6m::new(memory, s, debug_sequence)?,
            ),
            SpecificCoreState::Armv7a(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::arm::armv7a::Armv7a::new(
                    memory,
                    s,
                    options.debug_base.expect("base_address not specified"),
                    debug_sequence,
                )?,
            ),
            SpecificCoreState::Armv7m(s) | SpecificCoreState::Armv7em(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::arm::armv7m::Armv7m::new(memory, s, debug_sequence)?,
            ),
            SpecificCoreState::Armv8a(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::arm::armv8a::Armv8a::new(
                    memory,
                    s,
                    options.debug_base.expect("base_address not specified"),
                    options.cti_base.expect("cti_address not specified"),
                    debug_sequence,
                )?,
            ),
            SpecificCoreState::Armv8m(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::arm::armv8m::Armv8m::new(memory, s, debug_sequence)?,
            ),
            _ => {
                return Err(Error::UnableToOpenProbe(
                    "Core architecture and Probe mismatch.",
                ))
            }
        })
    }

    pub(crate) fn enable_arm_debug(
        &self,
        interface: &mut dyn ArmProbeInterface,
    ) -> Result<(), Error> {
        let ResolvedCoreOptions::Arm { sequence, options } = &self.core_state.core_access_options
        else {
            unreachable!("This should never happen. Please file a bug if it does.");
        };

        tracing::debug_span!("debug_core_start", id = self.id()).in_scope(|| {
            // Enable debug mode
            sequence.debug_core_start(
                interface,
                self.arm_memory_ap(),
                self.core_type(),
                options.debug_base,
                options.cti_base,
            )
        })?;

        Ok(())
    }

    pub(crate) fn arm_reset_catch_set(
        &self,
        interface: &mut dyn ArmProbeInterface,
    ) -> Result<(), Error> {
        let ResolvedCoreOptions::Arm { sequence, options } = &self.core_state.core_access_options
        else {
            unreachable!("This should never happen. Please file a bug if it does.");
        };

        let mut memory_interface = interface.memory_interface(self.arm_memory_ap())?;

        let reset_catch_span = tracing::debug_span!("reset_catch_set", id = self.id()).entered();
        sequence.reset_catch_set(&mut *memory_interface, self.core_type(), options.debug_base)?;

        drop(reset_catch_span);

        Ok(())
    }

    pub(crate) fn attach_riscv<'probe>(
        &'probe mut self,
        target: &'probe Target,
        interface: &'probe mut RiscvCommunicationInterface,
    ) -> Result<Core<'probe>, Error> {
        let memory_regions = &target.memory_map;
        let name = &target.cores[self.id].name;

        let options = match &self.core_state.core_access_options {
            ResolvedCoreOptions::Riscv { options } => options,
            _ => {
                return Err(Error::UnableToOpenProbe(
                    "Core architecture and Probe mismatch.",
                ))
            }
        };

        Ok(match &mut self.specific_state {
            SpecificCoreState::Riscv(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::riscv::Riscv32::new(
                    options.hart_id.unwrap_or_default(),
                    interface,
                    s,
                )?,
            ),
            _ => {
                return Err(Error::UnableToOpenProbe(
                    "Core architecture and Probe mismatch.",
                ))
            }
        })
    }

    pub(crate) fn attach_xtensa<'probe>(
        &'probe mut self,
        target: &'probe Target,
        interface: &'probe mut XtensaCommunicationInterface,
    ) -> Result<Core<'probe>, Error> {
        let memory_regions = &target.memory_map;
        let name = &target.cores[self.id].name;

        Ok(match &mut self.specific_state {
            SpecificCoreState::Xtensa(s) => Core::new(
                self.id,
                name,
                memory_regions,
                crate::architecture::xtensa::Xtensa::new(interface, s),
            ),
            _ => {
                return Err(Error::UnableToOpenProbe(
                    "Core architecture and Probe mismatch.",
                ))
            }
        })
    }

    /// Get the memory AP for this core.
    ///
    /// ## Panic
    ///
    /// This function will panic if the core is not an ARM core and doesn't have a memory AP
    pub(crate) fn arm_memory_ap(&self) -> MemoryAp {
        self.core_state.memory_ap()
    }
}

/// A generic core state which caches the generic parts of the core state.
#[derive(Debug)]
pub struct CoreState {
    /// Information needed to access the core
    core_access_options: ResolvedCoreOptions,
}

impl CoreState {
    /// Creates a new core state from the core ID.
    pub fn new(core_access_options: ResolvedCoreOptions) -> Self {
        Self {
            core_access_options,
        }
    }

    pub(crate) fn memory_ap(&self) -> MemoryAp {
        let arm_core_access_options = match self.core_access_options {
            ResolvedCoreOptions::Arm { ref options, .. } => options,
            _ => unreachable!("This should never happen. Please file a bug if it does."),
        };

        let dp = match arm_core_access_options.psel {
            0 => DpAddress::Default,
            x => DpAddress::Multidrop(x),
        };

        let ap = ApAddress {
            dp,
            ap: arm_core_access_options.ap,
        };

        MemoryAp::new(ap)
    }
}

/// The architecture specific core state.
#[derive(Debug)]
pub enum SpecificCoreState {
    /// The state of an ARMv6-M core.
    Armv6m(CortexMState),
    /// The state of an ARMv7-A core.
    Armv7a(CortexAState),
    /// The state of an ARMv7-M core.
    Armv7m(CortexMState),
    /// The state of an ARMv7-EM core.
    Armv7em(CortexMState),
    /// The state of an ARMv8-A core.
    Armv8a(CortexAState),
    /// The state of an ARMv8-M core.
    Armv8m(CortexMState),
    /// The state of an RISC-V core.
    Riscv(RiscVState),
    /// The state of an Xtensa core.
    Xtensa(XtensaState),
}

impl SpecificCoreState {
    pub(crate) fn from_core_type(typ: CoreType) -> Self {
        match typ {
            CoreType::Armv6m => SpecificCoreState::Armv6m(CortexMState::new()),
            CoreType::Armv7a => SpecificCoreState::Armv7a(CortexAState::new()),
            CoreType::Armv7m => SpecificCoreState::Armv7m(CortexMState::new()),
            CoreType::Armv7em => SpecificCoreState::Armv7m(CortexMState::new()),
            CoreType::Armv8a => SpecificCoreState::Armv8a(CortexAState::new()),
            CoreType::Armv8m => SpecificCoreState::Armv8m(CortexMState::new()),
            CoreType::Riscv => SpecificCoreState::Riscv(RiscVState::new()),
            CoreType::Xtensa => SpecificCoreState::Xtensa(XtensaState::new()),
        }
    }

    pub(crate) fn core_type(&self) -> CoreType {
        match self {
            SpecificCoreState::Armv6m(_) => CoreType::Armv6m,
            SpecificCoreState::Armv7a(_) => CoreType::Armv7a,
            SpecificCoreState::Armv7m(_) => CoreType::Armv7m,
            SpecificCoreState::Armv7em(_) => CoreType::Armv7em,
            SpecificCoreState::Armv8a(_) => CoreType::Armv8a,
            SpecificCoreState::Armv8m(_) => CoreType::Armv8m,
            SpecificCoreState::Riscv(_) => CoreType::Riscv,
            SpecificCoreState::Xtensa(_) => CoreType::Xtensa,
        }
    }
}