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
//! RISC-V trap/exception handling
#![warn(missing_docs)]
// TODO(eliza): none of this is really D1-specific, and it should all work on
// any RISC-V target. If/when we add a generic `mnemos-riscv` crate, we may want
// to move this stuff there...

use core::fmt;

/// Represents the cause of a trap, based on the value of the `mcause` register.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Trap {
    /// The trap was an interrupt.
    Interrupt(Interrupt),
    /// The trap was an exception.
    Exception(Exception),
}

/// Error returned by [`Trap::from_mcause`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InvalidMcause {
    bits: usize,
    err: &'static str,
}

/// Pretty-prints a `riscv_rt::TrapFrame`.
#[derive(Copy, Clone, Debug)]
pub struct PrettyTrapFrame<'a> {
    #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
    frame: &'a riscv_rt::TrapFrame,

    #[cfg(not(any(target_arch = "riscv64", target_arch = "riscv32")))]
    _frame: core::marker::PhantomData<&'a ()>,
}

macro_rules! cause_enum {
    (
        $(#[$meta:meta])* $vis:vis enum $Enum:ident {
            $(
                $Variant:ident = $val:literal => $pretty:literal
            ),+
            $(,)?
        }
    ) => {
        $(#[$meta])*
        #[repr(usize)]
        $vis enum $Enum {
            $(
                #[doc = $pretty]
                $Variant = $val,
            )+
        }

        impl fmt::Display for $Enum {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self {
                    $(
                        $Enum::$Variant => f.pad($pretty),
                    )+
                }
            }
        }

        impl fmt::UpperHex for $Enum {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::UpperHex::fmt(&(*self as usize), f)
            }
        }

        impl fmt::LowerHex for $Enum {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::LowerHex::fmt(&(*self as usize), f)
            }
        }

        impl TryFrom<usize> for $Enum {
            type Error = &'static str;

            fn try_from(value: usize) -> Result<Self, Self::Error> {
                match value {
                    $(
                        $val => Ok($Enum::$Variant),
                    )+
                    _ => Err(cause_enum!(@error: $Enum, $($val),+)),
                }
            }
        }
    };

    (@error: $Enum:ident, $firstval:literal, $($val:literal),*) => {
        concat!(
            "invalid value for ",
            stringify!($Enum),
            ", expected one of [",
            stringify!($firstval),
            $(
                ", ",
                stringify!($val),
            )+
            "]",
        )
    };
}

cause_enum! {
    /// RISC-V exception causes.
    ///
    /// If the interrupt bit (the highest bit) in the `mcause` register is 0, the
    /// rest of the `mcause` register is interpreted as an exception cause.
    ///
    /// See "3.1.20 Machine Cause Register (`mcause`)" in [_RISC-V rivileged
    /// Architectures_, v1.10][manual].
    ///
    /// [manual]:
    ///     https://riscv.org/wp-content/uploads/2017/05/riscv-privileged-v1.10.pdf
    #[derive(Copy, Clone, Debug, Eq, PartialEq)]
    pub enum Exception {
        InstAddrMisaligned = 0 => "Instruction address misaligned",
        InstAccessFault = 1 => "Instruction access fault",
        IllegalInst = 2 => "Illegal instruction",
        Breakpoint = 3 => "Breakpoint",
        LoadAddrMisaligned = 4 => "Load address misaligned",
        LoadAccessFault = 5 => "Load access fault",
        StoreAddrMisaligned = 6 => "Store/AMO address misaligned",
        StoreAccessFault = 7 => "Store/AMO access fault",
        UModeEnvCall = 8 => "Environment call from U-mode",
        SModeEnvCall = 9 => "Environment call from S-mode",
        MModeEnvCall = 11 => "Environment call from M-mode",
        InstPageFault = 12 => "Instruction page fault",
        LoadPageFault = 13 => "Load page fault",
        StorePageFault = 15 => "Store/AMO page fault",
    }
}

cause_enum! {
    /// RISC-V interrupt causes.
    ///
    /// If the interrupt bit (the highest bit) in the `mcause` register is 1, the
    /// rest of the `mcause` register is interpreted as an interrupt cause.
    ///
    /// See "3.1.20 Machine Cause Register (`mcause`)" in [_RISC-V Privileged
    /// Architectures_, v1.10][manual].
    ///
    /// [manual]:
    ///     https://riscv.org/wp-content/uploads/2017/05/riscv-privileged-v1.10.pdf
    #[derive(Copy, Clone, Debug, Eq, PartialEq)]
    pub enum Interrupt {
        UserSw = 0 => "User software interrupt",
        SupervisorSw = 1 => "Supervisor software interrupt",
        MachineSw = 3 => "Machine software interrupt",
        UserTimer = 4 => "User timer interrupt",
        SupervisorTimer = 5 => "Supervisor timer interrupt",
        MachineTimer = 7 => "Machine timer interrupt",
        UserExt = 8 => "User external interrupt",
        SupervisorExt = 9 => "Supervisor external interrupt",
        MachineExt = 11 => "Machine external interrupt",
    }
}

