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
// Copyright (C) 2025, 2026 FZI Forschungszentrum Informatik
// SPDX-License-Identifier: Apache-2.0
//! Payload generation utilities
//!
//! This module provides the payload [`Generator`], which processes
//! [`Step`][step::Step]s payloads and generates [`InstructionTrace`]s.

pub mod error;
pub mod hart2enc;
pub mod state;
pub mod step;

use crate::config::{self, AddressMode, Features};
use crate::packet::{payload, sync, unit};
use crate::types::Privilege;

use error::Error;
use hart2enc::CType;
use payload::InstructionTrace;

/// Generator for tracing payloads
///
/// A generator processes [`Step`][step::Step]s of execution on a single RISC-V
/// HART and generates [`InstructionTrace`] payloads.
///
/// A [`sync::Support`] payload signalling both begin of qualification may be
/// generated via [`begin_qualification`][Self::begin_qualification]. Calling
/// that fn will also configure the generator for the optional features included
/// in the payload, or return an error if the set of features is not supported.
///
/// Traces are generated by feeding [`Step`][step::Step]s of execution as well
/// as [`Event`]s via [`process_step`][Self::process_step]. That fn will return
/// an [`Output`] [`Iterator`] yielding generated payloads, with the expectation
/// that those payloads will be forwarded via some sort of funnel. Failure to
/// exhaust the [`Iterator`] may result in malformed payloads for subsequent
/// [`Step`][step::Step]s.
///
/// Once all relevant [`Step`][step::Step]s of execution were processed, users
/// may end qualification, extracting any pending [`InstructionTrace`] payloads
/// by calling [`end_qualification`][Self::end_qualification], which returns an
/// [`Output`] [`Iterator`] over those payloads. If qualification was initiated
/// properly via [`begin_qualification`][Self::begin_qualification], [`Output`]
/// will also yield a [`sync::Support`] payload indicating end of qualification.
///
/// Generators are constructed using a [`Builder`].
#[derive(Clone, Debug)]
pub struct Generator<S, I = unit::ReferenceIOptions, D = unit::ReferenceDOptions>
where
    S: step::Step,
    I: unit::IOptions,
{
    state: state::State,
    features: Features,
    options: Option<(I, D)>,
    current: Option<S>,
    previous: Option<(step::Kind, Privilege)>,
    reported_exception: bool,
    event: Option<Event>,
}

impl<S: step::Step + Clone, I: unit::IOptions + Clone, D: Clone> Generator<S, I, D> {
    /// Begin qualification, generating a [`sync::Support`] payload
    ///
    /// Extracts the selection of optional [`Features`] and the [`AddressMode`]
    /// from the `ioptions`. If all features are supported, this fn feturns a
    /// [`sync::Support`] payload with the given `ioptions` and `doptions`.
    /// Otherwise an error is returned.
    pub fn begin_qualification(
        &mut self,
        ioptions: I,
        doptions: D,
    ) -> Result<sync::Support<I, D>, Error> {
        ioptions
            .update_features(&mut self.features)
            .map_err(Error::UnsupportedFeature)?;
        if self.features.implicit_returns {
            return Err(Error::UnsupportedFeature("implicit return"));
        }
        if let Some(mode) = ioptions.address_mode() {
            self.state.set_address_mode(mode);
        }

        self.options = Some((ioptions.clone(), doptions.clone()));
        Ok(sync::Support {
            ienable: true,
            encoder_mode: sync::EncoderMode::BranchTrace,
            qual_status: sync::QualStatus::NoChange,
            ioptions,
            denable: false,
            dloss: false,
            doptions,
        })
    }

