riscv-etrace 0.10.0

Decoder and tracer for RISC-V efficient instruction tracing
Documentation
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
// Copyright (C) 2024 - 2026 FZI Forschungszentrum Informatik
// SPDX-License-Identifier: Apache-2.0
//! Instruction information

/// Instruction information
///
/// This trait defines fns for querying control flow relevant information of
/// individual instructions.
pub trait Info: Send + Sync {
    /// Type for representing a register address
    type Register: Clone + PartialEq;

    /// Determine the branch target
    ///
    /// If [`Self`] refers to a branch instruction, this fn returns the
    /// immediate, which is the branch target relative to this instruction.
    /// Returns `None` if [`Self`] does not refer to a (known) branch
    /// instruction. Jump instructions are not considered branch instructions.
    fn branch_target(&self) -> Option<i16>;

    /// Determine the inferable jump target
    ///
    /// If [`Self`] refers to a jump instruction that in itself determines the
    /// jump target, this fn returns that target relative to this instruction.
    /// Returns `None` if [`Self`] does not refer to a (known) jump instruction
    /// or if the branch target cannot be inferred based on the instruction
    /// alone.
    ///
    /// For example, a `jalr` instruciton's target will never be considered
    /// inferable unless the source register is the `zero` register, even if it
    /// is preceeded directly by `auipc` and `addi` instructions defining a
    /// constant jump target.
    ///
    /// Branch instructions are not considered jump instructions.
    fn inferable_jump_target(&self) -> Option<i32>;

    /// Determine the uninferable jump target
    ///
    /// If [`Self`] refers to a jump instruction that in itself does not
    /// determine the (relative) jump target, this fn returns the information
    /// neccessary to determine the target in the form of a register number
    /// (first tuple element) and an offset (second tuple element). The jump
    /// target is computed by adding the offset to the contents of the denoted
    /// register.
    ///
    /// Note that a `jalr` instruciton's target will always be considered
    /// uninferable unless the source register is the `zero` register, even if
    /// it is preceeded directly by `auipc` and `addi` instructions defining a
    /// constant jump target. However, callers may be able to infer the jump
    /// target in such situations using statically determined register values.
    ///
    /// Branch instructions are not considered jump instructions.
    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)>;

    /// Determine the upper immediate
    ///
    /// If [`Self`] refers to an `auipc`, `lui` or other instruction loading an
    /// upper immediate, this fn returns the register the immediate is stored to
    /// (first tuple element) and its effective value after the instruction
    /// retired (second tuple element) under the assumption that the
    /// instruction's address is `pc`.
    fn upper_immediate(&self, pc: u64) -> Option<(Self::Register, u64)>;

    /// Determine whether this instruction returns from a trap
    ///
    /// Returns `true` if [`Self`] refers to one of the (known) special
    /// instructions that return from a trap.
    fn is_return_from_trap(&self) -> bool;

    /// Determine whether this instruction is an `ecall` or `ebreak`
    ///
    /// Returns `true` if this refers to either an `ecall`, `ebreak` or
    /// `c.ebreak`.
    fn is_ecall_or_ebreak(&self) -> bool;

    /// Determine whether this instruction can be considered a function call
    ///
    /// Returns `true` if [`Self`] refers to an instruction that we consider a
    /// function call, that is a jump-and-link instruction with either `ra`/`x1`
    /// (the return address register) or `x5` (alternative return address) as
    /// `rd`. See section 4.1.1 of the specification for details.
    fn is_call(&self) -> bool;

    /// Determine whether this instruction can be considered a function return
    ///
    /// Returns `true` if [`Self`] refers to an instruction that we consider a
    /// function return, that is a jump register instruction with either
    /// `ra`/`x1` (the return address register) or `x5` (alternative return
    /// address) as `rs1` and neither as `rd`. See section 4.1.1 of the
    /// specification for details.
    fn is_return(&self) -> bool;

    /// Determin whether this instruction is a branch instruction
    ///
    /// Returns `true` if [`Self`] refers to a branch instruction.
    fn is_branch(&self) -> bool {
        self.branch_target().is_some()
    }

    /// Determin whether this instruction is an inferable jump
    ///
    /// Returns `true` if [`Self`] refers to a jump with a jump target that can
    /// be infered from the instruction lone. See
    /// [`inferable_jump_target`][Self::inferable_jump_target] for details.
    fn is_inferable_jump(&self) -> bool {
        self.inferable_jump_target().is_some()
    }

    /// Determin whether this instruction is an uninferable jump
    ///
    /// Returns `true` if [`Self`] refers to a jump with a jump target that can
    /// not be infered from the instruction lone. See
    /// [`uninferable_jump_target`][Self::uninferable_jump_target] for details.
    fn is_uninferable_jump(&self) -> bool {
        self.uninferable_jump_target().is_some()
    }

    /// Determine whether this instruction causes an uninferable discontinuity
    ///
    /// Returns `true` if [`Self`] refers to an instruction that causes a (PC)
    /// discontinuity with a target that can not be inferred from the
    /// instruction alone. This is the case if the instruction is either
    /// * an [uninferable jump][Self::is_uninferable_jump],
    /// * a [return from trap][Self::is_return_from_trap] or
    /// * an [`ecall` or `ebreak`][Self::is_ecall_or_ebreak].
    fn is_uninferable_discon(&self) -> bool {
        self.is_uninferable_jump() || self.is_return_from_trap() || self.is_ecall_or_ebreak()
    }

    /// Create an instruction that is to be ignored
    ///
    /// Create a valid instruction that does not have any effect on control flow
    /// and is not used for construction of addresses, such as a `nop` or an
    /// "unknown" or "unimplemented" instruction. If this instruction does have
    /// a known size, it is a 32bit (uncompressed) instruction.
    fn ignored() -> Self;
}

