riscv-etrace 0.6.2

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
// Copyright (C) 2025 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 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
/// a [`InstructionTrace`] payload if one was generated, with the expectation
/// that the payload will be forwarded via some sort of funnel.
///
/// 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 a
/// [`Drain`] [`Iterator`] over those payloads. If qualification was initiated
/// properly via [`begin_qualification`][Self::begin_qualification], [`Drain`]
/// 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) -> Drain<'_, S, I, D> {
        Drain::new(self, ienable)
    }

    /// 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>,
    ) -> Result<Option<InstructionTrace<I, D>>, Error> {
        if let Some(current) = self.current.as_mut() {
            current.refine(&step);
        }

        self.do_step(Some(step), event).map(|p| {
            if let Some(StepOutput::Payload(payload)) = p {
                Some(payload)
            } else {
                None
            }
        })
    }

    /// Drive the inner state by a single step, potentially producing a payload
    fn do_step(
        &mut self,
        next: Option<S>,
        next_event: Option<Event>,
    ) -> Result<Option<StepOutput<'_, I, D>>, Error> {
        use hart2enc::CType;
        use step::Kind;

        let current = self.current.take();
        self.current = next.clone();

        let Some(current) = current 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.previous = None;
            self.reported_exception = false;
            self.event = None;
            return Ok(None);
        };

        let kind = current.kind();

        let previous = self.previous.take();
        self.previous = Some((kind, current.context().privilege));

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

        let event = self.event.take();
        self.event = next_event;

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

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

        // Corresponds to `Exception previous?` in spec
        if let Some((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(StepOutput::Payload(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(StepOutput::Payload(builder.report_sync().into())));
        }

        // Corresponds to `Updiscon previous?` in spec
        let sijumps = self.features.sequentially_inferred_jumps;
        if previous.map(|(k, _)| k.is_updiscon(sijumps)) == Some(true) {
            return if let Kind::Trap {
                insn_size: None,
                info,
            } = kind
            {
                self.reported_exception = true;
                Ok(builder.report_trap(false, info).into())
            } else {
                let reason = if next
                    .as_ref()
                    .map(|n| {
                        next_event == Some(Event::ReSync)
                            || matches!(n.kind(), Kind::Trap { .. })
                            || !matches!(n.ctype(), CType::Unreported)
                            || current.context().privilege != n.context().privilege
                    })
                    .unwrap_or(self.options.is_some())
                {
                    state::Reason::Updiscon
                } else {
                    state::Reason::Other
                };
                builder.report_address(reason)
            }
            .map(Into::into);
        }

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

        if let Kind::Trap { insn_size, .. } = kind {
            return if insn_size.is_some() {
                builder.report_address(state::Reason::Other).map(Into::into)
            } else {
                Ok(None)
            };
        }

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

        // The following correspond to `Next inst is exc_only, ppccd_br or
        // unqualified?` in spec
        let Some(next) = next else {
            return Ok(builder.into());
        };

        let ppccd = next.context().privilege != 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(Into::into);
        }

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

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

/// 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,
}

/// Output potentially produced by the [`Generator`]
#[derive(Debug)]
enum StepOutput<'s, I: unit::IOptions, D> {
    Payload(InstructionTrace<I, D>),
    Builder(state::PayloadBuilder<'s>),
}

impl<I: unit::IOptions, D> From<InstructionTrace<I, D>> for Option<StepOutput<'_, I, D>> {
    fn from(payload: InstructionTrace<I, D>) -> Self {
        Some(StepOutput::Payload(payload))
    }
}

impl<'s, I: unit::IOptions, D> From<state::PayloadBuilder<'s>> for Option<StepOutput<'s, I, D>> {
    fn from(builder: state::PayloadBuilder<'s>) -> Self {
        Some(StepOutput::Builder(builder))
    }
}

/// 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,
        })
    }
}

/// Payload draining [`Iterator`]
#[derive(Debug)]
pub struct Drain<'g, S: step::Step, I: unit::IOptions, D> {
    gen: &'g mut Generator<S, I, D>,
    ienable: bool,
    qual_status: Option<sync::QualStatus>,
}

impl<'g, S: step::Step, I: unit::IOptions, D> Drain<'g, S, I, D> {
    /// Create a new draining [`Iterator`]
    fn new(gen: &'g mut Generator<S, I, D>, ienable: bool) -> Self {
        Drain {
            gen,
            ienable,
            qual_status: Some(sync::QualStatus::EndedRep),
        }
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        match self.gen.do_step(None, None) {
            Ok(Some(StepOutput::Payload(p))) => {
                self.qual_status = Some(sync::QualStatus::EndedNtr);
                Some(Ok(p))
            }
            Ok(Some(StepOutput::Builder(b))) => Some(b.report_address(state::Reason::Other)),
            Ok(None) => Option::zip(self.gen.options.clone(), self.qual_status.take()).map(
                |((ioptions, doptions), qual_status)| {
                    Ok(sync::Support {
                        ienable: self.ienable,
                        encoder_mode: sync::EncoderMode::BranchTrace,
                        qual_status,
                        ioptions,
                        denable: false,
                        dloss: false,
                        doptions,
                    }
                    .into())
                },
            ),
            Err(e) => Some(Err(e)),
        }
    }
}