ab-riscv-interpreter 0.0.2

Composable and generic RISC-V interpreter
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
extern crate alloc;

use crate::v::vector_registers::{
    VectorRegisterFile, VectorRegisters, VectorRegistersBase, VectorRegistersExt,
};
use crate::{
    Address, BasicInt, CsrError, Csrs, CustomErrorPlaceholder, ExecutableInstruction,
    ExecutionError, FetchInstructionResult, InstructionFetcher, InterpreterState, ProgramCounter,
    ProgramCounterError, SystemInstructionHandler, VirtualMemory, VirtualMemoryError,
};
use ab_riscv_primitives::instructions::Instruction;
use ab_riscv_primitives::instructions::rv64::Rv64Instruction;
use ab_riscv_primitives::instructions::v::Vtype;
use ab_riscv_primitives::privilege::PrivilegeLevel;
use ab_riscv_primitives::registers::general_purpose::{Reg, Registers};
use ab_riscv_primitives::registers::vector::VCsr;
use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
use core::marker::PhantomData;
use core::ops::ControlFlow;

pub(crate) const TEST_BASE_ADDR: u64 = 0x1000;
const TRAP_ADDRESS: u64 = 0;
/// Zve64x element width
const ZVE64X_ELEN: u32 = 64;
/// VLEN in bits for the test vector register file
const TEST_VLEN: u32 = 128;
/// VLEN in bytes
const TEST_VLENB: usize = (TEST_VLEN / u8::BITS) as usize;

/// Simple test memory implementation
pub(crate) struct TestMemory {
    data: Vec<u8>,
    base_addr: u64,
}

impl TestMemory {
    fn new(size: usize, base_addr: u64) -> Self {
        Self {
            data: vec![0; size],
            base_addr,
        }
    }
}

impl VirtualMemory for TestMemory {
    fn read<T>(&self, address: u64) -> Result<T, VirtualMemoryError>
    where
        T: BasicInt,
    {
        let offset = address
            .checked_sub(self.base_addr)
            .ok_or(VirtualMemoryError::OutOfBoundsRead { address })?;

        if offset.saturating_add(size_of::<T>() as u64) > self.data.len() as u64 {
            return Err(VirtualMemoryError::OutOfBoundsRead { address });
        }

        // SAFETY: Only reading basic integers from initialized memory
        unsafe {
            Ok(self
                .data
                .as_ptr()
                .cast::<T>()
                .byte_add(offset as usize)
                .read_unaligned())
        }
    }

    unsafe fn read_unchecked<T>(&self, address: u64) -> T
    where
        T: BasicInt,
    {
        // SAFETY: Guaranteed by function contract
        unsafe {
            let offset = address.unchecked_sub(self.base_addr) as usize;
            self.data
                .as_ptr()
                .cast::<T>()
                .byte_add(offset)
                .read_unaligned()
        }
    }

    fn read_slice(&self, address: u64, len: u32) -> Result<&[u8], VirtualMemoryError> {
        let offset = address
            .checked_sub(self.base_addr)
            .ok_or(VirtualMemoryError::OutOfBoundsRead { address })?;

        if offset > self.data.len() as u64 {
            return Err(VirtualMemoryError::OutOfBoundsRead { address });
        }

        self.data
            .get(offset as usize..)
            .and_then(|data| data.get(..len as usize))
            .ok_or(VirtualMemoryError::OutOfBoundsRead { address })
    }

    fn read_slice_up_to(&self, address: u64, len: u32) -> &[u8] {
        let Some(offset) = address.checked_sub(self.base_addr) else {
            return &[];
        };

        if offset > self.data.len() as u64 {
            return &[];
        }

        let remaining = self.data.get(offset as usize..).unwrap_or_default();
        remaining.get(..len as usize).unwrap_or(remaining)
    }