    /// End qualifiation, returning an [`Iterator`] over remaining payloads
    ///
    /// Ends qualification and returns an [`Iterator`] over at most two items: a
    /// payload indicating an address and one [`sync::Support`] payload with the
    /// given `ienable` value.
    ///
    /// The address payload is included if the current address was not yet
    /// reported due to other reasons. The support payload is included if
    /// [`begin_qualification`][Self::begin_qualification] was called on this
    /// generator before.
    pub fn end_qualification(&mut self, ienable: bool) -> Output<'_, S, I, D> {
        self.do_step(OutputKind::Draining { ienable }, None)
    }

    /// Process a single [Step][step::Step], potentially producing a payload
    ///
    /// Drives the inner state, feeding the given `step` and optional `event`
    /// for the next step. If a payload is produced for the current step, that
    /// payload is returned.
    pub fn process_step(&mut self, step: S, event: Option<Event>) -> Output<'_, S, I, D> {
        if let Some(current) = self.current.as_mut() {
            current.refine(&step);
        }

        let kind = OutputKind::Regular {
            next_kind: step.kind(),
            next_ctype: step.ctype(),
            next_priv: step.context().privilege,
            next_event: event,
        };
        self.do_step(kind, Some(step))
    }

    /// Drive the inner state by a single step, potentially producing a payload
    fn do_step(&mut self, kind: OutputKind, next: Option<S>) -> Output<'_, S, I, D> {
        let current = self.current.take();
        let event = self.event.take();
        let previous = self.previous.take();

        self.current = next;
        if let OutputKind::Regular { next_event, .. } = &kind {
            self.event = *next_event;
        }

        let state = if let Some(current) = current {
            self.previous = Some((current.kind(), current.context().privilege));

            Some(OutputState::First {
                previous,
                current,
                event,
            })
        } else {
            // We cannot and do not generate a payload without a current step.
            // This corresponds to the `N` vertex for the `Qualified?` node in
            // the spec.
            self.reported_exception = false;
            None
        };

        Output {
            generator: self,
            kind,
            state,
        }
    }
}

/// An event causing additional reporting
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Event {
    /// The resync counter reached the threshold value
    ReSync,
    /// Notification was requested for this step
    Notify,
}

/// Create a new [`Builder`] for [`Generator`]s
pub fn builder() -> Builder {
    Default::default()
}

/// Builder for [`Generator`]s
///
/// A builder will build a single [`Generator`] for a single RISC-V hart.
///
/// If multiple harts are to be traced, multiple [`Generator`]s need to be
/// built.
#[derive(Copy, Clone, Default)]
pub struct Builder {
    features: Features,
    address_mode: AddressMode,
}

impl Builder {
    /// Build the [`Generator`] with the given [`config::Parameters`]
    ///
    /// New builders assume [`Default`] parameters.
    pub fn with_params(self, config: &config::Parameters) -> Self {
        Self {
            features: Features {
                sequentially_inferred_jumps: config.sijump_p,
                ..self.features
            },
            ..self
        }
    }

    /// Build a [`Generator`] in the given [`AddressMode`]
    ///
    /// New builders are configured for [`AddressMode::Delta`].
    pub fn with_address_mode(self, mode: AddressMode) -> Self {
        Self {
            address_mode: mode,
            ..self
        }
    }

    /// Build a [`Generator`] with implicit return enabled or disabled
    ///
    /// New builders are configured for no implicit return.
    pub fn with_implicit_return(self, implicit_returns: bool) -> Self {
        Self {
            features: Features {
                implicit_returns,
                ..self.features
            },
            ..self
        }
    }

    /// Build a [`Generator`]
    pub fn build<S, I, D>(&self) -> Result<Generator<S, I, D>, Error>
    where
        S: step::Step,
        I: unit::IOptions,
    {
        let state = state::State::new(self.address_mode);
        Ok(Generator {
            state,
            features: self.features,
            options: None,
            current: None,
            previous: None,
            reported_exception: false,
            event: None,
        })
    }
}

/// Output produced by a [`Generator`] for a single [`Step`][step::Step]
#[derive(Debug)]
pub struct Output<'g, S, I = unit::ReferenceIOptions, D = unit::ReferenceDOptions>
where
    S: step::Step,
    I: unit::IOptions,
{
    generator: &'g mut Generator<S, I, D>,
    kind: OutputKind,
    state: Option<OutputState<S>>,
}

