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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Copyright (C) 2025, 2026 FZI Forschungszentrum Informatik
// SPDX-License-Identifier: Apache-2.0
//! Trace unit implementation specific definitions and utilities
//!
//! This module provides traits for capturing some specifics of trace unit
//! implementations not captured by [`config::Parameters`], as well as
//! implementations of those traits.

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use core::fmt;

use crate::config;

use super::decoder::{Decode, Decoder};
use super::encoder::{Encode, Encoder};
use super::error::Error;

use config::AddressMode;

/// Specifics about a trace unit implementation
pub trait Unit<U = Self> {
    /// Instruction trace options
    type IOptions: IOptions + 'static;

    /// Data trace options
    type DOptions: DOptions + 'static;

    /// Width of the encoder mode field
    fn encoder_mode_width(&self) -> u8;

    /// Decode instruction trace options
    fn decode_ioptions(decoder: &mut Decoder<U>) -> Result<Self::IOptions, Error>;

    /// Decode data trace options
    fn decode_doptions(decoder: &mut Decoder<U>) -> Result<Self::DOptions, Error>;

    /// Create a [`Plug`] for this unit
    #[cfg(feature = "alloc")]
    fn as_plug(&self) -> Plug
    where
        Self: Unit<Plug> + Sized,
        <Self as Unit<Plug>>::IOptions: fmt::Debug,
        <Self as Unit<Plug>>::DOptions: fmt::Debug,
    {
        Plug::new(self)
    }
}

/// Instruction trace options that may be communicated via support packets
///
/// This trait features fns that return either [`Some`] value reflecting an
/// option or [`None`] if the type does not contain any information on the
/// specific option.
pub trait IOptions: Send + Sync {
    /// Retrieve the encoder's address mode
    fn address_mode(&self) -> Option<AddressMode> {
        None
    }

    /// Retrieve whether the encoder reports sequentially inferable jumps
    ///
    /// Returns `Some(true)` if the encoder signals that it does _not_ report
    /// sequentially inferable jumps and `Some(false)` if it signals that it
    /// _does_ report them.
    fn sequentially_inferred_jumps(&self) -> Option<bool> {
        None
    }

    /// Retrieve whether the encoder reports function return addresses
    ///
    /// Returns `Some(true)` if the encoder signals that it does _not_ report
    /// function return addresses and `Some(false)` if it signals that it _does_
    /// report them.
    fn implicit_return(&self) -> Option<bool> {
        None
    }

    /// Retrieve whether the encoder may omit trap vector addresses
    ///
    /// Returns `Some(true)` if the encoder signals that it omits addresses from
    /// packets reporting traps if that address can be determined from `ecause`.
    /// Returns `Some(false)` if the encoder signals that it always includes the
    /// address.
    fn implicit_exception(&self) -> Option<bool> {
        None
    }

    /// Retrieve whether branch prediction is enabled
    fn branch_prediction(&self) -> Option<bool> {
        None
    }

    /// Retrieve whether jump target caching is enabled
    fn jump_target_cache(&self) -> Option<bool> {
        None
    }

    /// Update the active [`Features`][config::Features] based on these ioptions
    ///
    /// On success, the given [`Features`][config::Features] reflect the
    /// configuration conveyed by these ioptions. If any of the activated
    /// options is not supported, the name of the feature is returned as an
    /// error. It is the responsibility of the caller to wrap that `&str` into
    /// an appropriate error type if neccessary.
    fn update_features(&self, features: &mut config::Features) -> Result<(), &'static str> {
        // Before touching any state, we need to assert no unsupported option is
        // active.
        if self.implicit_exception() == Some(true) {
            return Err("implicit exceptions");
        }
        if self.branch_prediction() == Some(true) {
            return Err("branch prediction");
        }
        if self.jump_target_cache() == Some(true) {
            return Err("jump target cache");
        }

        if let Some(jumps) = self.sequentially_inferred_jumps() {
            features.sequentially_inferred_jumps = jumps;
        }
        if let Some(returns) = self.implicit_return() {
            features.implicit_returns = returns;
        }

        Ok(())
    }
}

#[cfg(feature = "alloc")]
impl<T: IOptions + ?Sized> IOptions for Box<T> {
    fn address_mode(&self) -> Option<AddressMode> {
        T::address_mode(self.as_ref())
    }

    fn sequentially_inferred_jumps(&self) -> Option<bool> {
        T::sequentially_inferred_jumps(self.as_ref())
    }