// === impl Trap ===

impl Trap {
    /// Reads the value of the `mcause` register and interprets it as a `Trap`.
    ///
    /// # Returns
    ///
    /// - [`Ok`]`(`[`Trap`]`)` if the value of the `mcause` register is a valid
    ///   trap code
    /// - [`Err`]`(`[`InvalidMcause`]`)` if the value of the `mcause` register
    ///   is not a valid trap code. Note that this Should Not Happen if the
    ///   hardware is functioning correctly.
    #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
    pub fn from_mcause() -> Result<Self, InvalidMcause> {
        let mut bits: usize;
        unsafe {
            core::arch::asm!("csrrs {}, mcause, x0", out(reg) bits, options(nomem, nostack, preserves_flags));
        }
        Self::from_bits(bits)
    }

    /// Reads the value of the `mcause` register and interprets it as a `Trap`.
    ///
    /// # Returns
    ///
    /// - [`Ok`]`(`[`Trap`]`)` if the value of the `mcause` register is a valid
    ///   trap code
    /// - [`Err`]`(`[`InvalidMcause`]`)` if the value of the `mcause` register
    ///   is not a valid trap code. Note that this Should Not Happen if the
    ///   hardware is functioning correctly.
    #[cfg(not(any(target_arch = "riscv64", target_arch = "riscv32")))]
    pub fn from_mcause() -> Result<Self, InvalidMcause> {
        unimplemented!("cannot access mcause on a non-RISC-V platform!")
    }

    #[cfg_attr(
        not(any(target_arch = "riscv64", target_arch = "riscv32")),
        allow(dead_code)
    )]
    fn from_bits(bits: usize) -> Result<Self, InvalidMcause> {
        const INTERRUPT_BIT: usize = 1 << (usize::BITS - 1);

        let res = if bits & INTERRUPT_BIT == INTERRUPT_BIT {
            Interrupt::try_from(bits & !INTERRUPT_BIT).map(Self::Interrupt)
        } else {
            Exception::try_from(bits & !INTERRUPT_BIT).map(Self::Exception)
        };
        res.map_err(|err| InvalidMcause { err, bits })
    }
}

impl fmt::Display for Trap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Trap::Interrupt(t) => fmt::Display::fmt(t, f),
            Trap::Exception(t) => fmt::Display::fmt(t, f),
        }
    }
}

// === impl InvalidMcause ===

impl fmt::Display for InvalidMcause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { bits, err } = self;
        write!(f, "invalid mcause ({bits:#b}): {err}")
    }
}

// === impl PrettyTrapFrame ===

#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
const CHARS: usize = (usize::BITS / 4) as usize;

#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
macro_rules! pretty_trap_frame {
    (fmt: $f:ident, frame: $frame:expr, $spec:literal => $($reg:ident),+ $(,)?) => {

        let nl = if $f.alternate() { "\n" } else { ", " };
        $(
            $f.pad(stringify!($reg))?;
            write!($f, concat!(": {:0width$", $spec,"}{}"), $frame.$reg, nl, width = CHARS)?;
        )+
    }
}

#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
impl<'frame> From<&'frame riscv_rt::TrapFrame> for PrettyTrapFrame<'frame> {
    #[inline]
    fn from(frame: &'frame riscv_rt::TrapFrame) -> Self {
        Self { frame }
    }
}

impl fmt::LowerHex for PrettyTrapFrame<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
        pretty_trap_frame!(fmt: f, frame: self.frame, "x" => ra, t0, t1, t2, t3, t4, t5, t6, a0, a1, a2, a3, a4, a5, a6, a7);

        #[cfg(not(any(target_arch = "riscv64", target_arch = "riscv32")))]
        f.pad("<not on RISC-V lol>")?;

        Ok(())
    }
}

impl fmt::UpperHex for PrettyTrapFrame<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
        pretty_trap_frame!(fmt: f, frame: self.frame, "X" => ra, t0, t1, t2, t3, t4, t5, t6, a0, a1, a2, a3, a4, a5, a6, a7);

        #[cfg(not(any(target_arch = "riscv64", target_arch = "riscv32")))]
        f.pad("<not on RISC-V lol>")?;

        Ok(())
    }
}