impl<S: step::Step, I: unit::IOptions, D> Output<'_, S, I, D> {
    /// Handle the start of the given block, potentially issuing a payload
    fn do_block_start(
        &mut self,
        previous: Option<(step::Kind, Privilege)>,
        current: &S,
        event: Option<Event>,
    ) -> Result<Option<InstructionTrace<I, D>>, Error> {
        let kind = current.kind();

        let reported_exception = self.generator.reported_exception;
        self.generator.reported_exception = false;

        let mut builder = self.generator.state.payload_builder(
            current.address(),
            current.context(),
            current.timestamp(),
        );

        // Corresponds to `Branch?` in spec
        if let step::Kind::Branch { taken, .. } = kind {
            builder.add_branch(taken, current.is_single())?;
        }

        // Corresponds to `Exception previous?` in spec
        if let Some((step::Kind::Trap { info, .. }, _)) = previous {
            let payload = if kind.is_exc_only() {
                builder.report_trap(false, info).into()
            } else if reported_exception {
                builder.report_sync().into()
            } else {
                builder.report_trap(true, info).into()
            };
            return Ok(Some(payload));
        }

        // Corresponds to `Inst is 1st qualified, ppccd or >max_resync?` in spec
        if event == Some(Event::ReSync)
            || matches!(current.ctype(), CType::Precisely | CType::AsyncDiscon)
            || previous.map(|(_, p)| p) != Some(current.context().privilege)
        {
            return Ok(Some(builder.report_sync().into()));
        }

        // Corresponds to `Updiscon previous?` in spec
        let sijumps = self.generator.features.sequentially_inferred_jumps;
        if previous.map(|(k, _)| k.is_updiscon(sijumps)) == Some(true) {
            return if let step::Kind::Trap {
                insn_size: None,
                info,
            } = kind
            {
                self.generator.reported_exception = true;
                Ok(builder.report_trap(false, info).into())
            } else {
                let reason = if self
                    .kind
                    .is_updiscon_cause(current.context().privilege)
                    .unwrap_or(self.generator.options.is_some())
                {
                    state::Reason::Updiscon
                } else {
                    state::Reason::Other
                };
                builder.report_address(reason)
            }
            .map(Some);
        }

        Ok(None)
    }

    /// Handle the end of the given block, potentially issuing a payload
    fn do_block_end(
        &mut self,
        current: &S,
        event: Option<Event>,
    ) -> Result<Option<InstructionTrace<I, D>>, Error> {
        let mut builder = self.generator.state.payload_builder(
            current.last_address(),
            current.context(),
            current.timestamp(),
        );

        // The following correspond to `resync_br or er_n?` in spec
        if event == Some(Event::Notify) {
            return builder.report_address(state::Reason::Notify).map(Some);
        }

        if let step::Kind::Trap { insn_size, .. } = current.kind() {
            // We return for traps in any case since payload generation is only
            // valid for non-trap steps for any of all of the remaining cases.
            return if insn_size.is_some() {
                builder.report_address(state::Reason::Other).map(Some)
            } else {
                Ok(None)
            };
        }

        // The following correspond to `Next inst is exc_only, ppccd_br or
        // unqualified?` in spec
        let OutputKind::Regular {
            next_kind,
            next_ctype,
            next_priv,
            next_event,
        } = self.kind
        else {
            return Ok(None);
        };

        let have_branches = builder.branches() != 0;
        if next_event == Some(Event::ReSync) && have_branches {
            return builder.report_address(state::Reason::Other).map(Some);
        }

        let ppccd = next_priv != current.context().privilege
            || matches!(next_ctype, CType::Precisely | CType::AsyncDiscon);
        if next_kind.is_exc_only() || (ppccd && have_branches) {
            return builder.report_address(state::Reason::Other).map(Some);
        }

        // Corresponds to `rpt_br?` in spec
        if let Some(branches) = builder.report_full_branchmap() {
            return Ok(Some(branches.into()));
        }

        // Corresponds to `cci?` in spec
        match current.ctype() {
            CType::Imprecisely => Ok(Some(builder.context().into())),
            _ => Ok(None),
        }
    }
}