    fn implicit_return(&self) -> Option<bool> {
        T::implicit_return(self.as_ref())
    }

    fn implicit_exception(&self) -> Option<bool> {
        T::implicit_exception(self.as_ref())
    }

    fn branch_prediction(&self) -> Option<bool> {
        T::branch_prediction(self.as_ref())
    }

    fn jump_target_cache(&self) -> Option<bool> {
        T::jump_target_cache(self.as_ref())
    }
}

#[cfg(feature = "either")]
impl<L: IOptions, R: IOptions> IOptions for either::Either<L, R> {
    fn address_mode(&self) -> Option<AddressMode> {
        either::for_both!(self, o => o.address_mode())
    }

    fn sequentially_inferred_jumps(&self) -> Option<bool> {
        either::for_both!(self, o => o.sequentially_inferred_jumps())
    }

    fn implicit_return(&self) -> Option<bool> {
        either::for_both!(self, o => o.implicit_return())
    }

    fn implicit_exception(&self) -> Option<bool> {
        either::for_both!(self, o => o.implicit_exception())
    }

    fn branch_prediction(&self) -> Option<bool> {
        either::for_both!(self, o => o.branch_prediction())
    }

    fn jump_target_cache(&self) -> Option<bool> {
        either::for_both!(self, o => o.jump_target_cache())
    }
}

/// An [`IOptions`] that is [`Debug`][fmt::Debug]
pub trait DebugIOptions: IOptions + fmt::Debug {}

impl<T: IOptions + fmt::Debug> DebugIOptions for T {}

/// Data trace options that may be communicated via support packets
pub trait DOptions: Send + Sync {}

#[cfg(feature = "alloc")]
impl<T: DOptions + ?Sized> DOptions for Box<T> {}

#[cfg(feature = "either")]
impl<L: DOptions, R: DOptions> DOptions for either::Either<L, R> {}

/// An `doptions` that are [`Debug`][fmt::Debug]
pub trait DebugDOptions: DOptions + fmt::Debug {}

impl<T: DOptions + fmt::Debug> DebugDOptions for T {}

/// Reference trace [`Unit`]
///
/// This unit is used in the reference flow (in the form of a model).
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Reference;

impl<U> Unit<U> for Reference {
    type IOptions = ReferenceIOptions;
    type DOptions = ReferenceDOptions;

    fn encoder_mode_width(&self) -> u8 {
        1
    }

    fn decode_ioptions(decoder: &mut Decoder<U>) -> Result<Self::IOptions, Error> {
        Decode::decode(decoder)
    }

    fn decode_doptions(decoder: &mut Decoder<U>) -> Result<Self::DOptions, Error> {
        Decode::decode(decoder)
    }
}

/// [`IOptions`] for the [`Reference`] [`Unit`]
#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub struct ReferenceIOptions {
    pub implicit_return: bool,
    pub implicit_exception: bool,
    pub full_address: bool,
    pub jump_target_cache: bool,
    pub branch_prediction: bool,
}

impl<U> Decode<'_, U> for ReferenceIOptions {
    fn decode(decoder: &mut Decoder<U>) -> Result<Self, Error> {
        let implicit_return = decoder.read_bit()?;
        let implicit_exception = decoder.read_bit()?;
        let full_address = decoder.read_bit()?;
        let jump_target_cache = decoder.read_bit()?;
        let branch_prediction = decoder.read_bit()?;
        Ok(Self {
            implicit_return,
            implicit_exception,
            full_address,
            jump_target_cache,
            branch_prediction,
        })
    }
}

impl<U> Encode<'_, U> for ReferenceIOptions {
    fn encode(&self, encoder: &mut Encoder<U>) -> Result<(), Error> {
        encoder.write_bit(self.implicit_return)?;
        encoder.write_bit(self.implicit_exception)?;
        encoder.write_bit(self.full_address)?;
        encoder.write_bit(self.jump_target_cache)?;
        encoder.write_bit(self.branch_prediction)
    }
}

impl IOptions for ReferenceIOptions {
    fn address_mode(&self) -> Option<AddressMode> {
        Some(AddressMode::from_full(self.full_address))
    }

    fn implicit_return(&self) -> Option<bool> {
        Some(self.implicit_return)
    }

    fn implicit_exception(&self) -> Option<bool> {
        Some(self.implicit_exception)
    }

    fn branch_prediction(&self) -> Option<bool> {
        Some(self.branch_prediction)
    }

    fn jump_target_cache(&self) -> Option<bool> {
        Some(self.jump_target_cache)
    }
}