    fn write<T>(&mut self, address: u64, value: T) -> Result<(), VirtualMemoryError>
    where
        T: BasicInt,
    {
        let offset = address
            .checked_sub(self.base_addr)
            .ok_or(VirtualMemoryError::OutOfBoundsWrite { address })?;

        if offset.saturating_add(size_of::<T>() as u64) > self.data.len() as u64 {
            return Err(VirtualMemoryError::OutOfBoundsWrite { address });
        }

        // SAFETY: Only writing basic integers to initialized memory
        unsafe {
            self.data
                .as_mut_ptr()
                .cast::<T>()
                .byte_add(offset as usize)
                .write_unaligned(value);
        }

        Ok(())
    }

    fn write_slice(&mut self, address: u64, data: &[u8]) -> Result<(), VirtualMemoryError> {
        let offset = address
            .checked_sub(self.base_addr)
            .ok_or(VirtualMemoryError::OutOfBoundsWrite { address })?;

        if offset > self.data.len() as u64 {
            return Err(VirtualMemoryError::OutOfBoundsWrite { address });
        }

        let len = data.len();
        self.data
            .get_mut(offset as usize..)
            .and_then(|data| data.get_mut(..len))
            .ok_or(VirtualMemoryError::OutOfBoundsWrite { address })?
            .copy_from_slice(data);

        Ok(())
    }
}

/// Custom instruction handler for tests that returns instructions from a sequence
pub(crate) struct TestInstructionFetcher<I> {
    instructions: Vec<I>,
    return_trap_address: u64,
    base_address: u64,
    pc: u64,
}

impl<I> ProgramCounter<u64, TestMemory> for TestInstructionFetcher<I>
where
    I: Instruction<Reg = Reg<u64>>,
{
    #[inline(always)]
    fn get_pc(&self) -> u64 {
        self.pc
    }

    fn set_pc(
        &mut self,
        _memory: &TestMemory,
        pc: u64,
    ) -> Result<ControlFlow<()>, ProgramCounterError<u64>> {
        self.pc = pc;

        Ok(ControlFlow::Continue(()))
    }
}

impl<I> InstructionFetcher<I, TestMemory> for TestInstructionFetcher<I>
where
    I: Instruction<Reg = Reg<u64>>,
{
    #[inline]
    fn fetch_instruction(
        &mut self,
        _memory: &TestMemory,
    ) -> Result<FetchInstructionResult<I>, ExecutionError<Address<I>>> {
        if self.pc == self.return_trap_address {
            return Ok(FetchInstructionResult::ControlFlow(ControlFlow::Break(())));
        }

        let Some(&instruction) = self
            .instructions
            .get((self.pc - self.base_address) as usize / size_of::<u32>())
        else {
            return Ok(FetchInstructionResult::ControlFlow(ControlFlow::Break(())));
        };
        self.pc += u64::from(instruction.size());

        Ok(FetchInstructionResult::Instruction(instruction))
    }
}

impl<I> TestInstructionFetcher<I> {
    /// Create a new instance
    #[inline(always)]
    fn new(instructions: Vec<I>, return_trap_address: u64, base_address: u64, pc: u64) -> Self {
        Self {
            instructions,
            return_trap_address,
            base_address,
            pc,
        }
    }
}

pub(crate) struct TestInstructionHandler;

impl<I> SystemInstructionHandler<Reg<u64>, TestMemory, TestInstructionFetcher<I>>
    for TestInstructionHandler
where
    I: Instruction<Reg = Reg<u64>>,
{
    #[inline(always)]
    fn handle_ecall(
        &mut self,
        _regs: &mut Registers<Reg<u64>>,
        _memory: &mut TestMemory,
        program_counter: &mut TestInstructionFetcher<I>,
    ) -> Result<ControlFlow<()>, ExecutionError<u64>> {
        Err(ExecutionError::EcallUnsupported {
            address: program_counter.old_pc(Rv64Instruction::<Reg<u64>>::Ecall.size()),
        })
    }
}

struct CsrExtState {
    privilege_level: PrivilegeLevel,
    csrs: BTreeMap<u16, u64>,
    prepare_csr_read: fn(csr_index: u16, raw_value: u64) -> Result<u64, CsrError>,
    prepare_csr_write: fn(csr_index: u16, write_value: u64) -> Result<u64, CsrError>,
}