impl<T: Info> Info for Option<T> {
    type Register = T::Register;

    fn branch_target(&self) -> Option<i16> {
        self.as_ref().and_then(Info::branch_target)
    }

    fn inferable_jump_target(&self) -> Option<i32> {
        self.as_ref().and_then(Info::inferable_jump_target)
    }

    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)> {
        self.as_ref().and_then(Info::uninferable_jump_target)
    }

    fn upper_immediate(&self, pc: u64) -> Option<(Self::Register, u64)> {
        self.as_ref().and_then(|i| i.upper_immediate(pc))
    }

    fn is_return_from_trap(&self) -> bool {
        self.as_ref()
            .map(Info::is_return_from_trap)
            .unwrap_or(false)
    }

    fn is_ecall_or_ebreak(&self) -> bool {
        self.as_ref().map(Info::is_ecall_or_ebreak).unwrap_or(false)
    }

    fn is_call(&self) -> bool {
        self.as_ref().map(Info::is_call).unwrap_or(false)
    }

    fn is_return(&self) -> bool {
        self.as_ref().map(Info::is_return).unwrap_or(false)
    }

    fn ignored() -> Self {
        None
    }
}

impl<I, T> Info for (I, T)
where
    I: Info,
    T: Default,
    Self: Sync + Send,
{
    type Register = I::Register;

    fn branch_target(&self) -> Option<i16> {
        self.0.branch_target()
    }

    fn inferable_jump_target(&self) -> Option<i32> {
        self.0.inferable_jump_target()
    }

    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)> {
        self.0.uninferable_jump_target()
    }

    fn upper_immediate(&self, pc: u64) -> Option<(Self::Register, u64)> {
        self.0.upper_immediate(pc)
    }

    fn is_return_from_trap(&self) -> bool {
        self.0.is_return_from_trap()
    }

    fn is_ecall_or_ebreak(&self) -> bool {
        self.0.is_ecall_or_ebreak()
    }

    fn is_call(&self) -> bool {
        self.0.is_call()
    }

    fn is_return(&self) -> bool {
        self.0.is_return()
    }

    fn ignored() -> Self {
        (Info::ignored(), Default::default())
    }
}

#[cfg(feature = "either")]
impl<L, R, T> Info for either::Either<L, R>
where
    L: Info<Register = T>,
    R: Info<Register = T>,
    T: Clone + PartialEq,
{
    type Register = T;

    fn branch_target(&self) -> Option<i16> {
        either::for_both!(self, i => i.branch_target())
    }

    fn inferable_jump_target(&self) -> Option<i32> {
        either::for_both!(self, i => i.inferable_jump_target())
    }

    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)> {
        either::for_both!(self, i => i.uninferable_jump_target())
    }

    fn upper_immediate(&self, pc: u64) -> Option<(Self::Register, u64)> {
        either::for_both!(self, i => i.upper_immediate(pc))
    }

    fn is_return_from_trap(&self) -> bool {
        either::for_both!(self, i => i.is_return_from_trap())
    }

    fn is_ecall_or_ebreak(&self) -> bool {
        either::for_both!(self, i => i.is_ecall_or_ebreak())
    }

    fn is_call(&self) -> bool {
        either::for_both!(self, i => i.is_call())
    }

    fn is_return(&self) -> bool {
        either::for_both!(self, i => i.is_return())
    }

    fn ignored() -> Self {
        either::Left(Info::ignored())
    }
}