/// DOptions for the [`Reference`] [`Unit`]
#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub struct ReferenceDOptions {
    pub no_address: bool,
    pub no_data: bool,
    pub full_address: bool,
    pub full_data: bool,
}

impl<U> Decode<'_, U> for ReferenceDOptions {
    fn decode(decoder: &mut Decoder<U>) -> Result<Self, Error> {
        let no_address = decoder.read_bit()?;
        let no_data = decoder.read_bit()?;
        let full_address = decoder.read_bit()?;
        let full_data = decoder.read_bit()?;
        Ok(Self {
            no_address,
            no_data,
            full_address,
            full_data,
        })
    }
}

impl<U> Encode<'_, U> for ReferenceDOptions {
    fn encode(&self, encoder: &mut Encoder<U>) -> Result<(), Error> {
        encoder.write_bit(self.no_address)?;
        encoder.write_bit(self.no_data)?;
        encoder.write_bit(self.full_address)?;
        encoder.write_bit(self.full_data)
    }
}

impl DOptions for ReferenceDOptions {}

/// PULP trace [`Unit`]
///
/// Supports the [PULP rv tracer](https://github.com/pulp-platform/rv_tracer)
/// and compatible trace units.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct PULP;

impl<U> Unit<U> for PULP {
    type IOptions = PULPIOptions;
    type DOptions = NoOptions;

    fn encoder_mode_width(&self) -> u8 {
        1
    }

    fn decode_ioptions(decoder: &mut Decoder<U>) -> Result<Self::IOptions, Error> {
        Decode::decode(decoder)
    }

    fn decode_doptions(decoder: &mut Decoder<U>) -> Result<Self::DOptions, Error> {
        Decode::decode(decoder)
    }
}

/// [`IOptions`] for the [`PULP`] [`Unit`]
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct PULPIOptions {
    pub delta_address: bool,
    pub full_address: bool,
    pub implicit_exception: bool,
    pub sijump: bool,
    pub implicit_return: bool,
    pub branch_prediction: bool,
    pub jump_target_cache: bool,
}

impl<U> Decode<'_, U> for PULPIOptions {
    fn decode(decoder: &mut Decoder<U>) -> Result<Self, Error> {
        let jump_target_cache = decoder.read_bit()?;
        let branch_prediction = decoder.read_bit()?;
        let implicit_return = decoder.read_bit()?;
        let sijump = decoder.read_bit()?;
        let implicit_exception = decoder.read_bit()?;
        let full_address = decoder.read_bit()?;
        let delta_address = decoder.read_bit()?;
        Ok(Self {
            delta_address,
            full_address,
            implicit_exception,
            sijump,
            implicit_return,
            branch_prediction,
            jump_target_cache,
        })
    }
}

impl<U> Encode<'_, U> for PULPIOptions {
    fn encode(&self, encoder: &mut Encoder<U>) -> Result<(), Error> {
        encoder.write_bit(self.jump_target_cache)?;
        encoder.write_bit(self.branch_prediction)?;
        encoder.write_bit(self.implicit_return)?;
        encoder.write_bit(self.sijump)?;
        encoder.write_bit(self.implicit_exception)?;
        encoder.write_bit(self.full_address)?;
        encoder.write_bit(self.delta_address)
    }
}

impl IOptions for PULPIOptions {
    fn address_mode(&self) -> Option<AddressMode> {
        match (self.delta_address, self.full_address) {
            (true, false) => Some(AddressMode::Delta),
            (false, true) => Some(AddressMode::Full),
            _ => None,
        }
    }

    fn sequentially_inferred_jumps(&self) -> Option<bool> {
        Some(self.sijump)
    }

    fn implicit_return(&self) -> Option<bool> {
        Some(self.implicit_return)
    }

    fn implicit_exception(&self) -> Option<bool> {
        Some(self.implicit_exception)
    }

    fn branch_prediction(&self) -> Option<bool> {
        Some(self.branch_prediction)
    }

    fn jump_target_cache(&self) -> Option<bool> {
        Some(self.jump_target_cache)
    }
}