impl Default for CsrExtState {
    #[inline(always)]
    fn default() -> Self {
        Self {
            privilege_level: PrivilegeLevel::Machine,
            csrs: BTreeMap::new(),
            prepare_csr_read: |csr_index, _| Err(CsrError::IllegalRead { csr_index }),
            prepare_csr_write: |csr_index, _| Err(CsrError::IllegalWrite { csr_index }),
        }
    }
}

struct VectorExtState {
    vregs: VectorRegisterFile<TEST_VLENB>,
    vtype: Option<Vtype<ZVE64X_ELEN, TEST_VLEN>>,
    vtype_raw: u64,
    vl: u32,
    vs_dirty_count: u32,
    vector_allowed: bool,
}

impl Default for VectorExtState {
    fn default() -> Self {
        Self {
            vregs: VectorRegisterFile::default(),
            vtype: None,
            vtype_raw: 1u64 << (u64::BITS - 1),
            vl: 0,
            vs_dirty_count: 0,
            vector_allowed: true,
        }
    }
}

pub(crate) struct ExtState {
    csr: CsrExtState,
    vector: VectorExtState,
}

impl Default for ExtState {
    #[inline(always)]
    fn default() -> Self {
        Self {
            csr: CsrExtState::default(),
            vector: VectorExtState::default(),
        }
    }
}

impl Csrs<Reg<u64>> for ExtState {
    fn privilege_level(&self) -> PrivilegeLevel {
        self.csr.privilege_level
    }

    fn read_csr(&self, csr_index: u16) -> Result<u64, CsrError> {
        self.csr
            .csrs
            .get(&csr_index)
            .copied()
            .ok_or(CsrError::IllegalRead { csr_index })
    }

    fn write_csr(&mut self, csr_index: u16, value: u64) -> Result<(), CsrError> {
        let stored_value = self
            .csr
            .csrs
            .get_mut(&csr_index)
            .ok_or(CsrError::IllegalWrite { csr_index })?;
        *stored_value = value;
        Ok(())
    }

    fn process_csr_read(&self, csr_index: u16, raw_value: u64) -> Result<u64, CsrError> {
        (self.csr.prepare_csr_read)(csr_index, raw_value)
    }

    fn process_csr_write(&mut self, csr_index: u16, write_value: u64) -> Result<u64, CsrError> {
        (self.csr.prepare_csr_write)(csr_index, write_value)
    }
}

impl VectorRegistersBase for ExtState {
    const ELEN: u32 = ZVE64X_ELEN;
    const VLEN: u32 = TEST_VLEN;
}

impl VectorRegisters for ExtState
where
    Self: Csrs<Reg<u64>>,
    [(); Self::ELEN as usize]:,
    [(); Self::VLEN as usize]:,
{
    fn read_vreg(&self) -> &VectorRegisterFile<{ Self::VLENB as usize }> {
        &self.vector.vregs
    }

    fn write_vreg(&mut self) -> &mut VectorRegisterFile<{ Self::VLENB as usize }> {
        &mut self.vector.vregs
    }

    fn vtype(&self) -> Option<Vtype<{ Self::ELEN }, { Self::VLEN }>> {
        self.vector.vtype
    }

    fn set_vtype(&mut self, vtype: Option<Vtype<{ Self::ELEN }, { Self::VLEN }>>) {
        self.vector.vtype = vtype;
        match vtype {
            Some(vt) => {
                self.vector.vtype_raw = vt.to_raw::<Reg<u64>>();
                self.write_csr(VCsr::Vtype as u16, self.vector.vtype_raw)
                    .expect("Implementation didn't initialize `vtype` CSR");
            }
            None => {
                // vill: bit `XLEN-1` set, rest zero
                self.vector.vtype_raw = 1u64 << (u64::BITS - 1);
                self.write_csr(VCsr::Vtype as u16, self.vector.vtype_raw)
                    .expect("Implementation didn't initialize `vtype` CSR");
            }
        }
    }

    fn vl(&self) -> u32 {
        self.vector.vl
    }

    fn set_vl(&mut self, vl: u32) {
        self.vector.vl = vl;
        self.write_csr(VCsr::Vl as u16, vl as u64)
            .expect("Implementation didn't initialize `vl` CSR");
    }

    fn vector_instructions_allowed(&self) -> bool {
        self.vector.vector_allowed
    }

    fn mark_vs_dirty(&mut self) {
        self.vector.vs_dirty_count += 1;
    }
}