#[cfg(feature = "riscv-isa")]
impl Info for riscv_isa::Instruction {
    type Register = u32;

    fn branch_target(&self) -> Option<i16> {
        match self {
            Self::BEQ { offset, .. } => Some(*offset as i16),
            Self::BNE { offset, .. } => Some(*offset as i16),
            Self::BLT { offset, .. } => Some(*offset as i16),
            Self::BGE { offset, .. } => Some(*offset as i16),
            Self::BLTU { offset, .. } => Some(*offset as i16),
            Self::BGEU { offset, .. } => Some(*offset as i16),
            _ => None,
        }
    }

    fn inferable_jump_target(&self) -> Option<i32> {
        match self {
            Self::JALR { rs1: 0, offset, .. } => Some(*offset),
            Self::JAL { offset, .. } => Some(*offset),
            _ => None,
        }
    }

    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)> {
        match self {
            Self::JALR { rs1, offset, .. } => Some((*rs1, *offset as i16)),
            _ => None,
        }
        .filter(|(r, _)| *r != 0)
    }

    fn upper_immediate(&self, pc: u64) -> Option<(Self::Register, u64)> {
        match self {
            Self::LUI { rd, imm } => Some((*rd, 0, *imm as i32)),
            Self::AUIPC { rd, imm } => Some((*rd, pc, *imm as i32)),
            _ => None,
        }
        .map(|(r, b, o)| (r, b.wrapping_add_signed((o << 12).into())))
    }

    fn is_return_from_trap(&self) -> bool {
        matches!(self, Self::SRET | Self::MRET)
    }

    fn is_ecall_or_ebreak(&self) -> bool {
        matches!(self, Self::ECALL | Self::EBREAK)
    }

    fn is_call(&self) -> bool {
        match self {
            Self::JALR { rd: 1, rs1, .. } => *rs1 != 5,
            Self::JALR { rd: 5, rs1, .. } => *rs1 != 1,
            Self::JAL { rd, .. } => *rd == 1 || *rd == 5,
            _ => false,
        }
    }

    fn is_return(&self) -> bool {
        match self {
            Self::JALR { rd, rs1: 1, .. } => *rd != 1 && *rd != 5,
            Self::JALR { rd, rs1: 5, .. } => *rd != 1 && *rd != 5,
            _ => false,
        }
    }

    fn ignored() -> Self {
        Self::UNIMP
    }
}

#[cfg(feature = "riscv-isa")]
impl Info for riscv_isa::Compressed {
    type Register = u32;

    fn branch_target(&self) -> Option<i16> {
        match self {
            Self::C_BEQZ { offset, .. } => Some(*offset as i16),
            Self::C_BNEZ { offset, .. } => Some(*offset as i16),
            _ => None,
        }
    }

    fn inferable_jump_target(&self) -> Option<i32> {
        match self {
            Self::C_JAL { offset } => Some(*offset),
            Self::C_J { offset } => Some(*offset),
            _ => None,
        }
    }

    fn uninferable_jump_target(&self) -> Option<(Self::Register, i16)> {
        match self {
            Self::C_JALR { rs1 } => Some((*rs1, 0)),
            Self::C_JR { rs1 } => Some((*rs1, 0)),
            _ => None,
        }
        .filter(|(r, _)| *r != 0)
    }

    fn upper_immediate(&self, _pc: u64) -> Option<(Self::Register, u64)> {
        match self {
            Self::C_LUI { rd, imm } => {
                let mut imm = (*imm << 12).into();
                if imm & (1 << 17) > 0 {
                    imm |= 0xfffffffffffe0000;
                }
                Some((*rd, imm))
            }
            _ => None,
        }
    }

    fn is_return_from_trap(&self) -> bool {
        false
    }

    fn is_ecall_or_ebreak(&self) -> bool {
        matches!(self, Self::C_EBREAK)
    }

    fn is_call(&self) -> bool {
        match self {
            Self::C_JALR { rs1, .. } => *rs1 != 5,
            Self::C_JAL { .. } => true,
            _ => false,
        }
    }

    fn is_return(&self) -> bool {
        match self {
            Self::C_JR { rs1, .. } => *rs1 == 1 || *rs1 == 5,
            _ => false,
        }
    }

    fn ignored() -> Self {
        Self::UNIMP
    }
}