/// A [`Unit`] allowing plugging any [`Unit`] into a [`Decoder`]
///
/// [`Decoder`] is generic over its [`Unit`], and may thus be constructed with
/// any [`Unit`]. However , this choice is reflected in the [`Decoder`]'s type.
/// This helper allows erasing the type of the specific [`Unit`] used, serving
/// as a "plug" for arbitrary [`Unit`]s.
#[cfg(feature = "alloc")]
#[allow(clippy::type_complexity)]
#[derive(Copy, Clone, Debug)]
pub struct Plug {
    encoder_mode_width: u8,
    decode_ioptions: fn(&mut Decoder<Self>) -> Result<Box<dyn DebugIOptions>, Error>,
    decode_doptions: fn(&mut Decoder<Self>) -> Result<Box<dyn DebugDOptions>, Error>,
}

#[cfg(feature = "alloc")]
impl Plug {
    /// Create a new plug for the given [`Unit`]
    pub fn new<U>(inner: &U) -> Self
    where
        U: Unit<Self>,
        U::IOptions: fmt::Debug,
        U::DOptions: fmt::Debug,
    {
        fn decode_ioptions<U>(decoder: &mut Decoder<Plug>) -> Result<Box<dyn DebugIOptions>, Error>
        where
            U: Unit<Plug>,
            U::IOptions: fmt::Debug,
        {
            U::decode_ioptions(decoder).map(|r| -> Box<dyn DebugIOptions> { Box::new(r) })
        }

        fn decode_doptions<U>(decoder: &mut Decoder<Plug>) -> Result<Box<dyn DebugDOptions>, Error>
        where
            U: Unit<Plug>,
            U::DOptions: fmt::Debug,
        {
            U::decode_doptions(decoder).map(|r| -> Box<dyn DebugDOptions> { Box::new(r) })
        }

        Self {
            encoder_mode_width: inner.encoder_mode_width(),
            decode_ioptions: decode_ioptions::<U>,
            decode_doptions: decode_doptions::<U>,
        }
    }
}

#[cfg(feature = "alloc")]
impl Default for Plug {
    fn default() -> Self {
        Self::new(&Reference)
    }
}

#[cfg(feature = "alloc")]
impl Unit for Plug {
    type IOptions = Box<dyn DebugIOptions>;
    type DOptions = Box<dyn DebugDOptions>;

    fn encoder_mode_width(&self) -> u8 {
        self.encoder_mode_width
    }

    fn decode_ioptions(decoder: &mut Decoder<Self>) -> Result<Self::IOptions, Error> {
        (decoder.unit().decode_ioptions)(decoder)
    }

    fn decode_doptions(decoder: &mut Decoder<Self>) -> Result<Self::DOptions, Error> {
        (decoder.unit().decode_doptions)(decoder)
    }
}

/// List of [`Plug`] constructors for all [`Unit`]s provided by this library
#[cfg(feature = "alloc")]
pub const PLUGS: &[PlugsEntry<'static>] = &[
    PlugsEntry::new(
        "reference",
        "Reference flow's original encoder model",
        || Plug::new(&Reference),
    ),
    PlugsEntry::new("pulp", "PULP plattform's rv_tracer", || Plug::new(&PULP)),
];

/// A single entry in a list of [`Plug`]s
#[cfg(feature = "alloc")]
#[derive(Copy, Clone, Debug)]
pub struct PlugsEntry<'a> {
    name: &'a str,
    description: &'a str,
    ctor: fn() -> Plug,
}

#[cfg(feature = "alloc")]
impl<'a> PlugsEntry<'a> {
    /// Create a new entry
    pub const fn new(name: &'a str, description: &'a str, ctor: fn() -> Plug) -> Self {
        Self {
            name,
            description,
            ctor,
        }
    }

    /// Retrieve the name associated to the [`Plug`]
    pub fn name(&self) -> &'a str {
        self.name
    }

    /// Retrieve a description of the [`Plug`]
    pub fn description(&self) -> &'a str {
        self.description
    }

    /// Create the [`Plug`] associated to this entry
    pub fn plug(&self) -> Plug {
        (self.ctor)()
    }
}

#[cfg(feature = "alloc")]
impl Default for PlugsEntry<'_> {
    fn default() -> Self {
        PLUGS[0]
    }
}

/// Type representing an empty set, zero-bit wide set of options
#[derive(Copy, Clone, Debug, Default)]
pub struct NoOptions;

impl<U> Decode<'_, U> for NoOptions {
    fn decode(_decoder: &mut Decoder<U>) -> Result<Self, Error> {
        Ok(Self)
    }
}

impl<U> Encode<'_, U> for NoOptions {
    fn encode(&self, _encoder: &mut Encoder<U>) -> Result<(), Error> {
        Ok(())
    }
}

impl IOptions for NoOptions {}
impl DOptions for NoOptions {}