impl VectorRegistersExt<Reg<u64>> for ExtState {}

impl ExtState {
    pub(crate) fn set_privilege_level(&mut self, privilege_level: PrivilegeLevel) {
        self.csr.privilege_level = privilege_level;
    }

    pub(crate) fn set_prepare_csr_read_write(
        &mut self,
        prepare_csr_read: fn(csr_index: u16, raw_value: u64) -> Result<u64, CsrError>,
        prepare_csr_write: fn(csr_index: u16, write_value: u64) -> Result<u64, CsrError>,
    ) {
        self.csr.prepare_csr_read = prepare_csr_read;
        self.csr.prepare_csr_write = prepare_csr_write;
    }

    /// Initialize a single CSR (without this attempts to read or write this `csr_index` will fail)
    pub(crate) fn init_csr(&mut self, csr_index: u16, value: u64) {
        self.csr.csrs.insert(csr_index, value);
    }

    /// Initialize all vector CSRs with default values
    pub(crate) fn init_vector_csrs(&mut self) {
        // Initialize all vector CSRs
        self.init_csr(VCsr::Vstart as u16, 0);
        self.init_csr(VCsr::Vxsat as u16, 0);
        self.init_csr(VCsr::Vxrm as u16, 0);
        self.init_csr(VCsr::Vcsr as u16, 0);
        self.init_csr(VCsr::Vl as u16, 0);
        self.init_csr(VCsr::Vtype as u16, 1u64 << (u64::BITS - 1));
        self.init_csr(VCsr::Vlenb as u16, u64::from(Self::VLENB));
        // Fill them with default values
        self.initialize_vector_state();
    }

    /// Configure whether vector instructions are allowed
    pub(crate) fn set_vector_allowed(&mut self, vector_allowed: bool) {
        self.vector.vector_allowed = vector_allowed;
    }

    /// Get the current vector dirty count value
    pub(crate) fn vs_dirty_count(&self) -> u32 {
        self.vector.vs_dirty_count
    }
}

pub(crate) type TestInterpreterState<Instruction> = InterpreterState<
    Reg<u64>,
    ExtState,
    TestMemory,
    TestInstructionFetcher<Instruction>,
    TestInstructionHandler,
>;

pub(crate) fn initialize_state<I, Instructions>(
    instructions: Instructions,
) -> TestInterpreterState<I>
where
    I: Instruction<Reg = Reg<u64>>,
    Instructions: Into<Vec<I>>,
{
    InterpreterState {
        regs: Registers::default(),
        ext_state: ExtState::default(),
        memory: TestMemory::new(8192, TEST_BASE_ADDR),
        instruction_fetcher: TestInstructionFetcher::new(
            instructions.into(),
            TRAP_ADDRESS,
            TEST_BASE_ADDR,
            TEST_BASE_ADDR,
        ),
        system_instruction_handler: TestInstructionHandler,
        custom_error: PhantomData,
    }
}

pub(crate) fn execute<I>(
    state: &mut TestInterpreterState<I>,
) -> Result<(), ExecutionError<Address<I>>>
where
    I: Instruction<Reg = Reg<u64>>
        + ExecutableInstruction<TestInterpreterState<I>, CustomErrorPlaceholder>,
{
    loop {
        let instruction = match state.instruction_fetcher.fetch_instruction(&state.memory)? {
            FetchInstructionResult::Instruction(instruction) => instruction,
            FetchInstructionResult::ControlFlow(ControlFlow::Continue(())) => {
                continue;
            }
            FetchInstructionResult::ControlFlow(ControlFlow::Break(())) => {
                break;
            }
        };

        match instruction.execute(state)? {
            ControlFlow::Continue(()) => {
                continue;
            }
            ControlFlow::Break(()) => {
                break;
            }
        }
    }

    Ok(())
}