impl<S: step::Step, I: unit::IOptions + Clone, D: Clone> Iterator for Output<'_, S, I, D> {
    type Item = Result<InstructionTrace<I, D>, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.state.take()? {
            OutputState::First {
                previous,
                current,
                event,
            } => {
                let res = self.do_block_start(previous, &current, event).transpose();
                if res.is_none() {
                    self.state = Some(OutputState::Last { current, event });
                    return self.next();
                }
                if !current.is_single() {
                    self.state = Some(OutputState::Last { current, event });
                } else if let OutputKind::Draining { ienable } = &self.kind {
                    self.state = Some(OutputState::End {
                        ienable: *ienable,
                        qual_status: sync::QualStatus::EndedNtr,
                    });
                }
                res
            }
            OutputState::Last { current, event } => {
                let res = self.do_block_end(&current, event).transpose();
                let OutputKind::Draining { ienable } = &self.kind else {
                    return res;
                };

                let qual_status = match res.is_some() {
                    true => sync::QualStatus::EndedNtr,
                    false => sync::QualStatus::EndedRep,
                };
                self.state = Some(OutputState::End {
                    ienable: *ienable,
                    qual_status,
                });
                res.or_else(|| {
                    let res = self
                        .generator
                        .state
                        .payload_builder(
                            current.last_address(),
                            current.context(),
                            current.timestamp(),
                        )
                        .report_address(state::Reason::Other);
                    Some(res)
                })
            }
            OutputState::End {
                ienable,
                qual_status,
            } => {
                let (ioptions, doptions) = self.generator.options.clone()?;
                Some(Ok(sync::Support {
                    ienable,
                    encoder_mode: sync::EncoderMode::BranchTrace,
                    qual_status,
                    ioptions,
                    denable: false,
                    dloss: false,
                    doptions,
                }
                .into()))
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.state {
            Some(OutputState::First { .. }) => (1, Some(3)),
            Some(OutputState::Last { .. }) => (1, Some(2)),
            Some(OutputState::End { .. }) => (1, Some(1)),
            None => (0, Some(0)),
        }
    }
}

/// State of the [`Output`]
#[derive(Copy, Clone, Debug)]
enum OutputState<S> {
    /// Handling the first instruction in the block
    First {
        previous: Option<(step::Kind, Privilege)>,
        current: S,
        event: Option<Event>,
    },
    /// Handling the last instruction in the block
    Last { current: S, event: Option<Event> },
    /// End-of-trace condition
    End {
        ienable: bool,
        qual_status: sync::QualStatus,
    },
}

/// Kind of [`Output`]
#[derive(Copy, Clone, Debug)]
enum OutputKind {
    /// Regular tracing operation
    ///
    /// A new [`Step`]s was fed to the [`Generator`], resulting in this
    /// [`Output`].
    Regular {
        next_kind: step::Kind,
        next_ctype: CType,
        next_priv: Privilege,
        next_event: Option<Event>,
    },
    /// Draining a [`Generator`]'s inner state
    Draining { ienable: bool },
}

impl OutputKind {
    /// Determine whether the next [`Step`] warrants address with updiscon flag
    pub fn is_updiscon_cause(&self, privilege: Privilege) -> Option<bool> {
        let Self::Regular {
            next_kind,
            next_ctype,
            next_priv,
            next_event,
        } = self
        else {
            return None;
        };

        let res = *next_event == Some(Event::ReSync)
            || matches!(next_kind, step::Kind::Trap { .. })
            || !matches!(next_ctype, CType::Unreported)
            || privilege != *next_priv;
        Some(res)
    }
}