repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/model_emulated.rs | hw-model/src/model_emulated.rs | // Licensed under the Apache-2.0 license
use std::cell::Cell;
use std::collections::hash_map::DefaultHasher;
use std::error::Error;
use std::hash::Hasher;
use std::io::Write;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::mpsc;
use caliptra_api::soc_mgr::SocManager;
use caliptra_api_types::Fuses;
use caliptra_emu_bus::Clock;
use caliptra_emu_bus::Device;
use caliptra_emu_bus::Event;
use caliptra_emu_bus::EventData;
use caliptra_emu_bus::{Bus, BusMmio};
#[cfg(feature = "coverage")]
use caliptra_emu_cpu::CoverageBitmaps;
use caliptra_emu_cpu::{Cpu, CpuArgs, InstrTracer, Pic};
use caliptra_emu_periph::dma::axi_root_bus::AxiRootBus;
use caliptra_emu_periph::dma::recovery::RecoveryControl;
use caliptra_emu_periph::ActionCb;
use caliptra_emu_periph::MailboxExternal;
use caliptra_emu_periph::Mci;
use caliptra_emu_periph::ReadyForFwCb;
use caliptra_emu_periph::{
CaliptraRootBus, CaliptraRootBusArgs, MailboxRequester, SocToCaliptraBus, TbServicesCb,
};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use caliptra_hw_model_types::ErrorInjectionMode;
use caliptra_image_types::IMAGE_MANIFEST_BYTE_SIZE;
use caliptra_registers::i3ccsr::regs::DeviceStatus0ReadVal;
use tock_registers::interfaces::{ReadWriteable, Readable};
use crate::bus_logger::BusLogger;
use crate::bus_logger::LogFile;
use crate::trace_path_or_env;
use crate::HwModel;
use crate::InitParams;
use crate::ModelError;
use crate::Output;
use crate::TrngMode;
pub struct EmulatedApbBus<'a> {
model: &'a mut ModelEmulated,
}
impl Bus for EmulatedApbBus<'_> {
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, caliptra_emu_bus::BusError> {
let result = self.model.soc_to_caliptra_bus.read(size, addr);
self.model.cpu.bus.log_read("SoC", size, addr, result);
result
}
fn write(
&mut self,
size: RvSize,
addr: RvAddr,
val: RvData,
) -> Result<(), caliptra_emu_bus::BusError> {
let result = self.model.soc_to_caliptra_bus.write(size, addr, val);
self.model.cpu.bus.log_write("SoC", size, addr, val, result);
result
}
}
/// Emulated model
pub struct ModelEmulated {
cpu: Cpu<BusLogger<CaliptraRootBus>>,
soc_to_caliptra_bus: SocToCaliptraBus,
output: Output,
trace_fn: Option<Box<InstrTracer<'static>>>,
ready_for_fw: Rc<Cell<bool>>,
cpu_enabled: Rc<Cell<bool>>,
trace_path: Option<PathBuf>,
fuses: Fuses,
// Keep this even when not including the coverage feature to keep the
// interface consistent
_rom_image_tag: u64,
iccm_image_tag: Option<u64>,
trng_mode: TrngMode,
events_to_caliptra: mpsc::Sender<Event>,
events_from_caliptra: mpsc::Receiver<Event>,
collected_events_from_caliptra: Vec<Event>,
pub mci: Mci,
}
#[cfg(feature = "coverage")]
impl Drop for ModelEmulated {
fn drop(&mut self) {
let cov_path =
std::env::var(caliptra_coverage::CPTRA_COVERAGE_PATH).unwrap_or_else(|_| "".into());
if cov_path.is_empty() {
return;
}
let CoverageBitmaps { rom, iccm } = self.code_coverage_bitmap();
let _ = caliptra_coverage::dump_emu_coverage_to_file(
cov_path.as_str(),
self._rom_image_tag,
rom,
);
if let Some(iccm_image_tag) = self.iccm_image_tag {
let _ = caliptra_coverage::dump_emu_coverage_to_file(
cov_path.as_str(),
iccm_image_tag,
iccm,
);
}
}
}
#[cfg(feature = "coverage")]
impl ModelEmulated {
pub fn code_coverage_bitmap(&self) -> CoverageBitmaps {
self.cpu.code_coverage.code_coverage_bitmap()
}
}
fn hash_slice(slice: &[u8]) -> u64 {
let mut hasher = DefaultHasher::new();
std::hash::Hash::hash_slice(slice, &mut hasher);
hasher.finish()
}
impl SocManager for ModelEmulated {
type TMmio<'a> = BusMmio<EmulatedApbBus<'a>>;
fn delay(&mut self) {
self.step();
}
fn mmio_mut(&mut self) -> Self::TMmio<'_> {
BusMmio::new(self.apb_bus())
}
const SOC_IFC_ADDR: u32 = 0x3003_0000;
const SOC_IFC_TRNG_ADDR: u32 = 0x3003_0000;
const SOC_MBOX_ADDR: u32 = 0x3002_0000;
const MAX_WAIT_CYCLES: u32 = 20_000_000;
}
impl HwModel for ModelEmulated {
type TBus<'a> = EmulatedApbBus<'a>;
fn new_unbooted(params: InitParams) -> Result<Self, Box<dyn Error>>
where
Self: Sized,
{
let clock = Rc::new(Clock::new());
let pic = Rc::new(Pic::new());
let timer = clock.timer();
let args = CpuArgs::default();
let ready_for_fw = Rc::new(Cell::new(false));
let ready_for_fw_clone = ready_for_fw.clone();
let cpu_enabled = Rc::new(Cell::new(false));
let cpu_enabled_cloned = cpu_enabled.clone();
let output = Output::new(params.log_writer);
let output_sink = output.sink().clone();
let bus_args = CaliptraRootBusArgs {
rom: params.rom.into(),
tb_services_cb: TbServicesCb::new(move |ch| {
output_sink.set_now(timer.now());
output_sink.push_uart_char(ch);
}),
ready_for_fw_cb: ReadyForFwCb::new(move |_| {
ready_for_fw_clone.set(true);
}),
bootfsm_go_cb: ActionCb::new(move || {
cpu_enabled_cloned.set(true);
}),
security_state: params.security_state,
dbg_manuf_service_req: params.dbg_manuf_service,
subsystem_mode: params.subsystem_mode,
ocp_lock_en: params.ocp_lock_en,
prod_dbg_unlock_keypairs: params.prod_dbg_unlock_keypairs,
debug_intent: params.debug_intent,
cptra_obf_key: params.cptra_obf_key,
itrng_nibbles: Some(params.itrng_nibbles),
etrng_responses: params.etrng_responses,
test_sram: params.test_sram,
clock: clock.clone(),
pic: pic.clone(),
..CaliptraRootBusArgs::default()
};
let mut root_bus = CaliptraRootBus::new(bus_args);
let trng_mode = TrngMode::resolve(params.trng_mode);
let hw_config = {
let mut hw_config = 0;
if matches!(trng_mode, TrngMode::Internal) {
hw_config |= 1;
}
if params.subsystem_mode {
hw_config |= 1 << 5
}
if params.ocp_lock_en {
hw_config |= 1 << 6
}
hw_config
};
root_bus.soc_reg.set_hw_config(hw_config.into());
let input_wires = (!params.uds_fuse_row_granularity_64 as u32) << 31;
root_bus.soc_reg.set_generic_input_wires(&[input_wires, 0]);
let ss_strap_generic_reg_0 = params.otp_dai_idle_bit_offset << 16;
let ss_strap_generic_reg_1 = params.otp_direct_access_cmd_reg_offset;
root_bus
.soc_reg
.set_strap_generic(&[ss_strap_generic_reg_0, ss_strap_generic_reg_1, 0, 0]);
{
let mut iccm_ram = root_bus.iccm.ram().borrow_mut();
let Some(iccm_dest) = iccm_ram.data_mut().get_mut(0..params.iccm.len()) else {
return Err(ModelError::ProvidedIccmTooLarge.into());
};
iccm_dest.copy_from_slice(params.iccm);
let Some(dccm_dest) = root_bus.dccm.data_mut().get_mut(0..params.dccm.len()) else {
return Err(ModelError::ProvidedDccmTooLarge.into());
};
dccm_dest.copy_from_slice(params.dccm);
}
let soc_to_caliptra_bus = root_bus.soc_to_caliptra_bus(params.soc_user);
let (events_to_caliptra, events_from_caliptra, cpu) = {
let mut cpu = Cpu::new(BusLogger::new(root_bus), clock, pic, args);
if let Some(stack_info) = params.stack_info {
cpu.with_stack_info(stack_info);
}
let (events_to_caliptra, events_from_caliptra) = cpu.register_events();
(events_to_caliptra, events_from_caliptra, cpu)
};
let mut hasher = DefaultHasher::new();
std::hash::Hash::hash_slice(params.rom, &mut hasher);
let image_tag = hasher.finish();
let mci_regs = cpu.bus.bus.mci_external_regs();
let mut m = ModelEmulated {
output,
cpu,
soc_to_caliptra_bus,
trace_fn: None,
ready_for_fw,
cpu_enabled,
trace_path: trace_path_or_env(params.trace_path),
fuses: params.fuses,
_rom_image_tag: image_tag,
iccm_image_tag: None,
trng_mode,
events_to_caliptra,
events_from_caliptra,
collected_events_from_caliptra: vec![],
mci: mci_regs,
};
// Turn tracing on if the trace path was set
m.tracing_hint(true);
Ok(m)
}
fn type_name(&self) -> &'static str {
"ModelEmulated"
}
fn trng_mode(&self) -> TrngMode {
self.trng_mode
}
fn ready_for_fw(&self) -> bool {
self.ready_for_fw.get()
}
fn apb_bus(&mut self) -> Self::TBus<'_> {
EmulatedApbBus { model: self }
}
fn step(&mut self) {
if self.cpu_enabled.get() {
self.cpu.step(self.trace_fn.as_deref_mut());
}
// do the bare minimum for the recovery flow: activating the recovery image
const DEVICE_STATUS_PENDING: u32 = 0x4;
const ACTIVATE_RECOVERY_IMAGE_CMD: u32 = 0xF;
if DeviceStatus0ReadVal::from(self.cpu.bus.bus.dma.axi.recovery.device_status_0.reg.get())
.dev_status()
== DEVICE_STATUS_PENDING
{
self.cpu
.bus
.bus
.dma
.axi
.recovery
.recovery_ctrl
.reg
.modify(RecoveryControl::ACTIVATE_RECOVERY_IMAGE.val(ACTIVATE_RECOVERY_IMAGE_CMD));
}
for event in self.events_from_caliptra.try_iter() {
self.collected_events_from_caliptra.push(event.clone());
// brute force respond to AXI DMA MCU SRAM read
if let (Device::MCU, EventData::MemoryRead { start_addr, len }) =
(event.dest, event.event)
{
let addr = start_addr as usize;
let mcu_sram_data = self.cpu.bus.bus.dma.axi.mcu_sram.data_mut();
let Some(dest) = mcu_sram_data.get_mut(addr..addr + len as usize) else {
continue;
};
self.events_to_caliptra
.send(Event {
src: Device::MCU,
dest: Device::CaliptraCore,
event: EventData::MemoryReadResponse {
start_addr,
data: dest.to_vec(),
},
})
.unwrap();
}
}
}
fn output(&mut self) -> &mut Output {
// In case the caller wants to log something, make sure the log has the
// correct time.env::
self.output.sink().set_now(self.cpu.clock.now());
&mut self.output
}
fn cover_fw_image(&mut self, fw_image: &[u8]) {
let iccm_image = &fw_image[IMAGE_MANIFEST_BYTE_SIZE..];
self.iccm_image_tag = Some(hash_slice(iccm_image));
}
fn tracing_hint(&mut self, enable: bool) {
if enable == self.trace_fn.is_some() {
// No change
return;
}
self.trace_fn = None;
self.cpu.bus.log = None;
let Some(trace_path) = &self.trace_path else {
return;
};
let mut log = match LogFile::open(trace_path) {
Ok(file) => file,
Err(e) => {
eprintln!("Unable to open file {trace_path:?}: {e}");
return;
}
};
self.cpu.bus.log = Some(log.clone());
self.trace_fn = Some(Box::new(move |pc, _instr| {
writeln!(log, "pc=0x{pc:x}").unwrap();
}))
}
fn ecc_error_injection(&mut self, mode: ErrorInjectionMode) {
match mode {
ErrorInjectionMode::None => {
self.cpu.bus.bus.iccm.ram().borrow_mut().error_injection = 0;
self.cpu.bus.bus.dccm.error_injection = 0;
}
ErrorInjectionMode::IccmDoubleBitEcc => {
self.cpu.bus.bus.iccm.ram().borrow_mut().error_injection = 2;
}
ErrorInjectionMode::DccmDoubleBitEcc => {
self.cpu.bus.bus.dccm.error_injection = 8;
}
}
}
fn set_axi_user(&mut self, axi_user: u32) {
self.soc_to_caliptra_bus.mailbox = MailboxExternal {
soc_user: MailboxRequester::from(axi_user),
regs: self.soc_to_caliptra_bus.mailbox.regs.clone(),
};
}
fn warm_reset(&mut self) {
self.cpu.warm_reset();
self.step();
}
// [TODO][CAP2] Should it be statically provisioned?
fn put_firmware_in_rri(
&mut self,
firmware: &[u8],
soc_manifest: Option<&[u8]>,
mcu_firmware: Option<&[u8]>,
) -> Result<(), ModelError> {
self.cpu.bus.bus.dma.axi.recovery.cms_data = vec![firmware.to_vec()];
if let Some(soc_manifest) = soc_manifest {
self.cpu
.bus
.bus
.dma
.axi
.recovery
.cms_data
.push(soc_manifest.to_vec());
if let Some(mcu_fw) = mcu_firmware {
self.cpu
.bus
.bus
.dma
.axi
.recovery
.cms_data
.push(mcu_fw.to_vec());
}
}
Ok(())
}
fn events_from_caliptra(&mut self) -> Vec<Event> {
self.collected_events_from_caliptra.drain(..).collect()
}
fn events_to_caliptra(&mut self) -> mpsc::Sender<Event> {
self.events_to_caliptra.clone()
}
fn write_payload_to_ss_staging_area(&mut self, payload: &[u8]) -> Result<u64, ModelError> {
if !self.subsystem_mode() {
return Err(ModelError::SubsystemSramError);
}
let payload_len = payload.len();
self.cpu
.bus
.bus
.dma
.axi
.mcu_sram
.data_mut()
.get_mut(..payload_len)
.ok_or(ModelError::SubsystemSramError)?
.copy_from_slice(payload);
Ok(AxiRootBus::mcu_sram_offset())
}
fn fuses(&self) -> &Fuses {
&self.fuses
}
fn set_fuses(&mut self, fuses: Fuses) {
self.fuses = fuses;
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/keys.rs | hw-model/src/keys.rs | // Licensed under the Apache-2.0 license
#![allow(dead_code)]
use crate::otp_provision::{LifecycleRawTokens, LifecycleToken, ManufDebugUnlockToken};
// This is a random number, but should be kept in sync with what is the default value in the FPGA ROM.
pub const DEFAULT_LIFECYCLE_RAW_TOKEN: LifecycleToken =
LifecycleToken(0x05edb8c608fcc830de181732cfd65e57u128.to_le_bytes());
pub const DEFAULT_LIFECYCLE_RAW_TOKENS: LifecycleRawTokens = LifecycleRawTokens {
test_unlock: [DEFAULT_LIFECYCLE_RAW_TOKEN; 7],
manuf: DEFAULT_LIFECYCLE_RAW_TOKEN,
manuf_to_prod: DEFAULT_LIFECYCLE_RAW_TOKEN,
prod_to_prod_end: DEFAULT_LIFECYCLE_RAW_TOKEN,
rma: DEFAULT_LIFECYCLE_RAW_TOKEN,
};
// Default manuf debug unlock token.
pub const DEFAULT_MANUF_DEBUG_UNLOCK_RAW_TOKEN: ManufDebugUnlockToken = ManufDebugUnlockToken([
0xABCDEFEB, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xF888888A,
]);
// Default prod debug unlock ECDSA P384 public key.
pub const DEFAULT_PROD_DEBUG_UNLOCK_ECDSA_PUBKEY: [u32; 24] = [
0x65cb9862, 0x5d25e072, 0x1d735a9d, 0x24d4cacc, 0x6dff1d49, 0x623a6100, 0x8ab8b280, 0xfab229bc,
0x5dbb5af7, 0x8574f1ba, 0x85aec32b, 0xb7c20086, 0x3706908f, 0x43a3b93b, 0x5bbc5ce4, 0x9490bb87,
0xb6463f94, 0x4bee242a, 0x2d1b0095, 0xcc2bcce7, 0x61515988, 0x2dcfb1b3, 0x1cd97951, 0x2e63d4df,
];
// Default prod debug unlock ML-DSA-87 public key.
pub const DEFAULT_PROD_DEBUG_UNLOCK_MLDSA_PUBKEY: [u32; 648] = [
0x9f6a3445, 0x5550641d, 0x65619e8, 0x5ee1e1f7, 0x4041eea8, 0x3767646f, 0xd6574acd, 0x9a410c23,
0x4338a999, 0x20316d25, 0xf0511bdf, 0xc286dc6d, 0x4e96938, 0xc69dee81, 0x58765525, 0x7de18940,
0x40c19acf, 0xaee142ae, 0x47f985f5, 0xc41e6525, 0xac1ff787, 0x8c593946, 0x6ade2578, 0xb5cfc7d1,
0x6427203f, 0x9b60b8e3, 0xf4467d67, 0x8cb59dbb, 0xe4bfe3b, 0x1508e4ca, 0x37bcd0ce, 0xfb628f52,
0x80815641, 0xfeaf82c0, 0xb1998827, 0x7bab6200, 0x7bfbe9d6, 0x2caa4647, 0x5816b3c8, 0x72ed654,
0x8343c88, 0xf9717f6d, 0x3abfb250, 0x2455a4da, 0xb908cdf, 0x9a984ed1, 0x4fe3fdaa, 0xac7c34d2,
0xe4014483, 0xeb5a2f3e, 0x5eb1db64, 0x977dadea, 0xe73ef63f, 0x77e0eb9c, 0x6fa3b1cd, 0x774fcf5a,
0x848141ee, 0x4b853473, 0x39c4a07b, 0x6a7d1d8c, 0x6dbc9527, 0x2528a424, 0xf319d62f, 0xbd9d285b,
0xa7716624, 0xc0b057ec, 0xb6112565, 0x4bacaf80, 0x5148b64a, 0x56a1e1ea, 0x66315233, 0x274a1cea,
0x9ffddf6a, 0x5d18564d, 0xbacde095, 0xca23b35b, 0xe3105ab5, 0x4c28dd5d, 0xf97c3a34, 0xe5c2f1cd,
0x583622c2, 0xe064739c, 0xe2e0d5f9, 0x6298a263, 0xecabf70f, 0xbe0680f0, 0x545db4aa, 0x5fdee21f,
0x80a78f31, 0xa4c9dc3b, 0x252f9f8a, 0x1d19806d, 0x22548d9f, 0x81379485, 0x5f7a64ab, 0x560a0903,
0xf0d733d1, 0xa5cc7080, 0x6fc7b470, 0xf0178520, 0x2811a96b, 0x16991d48, 0xf0924114, 0x73c03210,
0x3c4ac5fd, 0x7f69549d, 0xe502ea66, 0x2bbc0ccf, 0xc07617ab, 0xc3daa303, 0x79c7cfd6, 0x6d91f95e,
0x922c69, 0xcd6e8d87, 0x6c66981b, 0x2078a92b, 0xac9d1c00, 0x3699c513, 0xc59705b5, 0x951f8601,
0x8c8e5770, 0x7815570d, 0xef192b7b, 0x16670fa, 0xb60d4028, 0x9dc945a9, 0x8010c7ab, 0x51ebb957,
0x40e8de78, 0x4481590c, 0xf5c92c6e, 0x85c08624, 0xbf895e73, 0xac19dd93, 0xb4e9bd5e, 0x49d3cfc2,
0xb1a0dc36, 0xd72c467d, 0xb5756eeb, 0x93728f1, 0xf060c60b, 0x470eb5bb, 0x2215662b, 0xbb464e13,
0x46ef6b57, 0x2ad27a34, 0x9d28bd00, 0xe0df8dc0, 0x89306dff, 0x287ec55a, 0xade63de3, 0x536979,
0xdf0c3a34, 0xcb544c75, 0x42919de8, 0xcd565b50, 0x36b46785, 0xe171845b, 0x3a48f009, 0x1a3271d7,
0x9f09f1a3, 0x61c16986, 0x68394dbe, 0x843cf032, 0xa13e77c8, 0xc8dcadf, 0x399e6db2, 0x268d1d92,
0xbd7ef6ae, 0x2d2a153d, 0x94395d8c, 0x681a7379, 0x91931bdd, 0x40faeb5b, 0xcb699be0, 0x7d6ffd00,
0xf541e94e, 0xcbcfcd4f, 0x99ebddd5, 0xa6285d71, 0x50a35fd5, 0xee37e2e4, 0x4f478cce, 0xf73ea1f8,
0x2fd32610, 0xbbeba71a, 0xca9c02dc, 0xd397d5ea, 0x2f7b1dd6, 0x71e939bb, 0x76395356, 0x4121f1a5,
0xe990cc94, 0xd56f9aea, 0x263c06bb, 0xb021ef38, 0x4df7bba1, 0xa3ecb3b, 0x67a65d94, 0x7e99cf4a,
0xeb2f944d, 0xe92b1d22, 0xe550696b, 0x1649ffd, 0x45d27bb4, 0xc0dd4b87, 0x17dd5d0a, 0x4a6e22b2,
0x984fc0b4, 0x21e3df84, 0xcdd78042, 0x3adba0b7, 0xc2dfb102, 0xb1ab3737, 0xfd3ba79, 0x1c721e78,
0x8ae9b59b, 0xbd1dc072, 0x56af3d05, 0x5fec2e14, 0x3abeb764, 0x49e138e3, 0x436e794b, 0x2e3db32a,
0xebe3b2db, 0x10c66337, 0x1a4eb109, 0xdb0d04e6, 0xe62c1918, 0x67c635f4, 0x83f98974, 0x6e6bed21,
0x1a0b9f0, 0x218d3380, 0x85c1d48e, 0x13b0bb42, 0x7576c33, 0x1e96838b, 0x4f35a791, 0x1eeb8459,
0x882d59e5, 0xfa5b8961, 0x2b9447a8, 0x1755c6d7, 0xc5f8bf13, 0x503d782a, 0xc3d03bbc, 0xa83fb07b,
0xf104794c, 0x11531dfe, 0x971b1a8d, 0x290c902, 0x98813c1d, 0x8c4b3e91, 0x4bc37027, 0x6b72b08,
0x73059598, 0x31709576, 0x267d7aa8, 0x278e0928, 0x496aee77, 0xa9bf1ca4, 0x40018cb4, 0xaa803e60,
0xe37e2de8, 0xaba8393c, 0x6b31c03c, 0x5979dc58, 0x59b58f96, 0x88d5fca0, 0x71eab363, 0xa1e737ec,
0xc7c11cb6, 0xf3e0bbc1, 0xf5ba8c22, 0x5740e5ca, 0xdf7bc1d, 0xcec8e66b, 0x3be44d4b, 0x5986ece3,
0x28407c25, 0x872bb5b5, 0x2ebd78a4, 0xa118c5b4, 0xf0518ee0, 0xe5754a6, 0x3082448b, 0x1d6f8b6d,
0x8b431cf1, 0xc59562b2, 0x17524c07, 0x1be9c20a, 0x49163950, 0xc4ee5329, 0xb8250779, 0x3b921e76,
0x9e37e449, 0xeb0000d0, 0xaf823288, 0x1a03186d, 0x949d885d, 0x7f0abf6c, 0xe55e7a6, 0xf594c424,
0x44b5b562, 0x27a91185, 0x46daa248, 0x1201d52, 0x23544eab, 0x3a29b3e1, 0xcdcf3dda, 0x4782d8d2,
0x10e87fd0, 0x3e400fa3, 0x8adb0048, 0x88ac4fc6, 0x89fd0491, 0x3a493d4, 0xe5358bd9, 0xea7abcd8,
0x9221cc52, 0xdf7cd6e0, 0xdc95fd50, 0xade0f09d, 0xe99035ba, 0x7a206c91, 0x1226500e, 0x8ab32475,
0xe46461e9, 0xf364b992, 0xd3cea9e7, 0x6df895d4, 0xd316ca05, 0x638900f5, 0x48369daf, 0xfb5fd6f2,
0x4f7025ec, 0xc8c7fa08, 0x84b2b8c0, 0x1c3f4193, 0x48db3f64, 0xf3c3f4cd, 0x8731c8ae, 0xbc2af341,
0xc803180e, 0x1356c3f8, 0xa3c9f7e1, 0x7535a572, 0x8a7bb388, 0x36d16f52, 0x7b911e76, 0x949d887f,
0x97ca3e8e, 0xdc719f87, 0x2c332042, 0x6b18e9da, 0xb2c2f359, 0xc9ee01e4, 0x5cf8d67a, 0x917d1123,
0xdabdd911, 0xe87359a5, 0xc76db41a, 0x266f8c61, 0x42709087, 0x3abe25e1, 0x2fbc272d, 0x8f49ab47,
0xbdf49f3a, 0x15a62fd9, 0xeb2045e8, 0x71e166a4, 0xee461e06, 0x12d0e793, 0xef0bd259, 0xf42ac48d,
0xcc557ac5, 0xb1c42836, 0xd9a5077c, 0x73ca49e1, 0x4ab5247a, 0xb704a6c3, 0x29284d14, 0x34ca626b,
0x4ff2161b, 0xecdefb4a, 0x2c800d11, 0x16235691, 0x773776f0, 0x87d50f96, 0x52aa2742, 0x70d07b10,
0x24b235f3, 0x6e6d5348, 0x33ab6d9e, 0x906c9bbb, 0x7945be9, 0x3c766a1a, 0x7381a6b3, 0x3cb7c147,
0x1f601d5e, 0xc90c23c, 0xf365b1bd, 0xcd43af48, 0x3943ffc3, 0xef7e97e8, 0xb6035031, 0x2066716,
0x69c52b6b, 0xcef77cf8, 0x47024fc1, 0xa4d015bb, 0x797a72dd, 0xbbba92ed, 0x6e130ddc, 0xc6435c65,
0x6d08687, 0xc01a116d, 0xb7d16d45, 0xda674018, 0x337a0ae1, 0x8a306805, 0x748f69dc, 0xbb204fcc,
0x7263eff9, 0x2cf2a34b, 0x7b8a850d, 0xec72dc92, 0x2f770daa, 0x37428459, 0xe47c61fb, 0x5b96bc09,
0xcba9934b, 0xf2e209cf, 0xe63d50c8, 0xf17757b3, 0xea371b95, 0xf4cf6126, 0x8488e995, 0x7359eb29,
0xf52b57bf, 0xe92cab84, 0x9188ca78, 0xca12a7b4, 0xfae556ec, 0x1750dbc1, 0x1d7fe6ac, 0x27656e58,
0x69a7e639, 0x3a1e295a, 0x9bbb01e5, 0xb8a66e0b, 0xb7bfed90, 0xeba4170c, 0x8ad49d37, 0x40c61098,
0x14b007eb, 0x8f364010, 0xb0b76063, 0x603b85, 0x713b09c0, 0x8c1f4cf2, 0xec4cec22, 0x432202fb,
0x9649a2dd, 0x8b97cd17, 0xe4e3d611, 0x9b3b9a67, 0x99f5d0b6, 0x87d2b762, 0x70381aa0, 0x1489a6c1,
0x9f4cb2aa, 0x98bce9e4, 0x8b84b72c, 0xf83dd2bd, 0xf1d78eec, 0xab3e0e0a, 0x62cf93ca, 0x23d10399,
0x9a77fe19, 0xb9270930, 0xf79fa140, 0xf824a063, 0x89dc697a, 0xf6046e4b, 0xd99207a7, 0x7f026eae,
0x3726f0cd, 0xb3d6507e, 0xa60bc852, 0xd703a542, 0x6a738413, 0xaf885c71, 0x721bd12, 0x7081e508,
0x71fbab87, 0xb3cdd5be, 0x1c7d9560, 0xac0e018a, 0xda82d7b, 0xe26ec271, 0x77fb6c9d, 0x736e5d76,
0x8a425b48, 0x5ecc107d, 0xe49b2d49, 0x4dd8eada, 0x6f46c4f5, 0x5e75a552, 0xd8c8e5ee, 0xcaa32388,
0xe6a99e97, 0x9efbaa4d, 0xd64a3cfd, 0x52aa4aa7, 0x1a9b88fc, 0xcd305b55, 0x19e8bf8e, 0xb51771c5,
0xa55a80fb, 0xb95d55a5, 0xcfe0e5d8, 0x480720cb, 0x1558b3fb, 0x6a2b26e0, 0x937f6ab8, 0x89483860,
0x37f4693b, 0x2227ce9f, 0x4699a6f0, 0x3fa507de, 0xfc401e06, 0x210da27f, 0x64f486b6, 0x4ec8ae2c,
0xa3f8ce6, 0xe61e2a8a, 0xec102b0c, 0xeb813f6e, 0x29095561, 0x85c2fecc, 0xf042f177, 0xe9c1a7e7,
0x26c7aff8, 0x3f6b5c9b, 0x1d2bc6e2, 0x882984fd, 0x47878c71, 0x27344d4, 0x72447be1, 0x53a22cc,
0x9665de3b, 0x366c578f, 0x412d6900, 0x172b98eb, 0xaef6135a, 0x424c616c, 0x69ca0758, 0x3f8ac2fb,
0x68fe8f58, 0x2f7bbd12, 0x7b8f93af, 0x56106a7d, 0x526db843, 0x131815eb, 0x95890402, 0x17767883,
0x83b87109, 0xe8140cd0, 0xf6052d11, 0xfb5937af, 0x60c71521, 0xd7a47ebf, 0x265933d5, 0xa740f703,
0x96c1f0fc, 0xa6d69a2f, 0xb9b7a5d6, 0xdea8cb75, 0xb8beff0, 0x579888fb, 0xc90db894, 0x50ccabfd,
0xb3ba7ad6, 0xf191640b, 0x7d61639c, 0x82640430, 0x55205d56, 0x8dbdeb96, 0xe667445e, 0x8196e7,
0x1f5df9bc, 0xbf60baeb, 0x71cef7aa, 0x7f6740cc, 0x2ad7026e, 0xd7f71e39, 0x442c7be, 0xb2c19c80,
0x16b5defb, 0xd7ac8f2d, 0x6b48e179, 0x8a01965f, 0x3b6f2043, 0xa3fb81c7, 0xe4572ff9, 0x286a8993,
0x30c3cdeb, 0xfe8b18ab, 0x4aeb9379, 0xfb2cd32e, 0xb07c37d9, 0x3259823e, 0xe0879102, 0x16a0d615,
0xe2dae1e7, 0x9a2b9b23, 0x585523db, 0x141b3f8b, 0x612a8857, 0xf7bdfe2e, 0x7e2d0263, 0xac15ca1b,
0x1380ccf1, 0x994b64cb, 0x5606990a, 0xc7653ced, 0x64a5e728, 0xe1a33015, 0x9c5f88cd, 0x9b6f7957,
0x6e63ed21, 0x8b792ddb, 0x9a675647, 0xd548dd56, 0x8e88675f, 0x9b51749a, 0x9843a006, 0xd6cc5bc3,
0xc4530aa4, 0x4b3b273b, 0xf4157b0b, 0x348b1414, 0x5a7bf1a0, 0x39cea033, 0x30cd2ac8, 0xc6970370,
];
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/mmio.rs | hw-model/src/mmio.rs | // Licensed under the Apache-2.0 license
use std::cell::Cell;
use crate::rv32_builder::Rv32Builder;
unsafe fn transmute_to_u32<T>(src: &T) -> u32 {
match std::mem::size_of::<T>() {
1 => std::mem::transmute_copy::<T, u8>(src).into(),
2 => std::mem::transmute_copy::<T, u16>(src).into(),
4 => std::mem::transmute_copy::<T, u32>(src),
_ => panic!("Unsupported write size"),
}
}
/// An MMIO interface that generates RV32IMC store instructions.
#[derive(Default)]
pub struct Rv32GenMmio {
builder: Cell<Rv32Builder>,
}
impl Rv32GenMmio {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> Vec<u8> {
self.into_inner().build()
}
pub fn into_inner(self) -> Rv32Builder {
self.builder.into_inner()
}
}
impl ureg::Mmio for Rv32GenMmio {
unsafe fn read_volatile<T: Clone + Copy + Sized>(&self, _src: *const T) -> T {
panic!("Rv32GenMmio: Reads not supported; write-only");
}
}
impl ureg::MmioMut for Rv32GenMmio {
/// Adds machine code that stores the 32-bit value `src` to destination
/// address `dst`.
///
/// # Safety
///
/// As the pointer isn't written to, this Mmio implementation isn't actually
/// unsafe for POD types like u8/u16/u32.
unsafe fn write_volatile<T: Clone + Copy>(&self, dst: *mut T, src: T) {
self.builder.set(
self.builder
.take()
.store(dst as u32, transmute_to_u32(&src)),
);
}
}
#[cfg(test)]
mod tests {
use ureg::MmioMut;
use super::*;
#[test]
fn test_rv32gen_mmio() {
let mmio = Rv32GenMmio::new();
unsafe {
mmio.write_volatile(4 as *mut u32, 0x3abc_9321);
mmio.write_volatile(8 as *mut u32, 0xd00f_b00d);
}
assert_eq!(
&mmio.build(),
&[
0xb7, 0x02, 0x00, 0x00, 0x37, 0x93, 0xbc, 0x3a, 0x13, 0x03, 0x13, 0x32, 0x23, 0xa2,
0x62, 0x00, 0xb7, 0x02, 0x00, 0x00, 0x37, 0xb3, 0x0f, 0xd0, 0x13, 0x03, 0xd3, 0x00,
0x23, 0xa4, 0x62, 0x00, 0x13, 0x00, 0x00, 0x00,
]
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/lcc.rs | hw-model/src/lcc.rs | // Licensed under the Apache-2.0 license
use bitflags::bitflags;
use crate::jtag::JtagAccessibleReg;
#[derive(Clone, Copy, Debug)]
#[repr(u32)]
pub enum LcCtrlReg {
AlertTest = 0x0,
Status = 0x4,
ClaimTransitionIfRegwen = 0x8,
ClaimTransitionIf = 0xC,
TransitionRegwen = 0x10,
TransitionCmd = 0x14,
TransitionCtrl = 0x18,
TransitionToken0 = 0x1C,
TransitionToken1 = 0x20,
TransitionToken2 = 0x24,
TransitionToken3 = 0x28,
TransitionTarget = 0x2C,
OtpVendorTestCtrl = 0x30,
OtpVendorTestStatus = 0x34,
LcState = 0x38,
LcTransitionCnt = 0x3C,
LcIdState = 0x40,
HwRevision0 = 0x44,
HwRevision1 = 0x48,
DeviceId0 = 0x4C,
DeviceId1 = 0x50,
DeviceId2 = 0x54,
DeviceId3 = 0x58,
DeviceId4 = 0x5C,
DeviceId5 = 0x60,
DeviceId6 = 0x64,
DeviceId7 = 0x68,
ManufState0 = 0x6C,
ManufState1 = 0x70,
ManufState2 = 0x74,
ManufState3 = 0x78,
ManufState4 = 0x7C,
ManufState5 = 0x80,
ManufState6 = 0x84,
ManufState7 = 0x88,
}
impl JtagAccessibleReg for LcCtrlReg {
fn byte_offset(&self) -> u32 {
*self as u32
}
}
bitflags! {
/// Bits of the lc_ctrl.STATUS register, aka [LcCtrlReg::Status].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LcCtrlStatus: u32 {
const INITIALIZED = 0b1 << 0;
const READY = 0b1 << 1;
const EXT_CLOCK_SWITCHED = 0b1 << 2;
const TRANSITION_SUCCESSFUL = 0b1 << 3;
const TRANSITION_COUNT_ERROR = 0b1 << 4;
const TRANSITION_ERROR = 0b1 << 5;
const TOKEN_ERROR = 0b1 << 6;
const FLASH_RMA_ERROR = 0b1 << 7;
const OTP_ERROR = 0b1 << 8;
const STATE_ERROR = 0b1 << 9;
const BUS_INTEG_ERROR = 0b1 << 10;
const OTP_PARTITION_ERROR = 0b1 << 11;
const ERRORS =
Self::TRANSITION_COUNT_ERROR.bits() |
Self::TRANSITION_ERROR.bits() |
Self::TOKEN_ERROR.bits() |
Self::FLASH_RMA_ERROR.bits() |
Self::OTP_ERROR.bits() |
Self::STATE_ERROR.bits() |
Self::BUS_INTEG_ERROR.bits() |
Self::OTP_PARTITION_ERROR.bits();
}
}
bitflags! {
/// Bits of the lc_ctrl.TRANSITION_CMD register, aka [LcCtrlReg::TransitionCmd].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LcCtrlTransitionCmd: u32 {
const START = 0b1;
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/bin/fpga_realtime_mbox_pauser.rs | hw-model/src/bin/fpga_realtime_mbox_pauser.rs | // Licensed under the Apache-2.0 license
use caliptra_hw_model::{mmio::Rv32GenMmio, HwModel, InitParams};
use nix::sys::signal;
use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet};
use std::process::exit;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use caliptra_api::soc_mgr::SocManager;
use caliptra_registers::soc_ifc;
fn gen_image_hi() -> Vec<u8> {
let rv32_gen = Rv32GenMmio::new();
let soc_ifc =
unsafe { soc_ifc::RegisterBlock::new_with_mmio(0x3003_0000 as *mut u32, &rv32_gen) };
soc_ifc
.cptra_generic_output_wires()
.at(0)
.write(|_| b'h'.into());
soc_ifc
.cptra_generic_output_wires()
.at(0)
.write(|_| b'i'.into());
soc_ifc
.cptra_generic_output_wires()
.at(0)
.write(|_| 0x100 | u32::from(b'i'));
soc_ifc.cptra_generic_output_wires().at(0).write(|_| 0xff);
rv32_gen.into_inner().empty_loop().build()
}
// Atomic flag to indicate if SIGBUS was received
static SIGBUS_RECEIVED: AtomicBool = AtomicBool::new(false);
// Signal handler function
extern "C" fn handle_sigbus(_: i32) {
SIGBUS_RECEIVED.store(true, Ordering::SeqCst);
}
fn main() {
println!("Setup signal handler...");
// Define the signal action
let sig_action = SigAction::new(
SigHandler::Handler(handle_sigbus),
SaFlags::empty(),
SigSet::empty(),
);
// Set the signal handler for SIGBUS
unsafe {
signal::sigaction(signal::Signal::SIGBUS, &sig_action)
.expect("Failed to set SIGBUS handler");
}
// Spawn a thread that causes a SIGBUS error
thread::spawn(|| {
// Sleep for a short duration to ensure the main thread is ready
thread::sleep(Duration::from_secs(2));
let mut model = caliptra_hw_model::new_unbooted(InitParams {
rom: &gen_image_hi(),
..Default::default()
})
.unwrap();
model.soc_ifc().cptra_fuse_wr_done().write(|w| w.done(true));
model.soc_ifc().cptra_bootfsm_go().write(|w| w.go(true));
// Set up the PAUSER as valid for the mailbox (using index 0)
model
.soc_ifc()
.cptra_mbox_valid_axi_user()
.at(0)
.write(|_| 0x1);
model
.soc_ifc()
.cptra_mbox_axi_user_lock()
.at(0)
.write(|w| w.lock(true));
// Set the PAUSER to something invalid
model.set_axi_user(0x2);
// The accesses below trigger sigbus
assert!(!model.soc_mbox().lock().read().lock());
// Should continue to read 0 because the reads are being blocked by valid PAUSER
assert!(!model.soc_mbox().lock().read().lock());
// Set the PAUSER back to valid
model.set_axi_user(0x1);
// Should read 0 the first time still for lock available
assert!(!model.soc_mbox().lock().read().lock());
// Should read 1 now for lock taken
assert!(model.soc_mbox().lock().read().lock());
model.soc_mbox().cmd().write(|_| 4242);
assert_eq!(model.soc_mbox().cmd().read(), 4242);
// Continue with the rest of your program
println!("Continuing execution...");
});
// Simulate some work in the main thread
loop {
if SIGBUS_RECEIVED.load(Ordering::SeqCst) {
println!("Received SIGBUS signal!");
// Handle the SIGBUS signal here
exit(42);
}
println!("Working...");
thread::sleep(Duration::from_secs(1));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/openocd/openocd_jtag_tap.rs | hw-model/src/openocd/openocd_jtag_tap.rs | // Licensed under the Apache-2.0 license
//
// Derived from OpenTitan's opentitanlib with original copyright:
//
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#![allow(dead_code)]
use std::path::PathBuf;
use anyhow::{bail, ensure, Context, Result};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::jtag::JtagAccessibleReg;
use crate::openocd::openocd_server::{OpenOcdError, OpenOcdServer};
/// Available JTAG TAPs in Calitpra Subsystem.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)]
pub enum JtagTap {
/// RISC-V Veer core's TAP for Caliptra Core.
CaliptraCoreTap,
/// RISC-V Veer core's TAP for Caliptra MCU.
CaliptraMcuTap,
/// Lifecycle Controller's TAP.
LccTap,
/// No TAP selected.
NoTap,
}
/// JTAG parameters to pass to OpenOCD server on startup.
#[derive(Debug, Clone)]
pub struct JtagParams {
/// OpenOCD binary path.
pub openocd: PathBuf,
/// JTAG adapter speed in kHz.
pub adapter_speed_khz: u64,
/// Whether or not to log OpenOCD server messages to stdio.
pub log_stdio: bool,
}
/// Errors related to the JTAG interface.
#[derive(Error, Debug, Deserialize, Serialize)]
pub enum JtagError {
#[error("Operation not valid on selected JTAG TAP: {0:?}")]
Tap(JtagTap),
#[error("JTAG timeout")]
Timeout,
#[error("JTAG busy")]
Busy,
#[error("Generic error {0}")]
Generic(String),
}
/// A JTAG TAP accessible through an OpenOCD server.
pub struct OpenOcdJtagTap {
/// OpenOCD server instance.
openocd: OpenOcdServer,
/// JTAG TAP OpenOCD server is connected to.
jtag_tap: JtagTap,
}
impl OpenOcdJtagTap {
/// Starts an OpenOCD server and connects to a specified JTAG TAP.
pub fn new(params: &JtagParams, tap: JtagTap) -> Result<Box<OpenOcdJtagTap>> {
let target_tap = match tap {
JtagTap::CaliptraCoreTap => "core",
JtagTap::CaliptraMcuTap => "mcu",
JtagTap::LccTap => "lcc",
// "none" will cause the OpenOCD startup stript to fail.
JtagTap::NoTap => "none",
};
let adapter_cfg = &format!(
"{} configure_adapter {}",
include_str!(env!("OPENOCD_SYSFSGPIO_ADAPTER_CFG")),
target_tap,
);
let tap_cfg = &format!(
"{} configure_tap {}",
include_str!(env!("OPENOCD_TAP_CFG")),
target_tap,
);
// Spawn the OpenOCD server, configure the adapter, and connect to the TAP.
let mut openocd = OpenOcdServer::spawn(¶ms.openocd, params.log_stdio)?;
openocd.execute(adapter_cfg)?;
openocd.execute(&format!("adapter speed {}", params.adapter_speed_khz))?;
openocd.execute("transport select jtag")?;
openocd.execute(tap_cfg)?;
// Capture outputs during initialization to see if error has occurred during the process.
let resp = openocd.execute("capture init")?;
if resp.contains("JTAG scan chain interrogation failed") {
bail!(OpenOcdError::InitializeFailure(resp));
}
Ok(Box::new(OpenOcdJtagTap {
openocd,
jtag_tap: tap,
}))
}
/// Stop the OpenOCD server, disconnecting from the TAP in the process.
pub fn disconnect(&mut self) -> Result<()> {
self.openocd.shutdown()
}
/// Return the TAP we are currently connected to.
pub fn tap(&self) -> JtagTap {
self.jtag_tap
}
pub fn read_reg(&mut self, reg: &dyn JtagAccessibleReg) -> Result<u32> {
ensure!(
self.jtag_tap != JtagTap::NoTap,
JtagError::Tap(self.jtag_tap)
);
let reg_offset = reg.word_offset();
let cmd = format!("riscv dmi_read 0x{reg_offset:x}");
let response = self.openocd.execute(cmd.as_str())?;
let response_hexstr = response.trim();
let value = u32::from_str_radix(
response_hexstr
.strip_prefix("0x")
.unwrap_or(response_hexstr),
16,
)
.context(format!(
"expected response to be hexadecimal word, got '{response}'"
))?;
Ok(value)
}
pub fn write_reg(&mut self, reg: &dyn JtagAccessibleReg, value: u32) -> Result<()> {
ensure!(
self.jtag_tap != JtagTap::NoTap,
JtagError::Tap(self.jtag_tap)
);
let reg_offset = reg.word_offset();
let cmd = format!("riscv dmi_write 0x{reg_offset:x} 0x{value:x}");
let response = self.openocd.execute(cmd.as_str())?;
if !response.is_empty() {
bail!("unexpected response: '{response}'");
}
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/openocd/printer.rs | hw-model/src/openocd/printer.rs | // Licensed under the Apache-2.0 license
//
// Derived from OpenTitan's opentitanlib with original copyright:
//
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use std::io::Read;
use std::sync::{Arc, Mutex};
use anyhow::Result;
// Accumulates output from a process's `stdout` or `stderr` and redirects to the
// parent process' `stdout`.
pub fn accumulate(stdout: impl Read, source: &str, accumulator: Arc<Mutex<String>>) {
if let Err(e) = worker(stdout, source, accumulator) {
eprintln!("accumulate error: {:?}", e);
}
}
fn worker(mut stdout: impl Read, source: &str, accumulator: Arc<Mutex<String>>) -> Result<()> {
let mut s = String::default();
loop {
read(&mut stdout, &mut s)?;
let mut lines = s.split('\n').collect::<Vec<&str>>();
let next = if !s.ends_with('\n') {
// If we didn't read a complete line at the end, save it for the
// next read.
lines.pop()
} else {
None
};
for line in lines {
println!("{}: {}", source, line.trim_end_matches('\r'));
}
accumulator.lock().unwrap().push_str(&s);
s = next.unwrap_or("").to_string();
}
}
fn read(stdout: &mut impl Read, s: &mut String) -> Result<()> {
let mut buf = [0u8; 256];
let n = stdout.read(&mut buf)?;
s.push_str(&String::from_utf8_lossy(&buf[..n]));
Ok(())
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/openocd/mod.rs | hw-model/src/openocd/mod.rs | // Licensed under the Apache-2.0 license
pub mod openocd_jtag_tap;
pub mod openocd_server;
pub mod printer;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/openocd/openocd_server.rs | hw-model/src/openocd/openocd_server.rs | // Licensed under the Apache-2.0 license
//
// Derived from OpenTitan's opentitanlib with original copyright:
//
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use anyhow::{bail, Context, Result};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::openocd::printer;
/// Errors related to the OpenOCD server.
#[derive(Error, Debug, Deserialize, Serialize)]
pub enum OpenOcdError {
#[error("OpenOCD initialization failed: {0}")]
InitializeFailure(String),
#[error("OpenOCD server exited prematurely")]
PrematureExit,
#[error("Generic error {0}")]
Generic(String),
}
/// Represents an OpenOCD server that we can interact with.
pub struct OpenOcdServer {
/// OpenOCD child process.
server_process: Child,
/// Receiving side of the stream to the telnet interface of OpenOCD.
reader: BufReader<TcpStream>,
/// Sending side of the stream to the telnet interface of OpenOCD.
writer: TcpStream,
}
impl Drop for OpenOcdServer {
fn drop(&mut self) {
let _ = self.shutdown();
}
}
impl OpenOcdServer {
/// Duration to wait for OpenOCD to be ready to accept a Tcl connection.
const OPENOCD_TCL_READY_TMO: Duration = Duration::from_secs(5);
/// Wait until we see a particular message over STDERR.
fn wait_until_regex_match<'a>(
stderr: &mut impl BufRead,
regex: &Regex,
timeout: Duration,
s: &'a mut String,
) -> Result<regex::Captures<'a>> {
let start = Instant::now();
loop {
// NOTE this read could block indefinitely, but this behavior is desired for test simplicity.
let n = stderr.read_line(s)?;
if n == 0 {
bail!("OpenOCD stopped before being ready?");
}
print!("OpenOCD::stderr: {}", s);
if regex.is_match(s) {
// This is not a `if let Some(capture) = regex.captures(s) {}` to to Rust
// borrow checker limitations. Can be modified if Polonius lands.
return Ok(regex.captures(s).unwrap());
}
s.clear();
if start.elapsed() >= timeout {
bail!("OpenOCD did not become ready to accept a Tcl connection");
}
}
}
/// Spawn an OpenOCD Tcl server with the given OpenOCD binary path.
pub fn spawn(path: &Path, log_stdio: bool) -> Result<Self> {
// Let OpenOCD choose which port to bind to, in order to never unnecesarily run into
// issues due to a particular port already being in use.
// We don't use the telnet and GDB ports so disable them.
// The configuration will happen through the Tcl interface, so use `noinit` to prevent
// OpenOCD from transition to execution mode.
let mut cmd = Command::new(path);
cmd.arg("-c")
.arg("tcl_port 0; telnet_port disabled; gdb_port disabled; noinit;");
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// SAFETY: prctl is a syscall which is atomic and thus async-signal-safe.
unsafe {
cmd.pre_exec(|| {
// Since we use OpenOCD as a library, make sure it's killed when
// the parent process dies. This setting is preserved across execve.
rustix::process::set_parent_process_death_signal(Some(
rustix::process::Signal::HUP,
))?;
Ok(())
});
}
if log_stdio {
println!("Spawning OpenOCD with: {cmd:?}");
}
let mut child = cmd
.spawn()
.with_context(|| format!("failed to spawn openocd: {cmd:?}",))?;
let stdout = child.stdout.take().unwrap();
let mut stderr = BufReader::new(child.stderr.take().unwrap());
// Wait until we see 'Info : Listening on port XYZ for Tcl connections' before knowing
// which port to connect to.
if log_stdio {
println!("Waiting for OpenOCD to be ready to accept a Tcl connection ...");
}
static READY_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new("Listening on port ([0-9]+) for tcl connections").unwrap());
let mut buf = String::new();
let regex_captures = Self::wait_until_regex_match(
&mut stderr,
&READY_REGEX,
Self::OPENOCD_TCL_READY_TMO,
&mut buf,
)
.context("OpenOCD was not ready in time to accept a connection")?;
let openocd_port: u16 = regex_captures.get(1).unwrap().as_str().parse()?;
// Print stdout and stderr with log
if log_stdio {
std::thread::spawn(move || {
printer::accumulate(stdout, "OpenOCD::stdout", Default::default())
});
std::thread::spawn(move || {
printer::accumulate(stderr, "OpenOCD::stderr", Default::default())
});
}
let kill_guard = scopeguard::guard(child, |mut child| {
let _ = child.kill();
});
if log_stdio {
println!("Connecting to OpenOCD Tcl interface ...");
}
let stream = TcpStream::connect(("localhost", openocd_port))
.context("failed to connect to OpenOCD socket")?;
let connection = Self {
server_process: scopeguard::ScopeGuard::into_inner(kill_guard),
reader: BufReader::new(stream.try_clone()?),
writer: stream,
};
Ok(connection)
}
/// Send a string to the OpenOCD Tcl server.
fn send(&mut self, cmd: &str) -> Result<()> {
// The protocol is to send the command followed by a `0x1a` byte,
// see https://openocd.org/doc/html/Tcl-Scripting-API.html#Tcl-RPC-server
// Sanity check to ensure that the command string is not malformed.
if cmd.contains('\x1A') {
bail!("Tcl command string should be contained inside the string to send.");
}
self.writer
.write_all(cmd.as_bytes())
.context("failed to send a command to the OpenOCD server")?;
self.writer
.write_all(&[0x1a])
.context("failed to send the command terminator to OpenOCD server")?;
self.writer.flush().context("failed to flush stream")?;
Ok(())
}
/// Receive a string from the OpenOCD Tcl server.
fn recv(&mut self) -> Result<String> {
let mut buf = Vec::new();
self.reader.read_until(0x1A, &mut buf)?;
if !buf.ends_with(b"\x1A") {
bail!(OpenOcdError::PrematureExit);
}
buf.pop();
String::from_utf8(buf).context("failed to parse OpenOCD response as UTF-8")
}
/// Execute a Tcl command via the OpenOCD and wait for its response.
pub fn execute(&mut self, cmd: &str) -> Result<String> {
self.send(cmd)?;
self.recv()
}
pub fn shutdown(&mut self) -> Result<()> {
self.execute("shutdown")?;
self.server_process
.wait()
.context("failed to wait for OpenOCD server to exit")?;
Ok(())
}
}
#[cfg(feature = "fpga_subsystem")]
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_openocd_server() {
let Ok(mut openocd) = OpenOcdServer::spawn(Path::new("openocd"), /*log_stdio=*/ true)
else {
panic!("Failed to spawn an openocd subprocess.");
};
let Ok(version) = openocd.execute("version") else {
panic!("Failed to execute an openocd command.");
};
println!("OpenOCD version: {version}");
assert!(openocd.shutdown().is_ok());
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/xi3c/controller.rs | hw-model/src/xi3c/controller.rs | // Licensed under the Apache-2.0 license
// This code was originally translated from the Xilinx I3C C driver:
// https://github.com/Xilinx/embeddedsw/tree/master/XilinxProcessorIPLib/drivers/i3c/src
// Which is:
// Copyright (C) 2024 Advanced Micro Devices, Inc. All Rights Reserved
// SPDX-License-Identifier: MIT
#![allow(dead_code)]
use crate::xi3c::XI3cError;
use std::{
cell::{Cell, RefCell},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant},
};
use tock_registers::interfaces::{Readable, Writeable};
use tock_registers::register_structs;
use tock_registers::registers::{ReadOnly, ReadWrite};
pub const MAX_TIMEOUT_US: u32 = 2_000_000;
pub const XI3C_BROADCAST_ADDRESS: u8 = 0x7e;
pub(crate) const XI3C_CCC_BRDCAST_ENEC: u8 = 0x0;
pub(crate) const XI3C_CCC_BRDCAST_DISEC: u8 = 0x1;
pub(crate) const XI3C_CCC_BRDCAST_RSTDAA: u8 = 0x6;
pub(crate) const XI3C_CCC_BRDCAST_ENTDAA: u8 = 0x7;
pub(crate) const XI3C_CCC_SETDASA: u8 = 0x87;
pub const XI3C_CMD_TYPE_I3C: u8 = 1;
/// BIT 4 - Resp Fifo not empty
pub(crate) const XI3C_SR_RESP_NOT_EMPTY_MASK: u32 = 0x10;
/// BIT 15 - Read FIFO empty
pub(crate) const XI3C_SR_RD_FIFO_NOT_EMPTY_MASK: u32 = 0x8000;
/// BIT 5 - Write Fifo Full
pub(crate) const XI3C_INTR_WR_FIFO_ALMOST_FULL_MASK: u32 = 0x20;
/// BIT 6 - Read Fifo Full
pub(crate) const XI3C_INTR_RD_FULL_MASK: u32 = 0x40;
/// BIT 7 - IBI
pub(crate) const XI3C_INTR_IBI_MASK: u32 = 0x80;
/// BIT 8 - Hot join
pub(crate) const XI3C_INTR_HJ_MASK: u32 = 0x100;
/// BIT 0 - Core Enable
pub(crate) const XI3C_CR_EN_MASK: u32 = 0x1;
/// BIT 2 - Resume Operation
pub(crate) const XI3C_CR_RESUME_MASK: u32 = 0x4;
/// BIT 3 - IBI Enable
pub(crate) const XI3C_CR_IBI_MASK: u32 = 0x8;
/// BIT 4 - Hot Join Enable
pub(crate) const XI3C_CR_HJ_MASK: u32 = 0x10;
/// BIT 0 - Reset
pub(crate) const XI3C_SOFT_RESET_MASK: u32 = 0x1;
/// BIT 1 to 4 - All fifos reset
pub(crate) const XI3C_ALL_FIFOS_RESET_MASK: u32 = 0x1e;
register_structs! {
pub XI3c {
(0x0 => pub version: ReadOnly<u32>), // Version Register
(0x4 => pub reset: ReadWrite<u32>), // Soft Reset Register
(0x8 => pub cr: ReadWrite<u32>), // Control Register
(0xC => pub address: ReadWrite<u32>), // Target Address Register
(0x10 => pub sr: ReadWrite<u32>), // Status Register
(0x14 => pub intr_status: ReadWrite<u32>), // Status Event Register
(0x18 => pub intr_re: ReadWrite<u32>), // Status Event Enable(Rising Edge) Register
(0x1C => pub intr_fe: ReadWrite<u32>), // Status Event Enable(Falling Edge) Register
(0x20 => pub cmd_fifo: ReadWrite<u32>), // I3C Command FIFO Register
(0x24 => pub wr_fifo: ReadWrite<u32>), // I3C Write Data FIFO Register
(0x28 => pub rd_fifo: ReadWrite<u32>), // I3C Read Data FIFO Register
(0x2C => pub resp_status_fifo: ReadWrite<u32>), // I3C Response status FIFO Register
(0x30 => pub fifo_lvl_status: ReadWrite<u32>), // I3C CMD & WR FIFO LVL Register
(0x34 => pub fifo_lvl_status_1: ReadWrite<u32>), // I3C RESP & RD FIFO LVL Register
(0x38 => pub scl_high_time: ReadWrite<u32>), // I3C SCL HIGH Register
(0x3C => pub scl_low_time: ReadWrite<u32>), // I3C SCL LOW Register
(0x40 => pub sda_hold_time: ReadWrite<u32>), // I3C SDA HOLD Register
(0x44 => pub bus_idle: ReadWrite<u32>), // I3C CONTROLLER BUS IDLE Register
(0x48 => pub tsu_start: ReadWrite<u32>), // I3C START SETUP Register
(0x4C => pub thd_start: ReadWrite<u32>), // I3C START HOLD Register
(0x50 => pub tsu_stop: ReadWrite<u32>), // I3C STOP Setup Register
(0x54 => pub od_scl_high_time: ReadWrite<u32>), // I3C OD SCL HIGH Register
(0x58 => pub od_scl_low_time: ReadWrite<u32>), // I3C OD SCL LOW Register
(0x5C => _reserved),
(0x60 => pub target_addr_bcr: ReadWrite<u32>), // I3C Target dynamic Address and BCR Register
(0x64 => @END),
}
}
pub enum Ccc {
Byte(u8),
Data(Vec<u8>),
}
#[derive(Clone)]
pub struct Config {
pub device_id: u16,
pub base_address: *mut u32,
pub input_clock_hz: u32,
pub rw_fifo_depth: u8,
pub wr_threshold: u8,
pub device_count: u8,
pub ibi_capable: bool,
pub hj_capable: bool,
pub entdaa_enable: bool,
pub known_static_addrs: Vec<u8>, // if entdaa is disabled, we have to know the static addresses to do SETDASA
}
unsafe impl Send for Controller {}
unsafe impl Sync for Controller {}
#[derive(Clone)]
pub struct Command {
/// I3C command type. 0 = legacy i2c, 1 = SDR, 2+ reserve
pub cmd_type: u8,
/// toc (termination on completion).
/// 0 = next command will be started with Sr
/// 1 = stop command will be issued after the existing command is completed
pub no_repeated_start: u8,
/// pec enable. Per the JEDEC standard, the PEC value will be computed. 0 = disable PEC, 1 = enable PEC.
pub pec: u8,
pub target_addr: u8,
pub rw: u8,
/// Bytes to Read/Write. This field acts as bytes to read/write (for common command codes (CCC) command, the number of bytes to read or write along with CCC like defining bytes for direct/broadcast CCC or subcommand bytes for broadcast CCC).
/// Only in SDR/I2C commands.
/// For other commands, it should be zero. The IP supports 4095 bytes to Read/Write for the SDR/I2C command.
pub byte_count: u16,
/// Transaction ID: This field acts as identification tag for I3C commands. The controller returns this tag along with the transaction status
pub tid: u8,
}
impl Default for Command {
fn default() -> Self {
Command {
cmd_type: XI3C_CMD_TYPE_I3C,
no_repeated_start: 0,
pec: 0,
target_addr: 0,
rw: 0,
byte_count: 0,
tid: 0,
}
}
}
#[derive(Copy, Clone, Default)]
pub struct TargetInfo {
pub dyna_addr: u8,
pub id: u64,
pub bcr: u8,
pub dcr: u8,
}
pub struct Controller {
pub config: Config,
pub ready: Cell<bool>,
pub error: Cell<u8>,
pub cur_device_count: Cell<u8>,
pub status_handler: Cell<Option<Box<dyn ErrorHandler + Send + Sync>>>,
pub target_info_table: RefCell<[TargetInfo; 108]>,
}
pub trait ErrorHandler {
fn handle_error(&self, error: u32);
}
pub static DYNA_ADDR_LIST: [u8; 108] = [
0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x5b, 0x5c, 0x5d, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
0x6b, 0x6c, 0x6d, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x77,
];
impl Controller {
pub fn new(config: Config) -> Self {
Controller {
config,
ready: false.into(),
error: 0.into(),
cur_device_count: 0.into(),
status_handler: None.into(),
target_info_table: RefCell::new([TargetInfo::default(); 108]),
}
}
#[inline(always)]
pub(crate) const fn regs(&self) -> &XI3c {
unsafe { &*(self.config.base_address as *const XI3c) }
}
pub fn bus_init(&self) -> Result<(), XI3cError> {
let cmd = Command {
cmd_type: XI3C_CMD_TYPE_I3C,
no_repeated_start: 1,
pec: 0,
target_addr: XI3C_BROADCAST_ADDRESS,
rw: 0,
byte_count: 0,
tid: 0,
};
// Disable Target Events
println!("XI3C: Broadcast CCC DISEC");
let result = self.send_transfer_cmd(&cmd, Ccc::Byte(XI3C_CCC_BRDCAST_DISEC));
if result.is_ok() {
println!("XI3C: Acknowledge received");
}
// Enable Target Events
println!("XI3C: Broadcast CCC ENEC");
let result = self.send_transfer_cmd(&cmd, Ccc::Byte(XI3C_CCC_BRDCAST_ENEC));
if result.is_ok() {
println!("XI3C: Acknowledge received");
}
// Reset Dynamic Address assigned to all the I3C Targets
println!("XI3C: Broadcast CCC RSTDAA");
let result = self.send_transfer_cmd(&cmd, Ccc::Byte(XI3C_CCC_BRDCAST_RSTDAA));
if result.is_ok() {
println!("XI3C: Acknowledge received");
}
Ok(())
}
pub fn set_i3c_not_ready(&self) {
self.ready.set(false);
}
pub fn cfg_initialize(&self) -> Result<(), XI3cError> {
if self.ready.get() {
return Err(XI3cError::DeviceStarted);
}
self.cur_device_count.set(0);
// Indicate the instance is now ready to use, initialized without error
self.ready.set(true);
// Reset the I3C controller to get it into its initial state. It is expected
// that device configuration will take place after this initialization
// is done, but before the device is started.
self.reset();
self.reset_fifos();
if self.config.ibi_capable {
println!("XI3C: enabling IBI");
self.enable_ibi();
}
if self.config.hj_capable {
self.enable_hotjoin();
}
// Enable I3C controller
self.enable(1);
self.bus_init()?;
if self.config.ibi_capable && self.config.device_count != 0 {
// cheat by enabling IBI everywhere
for i in 0..128 {
self.regs().target_addr_bcr.set(0x700 | i);
}
if self.config.entdaa_enable {
self.dyna_addr_assign(&DYNA_ADDR_LIST, self.config.device_count)?;
} else {
let static_addrs = self.config.known_static_addrs.clone();
println!(
"XI3C: initializing dynamic addresses with SETDASA (static address: {:x?})",
&static_addrs
);
let cmd = Command {
cmd_type: XI3C_CMD_TYPE_I3C,
no_repeated_start: 0,
pec: 0,
target_addr: XI3C_BROADCAST_ADDRESS,
rw: 0,
byte_count: 1,
tid: 2,
};
assert!(self.ready.get());
println!("XI3C: Broadcast CCC SETDASA");
self.send_transfer_cmd(&cmd, Ccc::Byte(XI3C_CCC_SETDASA))?;
println!("XI3C: Acknowledged");
for (i, addr) in static_addrs.iter().enumerate() {
self.dyna_addr_assign_static(
*addr,
DYNA_ADDR_LIST[i],
i == DYNA_ADDR_LIST.len() - 1,
)?;
}
}
self.config_ibi(self.config.device_count);
}
// Enable Hot join raising edge interrupt.
if self.config.hj_capable {
self.regs()
.intr_re
.set(self.regs().intr_re.get() | XI3C_INTR_HJ_MASK);
}
Ok(())
}
pub fn fill_cmd_fifo(&self, cmd: &Command) {
let dev_addr = ((cmd.target_addr & 0x7f) << 1) | cmd.rw & 0x1;
let mut transfer_cmd = (cmd.cmd_type & 0xf) as u32;
transfer_cmd |= ((cmd.no_repeated_start & 0x1) as u32) << 4;
transfer_cmd |= ((cmd.pec & 0x1) as u32) << 5;
transfer_cmd |= (dev_addr as u32) << 8;
transfer_cmd |= ((cmd.byte_count & 0xfff) as u32) << 16;
transfer_cmd |= ((cmd.tid & 0xf) as u32) << 28;
self.regs().cmd_fifo.set(transfer_cmd);
}
pub fn write_tx_fifo(&self, send_buffer: &[u8]) -> usize {
let data = if send_buffer.len() > 3 {
u32::from_be_bytes(send_buffer[0..4].try_into().unwrap())
} else {
let mut data = 0;
for (i, x) in send_buffer.iter().enumerate() {
data |= (*x as u32) << (24 - 8 * i);
}
data
};
self.regs().wr_fifo.set(data);
send_buffer.len().min(4)
}
pub fn read_rx_fifo(&self, recv_byte_count: u16) -> Vec<u8> {
let data = self.regs().rd_fifo.get();
if recv_byte_count > 3 {
data.to_be_bytes().to_vec()
} else {
data.to_be_bytes()[0..recv_byte_count as usize].to_vec()
}
}
/// Assign a dynamic address to a single static device using SETDASA
pub fn dyna_addr_assign_static(
&self,
static_addr: u8,
dyn_addr: u8,
last: bool,
) -> Result<(), XI3cError> {
let cmd = Command {
cmd_type: XI3C_CMD_TYPE_I3C,
no_repeated_start: if last { 1 } else { 0 }, // controller has a bug where it does not send 7E after CCC if it is a repeated start followed by non-CCC
pec: 0,
target_addr: static_addr,
rw: 0,
byte_count: 1,
tid: 3,
};
let addr = dyn_addr << 1;
println!(
"XI3C: Controller: Assigning dynamic address with SETDASA private write {:x}",
addr >> 1
);
self.master_send_polled(&cmd, &[addr], 1)?;
println!("XI3C: Acknowledged");
let mut table = self.target_info_table.borrow_mut();
let cur_device_count = self.cur_device_count.get() as usize;
table[cur_device_count].id = static_addr as u64;
table[cur_device_count].dyna_addr = dyn_addr;
// TODO: should we get the DCR and BCR from the device?
self.cur_device_count.set((cur_device_count + 1) as u8);
Ok(())
}
/// Assign dynamic addresses to all devices using ENTDAA
pub fn dyna_addr_assign(&self, dyna_addr: &[u8], dev_count: u8) -> Result<(), XI3cError> {
let mut cmd = Command {
cmd_type: 0,
no_repeated_start: 0,
pec: 0,
target_addr: 0,
rw: 0,
byte_count: 0,
tid: 0,
};
assert!(self.ready.get());
cmd.no_repeated_start = 0;
cmd.target_addr = XI3C_BROADCAST_ADDRESS;
cmd.tid = 0;
cmd.pec = 0;
cmd.cmd_type = 1;
println!("XI3C: Broadcast CCC ENTDAA");
self.send_transfer_cmd(&cmd, Ccc::Byte(XI3C_CCC_BRDCAST_ENTDAA))?;
println!("XI3C: Acknowledged");
let mut index = 0;
while index < dev_count as u16 && index < 108 {
let addr = (dyna_addr[index as usize] << 1) | get_odd_parity(dyna_addr[index as usize]);
self.write_tx_fifo(&[addr]);
if index + 1 == dev_count as u16 {
cmd.no_repeated_start = 1;
} else {
cmd.no_repeated_start = 0;
}
cmd.target_addr = XI3C_BROADCAST_ADDRESS;
cmd.tid = 0;
cmd.pec = 0;
cmd.cmd_type = 1;
println!(
"XI3C: Controller: Assigning dynamic address 0x{:x}",
addr >> 1
);
let recv_buffer = match self.master_recv_polled(None, &cmd, 9) {
Ok(recv_buffer) => recv_buffer,
Err(err) => {
println!("XI3C: No ack received for assigning address");
return Err(err);
}
};
println!("XI3C: cur_device_count = {}", self.cur_device_count.get());
let mut table = self.target_info_table.borrow_mut();
let cur_device_count = self.cur_device_count.get() as usize;
table[cur_device_count].id = ((recv_buffer[0] as u64) << 40)
| ((recv_buffer[1] as u64) << 32)
| ((recv_buffer[2] as u64) << 24)
| ((recv_buffer[3] as u64) << 16)
| ((recv_buffer[4] as u64) << 8)
| recv_buffer[5] as u64;
table[cur_device_count].bcr = recv_buffer[6];
println!("XI3C: Controller received BCR: {:x}", recv_buffer[6]);
println!("XI3C: Controller received DCR: {:x}", recv_buffer[7]);
table[cur_device_count].dcr = recv_buffer[7];
table[cur_device_count].dyna_addr = dyna_addr[index as usize];
self.cur_device_count.set((cur_device_count + 1) as u8);
index += 1;
}
Ok(())
}
pub fn config_ibi(&self, dev_count: u8) {
assert!(self.ready.get());
let mut index = 0;
while index < dev_count && index < 108 {
self.update_addr_bcr(index as u16);
index += 1;
}
}
#[inline]
pub fn enable(&self, enable: u8) {
assert!(self.ready.get());
let mut data = self.regs().cr.get();
data &= !XI3C_CR_EN_MASK;
data |= enable as u32;
self.regs().cr.set(data);
println!("XI3C: Enable set to {:x}", self.regs().cr.get());
}
#[inline]
pub fn resume(&self, resume: u8) {
assert!(self.ready.get());
let mut data = self.regs().cr.get();
data &= !XI3C_CR_RESUME_MASK;
data |= resume as u32;
self.regs().cr.set(data);
println!("XI3C: Resume set to {:x}", self.regs().cr.get());
}
#[inline]
fn enable_ibi(&self) {
assert!(self.ready.get());
let mut data = self.regs().cr.get();
data |= XI3C_CR_IBI_MASK;
self.regs().cr.set(data);
println!(
"Control register after enabling IBI: {:x}",
self.regs().cr.get()
);
}
#[inline]
fn enable_hotjoin(&self) {
assert!(self.ready.get());
let mut data = self.regs().cr.get();
data |= XI3C_CR_HJ_MASK;
self.regs().cr.set(data);
}
#[inline]
pub fn update_addr_bcr(&self, dev_index: u16) {
assert!(self.ready.get());
let table = self.target_info_table.borrow();
let mut addr_bcr = (table[dev_index as usize].dyna_addr & 0x7f) as u32;
addr_bcr |= (table[dev_index as usize].bcr as u32) << 8;
println!(
"XI3C: Updating BCR (index {}) for device {:x}",
dev_index, addr_bcr
);
self.regs().target_addr_bcr.set(addr_bcr);
}
pub fn off(&self) {
let mut data = self.regs().reset.get();
data |= XI3C_SOFT_RESET_MASK;
self.regs().reset.set(data);
}
#[inline]
pub fn reset(&self) {
assert!(self.ready.get());
let mut data = self.regs().reset.get();
data |= XI3C_SOFT_RESET_MASK;
self.regs().reset.set(data);
std::thread::sleep(Duration::from_micros(50));
data &= !XI3C_SOFT_RESET_MASK;
self.regs().reset.set(data);
std::thread::sleep(Duration::from_micros(10));
}
#[inline]
pub fn reset_fifos(&self) {
assert!(self.ready.get());
let mut data = self.regs().reset.get();
data |= XI3C_ALL_FIFOS_RESET_MASK;
self.regs().reset.set(data);
std::thread::sleep(Duration::from_micros(50));
data &= !XI3C_ALL_FIFOS_RESET_MASK;
self.regs().reset.set(data);
std::thread::sleep(Duration::from_micros(10));
}
/// Sets I3C Scl clock frequency.
/// - s_clk_hz is Scl clock to be configured in Hz.
/// - mode is the mode of operation I2C/I3C.
pub fn set_s_clk(&self, input_clock_hz: u32, s_clk_hz: u32, mode: u8) {
assert!(s_clk_hz > 0);
let t_high = input_clock_hz
.wrapping_add(s_clk_hz)
.wrapping_sub(1)
.wrapping_div(s_clk_hz)
>> 1;
let t_low = t_high;
let mut t_hold = t_low.wrapping_mul(4).wrapping_div(10);
let core_period_ns = 1_000_000_000_u32
.wrapping_add(input_clock_hz)
.wrapping_sub(1)
.wrapping_div(input_clock_hz);
if (self.regs().version.get() & 0xff00) >> 8 == 0 {
t_hold = if t_hold < 5 { 5 } else { t_hold };
} else {
t_hold = if t_hold < 6 { 6 } else { t_hold };
}
self.regs()
.scl_high_time
.set(t_high.wrapping_sub(2) & 0x3ffff);
self.regs()
.scl_low_time
.set(t_low.wrapping_sub(2) & 0x3ffff);
self.regs()
.sda_hold_time
.set(t_hold.wrapping_sub(2) & 0x3ffff);
let tcas_min: u32;
let mut od_t_high: u32;
let mut od_t_low: u32;
if mode == 0 {
self.regs()
.od_scl_high_time
.set(t_high.wrapping_sub(2) & 0x3ffff);
self.regs()
.od_scl_low_time
.set(t_low.wrapping_sub(2) & 0x3ffff);
tcas_min = 600_u32
.wrapping_add(core_period_ns)
.wrapping_sub(1)
.wrapping_div(core_period_ns);
} else {
od_t_low = 500_u32
.wrapping_add(core_period_ns)
.wrapping_sub(1)
.wrapping_div(core_period_ns);
od_t_high = 41_u32
.wrapping_add(core_period_ns)
.wrapping_sub(1)
.wrapping_div(core_period_ns);
od_t_low = if t_low < od_t_low { od_t_low } else { t_low };
od_t_high = if t_high > od_t_high {
od_t_high
} else {
t_high
};
self.regs()
.od_scl_high_time
.set(od_t_high.wrapping_sub(2) & 0x3ffff);
self.regs()
.od_scl_low_time
.set(od_t_low.wrapping_sub(2) & 0x3ffff);
tcas_min = 39_u32
.wrapping_add(core_period_ns)
.wrapping_sub(1)
.wrapping_div(core_period_ns);
}
let thd_start = if t_high > tcas_min { t_high } else { tcas_min };
let tsu_start = if t_low > tcas_min { t_low } else { tcas_min };
let tsu_stop = if t_low > tcas_min { t_low } else { tcas_min };
self.regs()
.tsu_start
.set(tsu_start.wrapping_sub(2) & 0x3ffff);
self.regs()
.thd_start
.set(thd_start.wrapping_sub(2) & 0x3ffff);
self.regs()
.tsu_stop
.set(tsu_stop.wrapping_sub(2) & (0x3ffff + 5));
}
fn get_response(&self) -> Result<(), XI3cError> {
let happened = self.wait_for_event(
XI3C_SR_RESP_NOT_EMPTY_MASK,
XI3C_SR_RESP_NOT_EMPTY_MASK,
MAX_TIMEOUT_US,
);
if !happened {
return Err(XI3cError::Timeout);
}
let response_data = self.regs().resp_status_fifo.get();
let error_code = ((response_data & 0x1e0) >> 5) as i32;
if error_code != 0 {
Err(XI3cError::SendError)
} else {
Ok(())
}
}
pub fn send_transfer_cmd(&self, cmd: &Command, data: Ccc) -> Result<(), XI3cError> {
assert!(self.ready.get());
let mut cmd = cmd.clone();
match data {
Ccc::Byte(byte) => {
cmd.byte_count = 1;
self.write_tx_fifo(&[byte]);
}
Ccc::Data(data) => {
cmd.byte_count = data.len() as u16;
self.write_tx_fifo(&data);
}
}
cmd.target_addr = XI3C_BROADCAST_ADDRESS;
cmd.rw = 0;
self.fill_cmd_fifo(&cmd);
self.get_response()
}
pub fn master_send(
&self,
cmd: &Command,
mut msg_ptr: &[u8],
byte_count: u16,
) -> Result<(), XI3cError> {
if msg_ptr.is_empty() {
return Err(XI3cError::NoData);
}
if byte_count > 4095 {
return Err(XI3cError::SendError);
}
msg_ptr = &msg_ptr[..byte_count as usize];
let mut cmd = cmd.clone();
cmd.byte_count = byte_count;
cmd.rw = 0;
let wr_fifo_space = (self.regs().fifo_lvl_status.get() & 0xffff) as u16;
let mut space_index: u16 = 0;
while space_index < wr_fifo_space && !msg_ptr.is_empty() {
let size = self.write_tx_fifo(msg_ptr);
msg_ptr = &msg_ptr[size..];
space_index += 1;
}
if (self.config.wr_threshold as u16) < byte_count {
self.regs().intr_fe.set(self.regs().intr_fe.get() | 0x20);
}
self.regs().intr_re.set(self.regs().intr_re.get() | 0x10);
self.fill_cmd_fifo(&cmd);
Ok(())
}
/// This function initiates a polled mode send in master mode.
///
/// It sends data to the FIFO and waits for the slave to pick them up.
/// If controller fails to send data due arbitration lost or any other error,
/// will stop transfer status.
/// - msg_ptr is the pointer to the send buffer.
/// - byte_count is the number of bytes to be sent.
pub fn master_send_polled(
&self,
cmd: &Command,
mut msg_ptr: &[u8],
byte_count: u16,
) -> Result<(), XI3cError> {
if msg_ptr.is_empty() {
return Err(XI3cError::NoData);
}
if byte_count > 4095 {
return Err(XI3cError::SendError);
}
msg_ptr = &msg_ptr[..byte_count as usize];
let mut cmd = cmd.clone();
cmd.byte_count = byte_count;
cmd.rw = 0;
if self.write_fifo_level() * 4 >= msg_ptr.len() as u16 {
// write the whole message at once for reliability
while !msg_ptr.is_empty() {
let written = self.write_tx_fifo(msg_ptr);
msg_ptr = &msg_ptr[written..];
}
self.fill_cmd_fifo(&cmd);
} else {
// not enough room, stream it in
self.fill_cmd_fifo(&cmd);
while !msg_ptr.is_empty() {
let wr_fifo_space = (self.regs().fifo_lvl_status.get() & 0xffff) as u16;
let mut space_index: u16 = 0;
while space_index < wr_fifo_space && !msg_ptr.is_empty() {
let written = self.write_tx_fifo(msg_ptr);
msg_ptr = &msg_ptr[written..];
space_index += 1;
}
}
}
// send cmd fifo last to ensure that data is in fifo before command starts
self.get_response()
}
pub fn master_recv_polled(
&self,
running: Option<Arc<AtomicBool>>,
cmd: &Command,
byte_count: u16,
) -> Result<Vec<u8>, XI3cError> {
self.master_recv(cmd, byte_count)?;
self.master_recv_finish(running, cmd, byte_count)
}
/// Starts a receive from a target, but does not wait on the result (must call .master_recv_finish() separately).
pub fn master_recv(&self, cmd: &Command, byte_count: u16) -> Result<(), XI3cError> {
if byte_count > 4095 {
return Err(XI3cError::RecvError);
}
let mut cmd = cmd.clone();
cmd.byte_count = byte_count;
cmd.rw = 1;
self.fill_cmd_fifo(&cmd);
Ok(())
}
/// Receives up to 4 bytes from the read FIFO.
/// Could return fewer. 0 bytes are returned if no data is available.
pub fn master_recv_4_bytes(&self) -> Vec<u8> {
let rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
if rx_data_available > 0 {
self.read_rx_fifo(rx_data_available.min(4))
} else {
vec![]
}
}
pub fn recv_data_available(&self) -> u16 {
(self.regs().fifo_lvl_status_1.get() & 0xffff) as u16
}
pub fn recv_bytes(&self, running: Option<Arc<AtomicBool>>, byte_count: u16) -> Vec<u8> {
let mut recv_byte_count = byte_count;
let mut recv = vec![];
let running = running.unwrap_or_else(|| Arc::new(AtomicBool::new(true)));
while running.load(Ordering::Relaxed) && recv_byte_count > 0 {
let rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
let mut data_index: u16 = 0;
while data_index < rx_data_available && recv_byte_count > 0 {
let new_bytes = self.read_rx_fifo(recv_byte_count);
recv.extend(&new_bytes);
recv_byte_count = recv_byte_count.saturating_sub(new_bytes.len() as u16);
data_index += 1;
}
}
recv
}
/// Finishes a receive from a target.
pub fn master_recv_finish(
&self,
running: Option<Arc<AtomicBool>>,
cmd: &Command,
byte_count: u16,
) -> Result<Vec<u8>, XI3cError> {
let mut recv_byte_count = if cmd.target_addr == XI3C_BROADCAST_ADDRESS {
(byte_count as i32 - 1) as u16
} else {
byte_count
};
let mut recv = vec![];
let running = running.unwrap_or_else(|| Arc::new(AtomicBool::new(true)));
while running.load(Ordering::Relaxed) && recv_byte_count > 0 {
let rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
let mut data_index: u16 = 0;
while data_index < rx_data_available && recv_byte_count > 0 {
let new_bytes = self.read_rx_fifo(recv_byte_count);
recv.extend(&new_bytes);
recv_byte_count = recv_byte_count.saturating_sub(new_bytes.len() as u16);
data_index += 1;
}
}
self.get_response()?;
Ok(recv)
}
fn ibi_read_rx_fifo(&self) -> Vec<u8> {
let rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
let mut data_index: u16 = 0;
let mut recv = vec![];
while data_index < rx_data_available {
recv.extend(self.read_rx_fifo(4));
data_index += 1;
}
recv
}
#[allow(dead_code)]
pub fn set_status_handler(&self, handler: Box<dyn ErrorHandler + Send + Sync>) {
assert!(self.ready.get());
self.status_handler.set(Some(handler));
}
pub fn ibi_ready(&self) -> bool {
self.regs().sr.get() & XI3C_SR_RD_FIFO_NOT_EMPTY_MASK != 0
}
pub fn interrupt_status(&self) -> u32 {
self.regs().intr_status.get()
}
pub fn interrupt_enable_set(&self, mask: u32) {
self.regs().intr_re.set(mask)
}
pub fn status(&self) -> u32 {
self.regs().sr.get()
}
/// Available space in CMD_FIFO to write
pub fn cmd_fifo_level(&self) -> u16 {
((self.regs().fifo_lvl_status.get() >> 16) & 0xffff) as u16
}
/// Available space in WR_FIFO to write
pub fn write_fifo_level(&self) -> u16 {
(self.regs().fifo_lvl_status.get() & 0xffff) as u16
}
/// Number of RESP status details are available in RESP_FIFO to read
pub fn resp_fifo_level(&self) -> u16 {
((self.regs().fifo_lvl_status_1.get() >> 16) & 0xffff) as u16
}
/// Number of read data words are available in RD_FIFO to read
pub fn read_fifo_level(&self) -> u16 {
(self.regs().fifo_lvl_status_1.get() & 0xffff) as u16
}
/// This function receives data during IBI in polled mode.
///
/// It polls the data register for data to come in during IBI.
/// If controller fails to read data due to any error, it will return an Err with the status.
pub fn ibi_recv_polled(&self, timeout: Duration) -> Result<Vec<u8>, XI3cError> {
let mut recv = vec![];
let mut data_index: u16;
let mut rx_data_available: u16;
let timeout = (timeout.as_micros() as u32).min(MAX_TIMEOUT_US);
let happened = self.wait_for_event(
XI3C_SR_RD_FIFO_NOT_EMPTY_MASK,
XI3C_SR_RD_FIFO_NOT_EMPTY_MASK,
timeout,
);
if happened {
while self.regs().sr.get() & XI3C_SR_RD_FIFO_NOT_EMPTY_MASK != 0
|| self.regs().sr.get() & XI3C_SR_RESP_NOT_EMPTY_MASK == 0
{
rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
data_index = 0;
while data_index < rx_data_available {
recv.extend(self.read_rx_fifo(4));
data_index += 1;
}
}
rx_data_available = (self.regs().fifo_lvl_status_1.get() & 0xffff) as u16;
data_index = 0;
while data_index < rx_data_available {
recv.extend(self.read_rx_fifo(4));
data_index += 1;
}
}
self.get_response()?;
Ok(recv)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/src/xi3c/mod.rs | hw-model/src/xi3c/mod.rs | // Licensed under the Apache-2.0 license
//! This is a driver for the Xilinx AXI I3C controller that is used in Xilinx
//! FPGAs for testing.
//!
//! Documentation for the underlying hardware is available at
//! https://docs.amd.com/r/en-US/pg439-axi-i3c/.
mod controller;
pub use controller::{Ccc, Command, Config, Controller, XI3c};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XI3cError {
/// Device is already started
DeviceStarted,
/// There was no data available
NoData,
/// Generic receive error
RecvError,
/// Generic transmit error
SendError,
/// Timeout error
Timeout,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/tests/model_tests.rs | hw-model/tests/model_tests.rs | // Licensed under the Apache-2.0 license
use caliptra_api::SocManager;
use caliptra_builder::firmware;
use caliptra_hw_model::{BootParams, DefaultHwModel, HwModel, InitParams};
use caliptra_hw_model_types::ErrorInjectionMode;
use caliptra_test_harness_types as harness;
#[cfg(feature = "fpga_realtime")]
use std::process::{Child, Command};
#[cfg(feature = "fpga_realtime")]
use std::thread;
#[cfg(feature = "fpga_realtime")]
use std::time::{Duration, Instant};
#[cfg(feature = "fpga_realtime")]
fn wait_with_timeout(child: &mut Child, timeout: Duration) -> Option<i32> {
let start = Instant::now();
while start.elapsed() < timeout {
match child.try_wait() {
Ok(Some(status)) => return status.code(),
Ok(None) => thread::sleep(Duration::from_millis(100)), // Check every 100ms
Err(_) => return None,
}
}
let _ = child.kill();
None
}
fn run_fw_elf(elf: &[u8]) -> DefaultHwModel {
let rom = caliptra_builder::elf2rom(elf).unwrap();
caliptra_hw_model::new(
InitParams {
rom: &rom,
random_sram_puf: false,
..Default::default()
},
BootParams::default(),
)
.unwrap()
}
fn run_fw_elf_with_rand_puf(elf: &[u8]) -> DefaultHwModel {
let rom = caliptra_builder::elf2rom(elf).unwrap();
caliptra_hw_model::new(
InitParams {
rom: &rom,
..Default::default()
},
BootParams::default(),
)
.unwrap()
}
#[test]
fn test_iccm_byte_write_nmi_failure() {
let elf = caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_ICCM_BYTE_WRITE)
.unwrap();
let symbols = caliptra_builder::elf_symbols(&elf).unwrap();
let main_symbol = symbols.iter().find(|s| s.name == "main").unwrap();
let main_addr = main_symbol.value as u32;
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_NMI
);
let nmi_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
// Exactly where the PC is when the NMI fires is a bit fuzzy...
assert!(nmi_info.mepc >= main_addr + 4 && nmi_info.mepc <= main_addr + 24);
assert_eq!(nmi_info.mcause, harness::NMI_CAUSE_DBUS_STORE_ERROR);
}
#[test]
fn test_iccm_unaligned_write_nmi_failure() {
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_ICCM_UNALIGNED_WRITE)
.unwrap();
let symbols = caliptra_builder::elf_symbols(&elf).unwrap();
let main_symbol = symbols.iter().find(|s| s.name == "main").unwrap();
let main_addr = main_symbol.value as u32;
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_NMI
);
let ext_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
// Exactly where the PC is when the NMI fires is a bit fuzzy...
assert!(ext_info.mepc >= main_addr + 4 && ext_info.mepc <= main_addr + 24);
assert_eq!(ext_info.mcause, harness::NMI_CAUSE_DBUS_STORE_ERROR);
}
#[test]
fn test_iccm_write_locked_nmi_failure() {
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_ICCM_WRITE_LOCKED)
.unwrap();
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_NMI
);
let ext_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
assert_eq!(ext_info.mcause, harness::NMI_CAUSE_DBUS_STORE_ERROR);
}
#[test]
fn test_invalid_instruction_exception_failure() {
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_INVALID_INSTRUCTION)
.unwrap();
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_EXCEPTION
);
let ext_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
assert_eq!(
ext_info.mcause,
harness::EXCEPTION_CAUSE_ILLEGAL_INSTRUCTION_ERROR
);
}
#[test]
fn test_write_to_rom() {
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_WRITE_TO_ROM).unwrap();
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_EXCEPTION
);
}
#[test]
fn test_iccm_double_bit_ecc_nmi_failure() {
// FPGA realtime model doesn't support ecc error injection
#![cfg_attr(feature = "fpga_realtime", ignore)]
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_ICCM_DOUBLE_BIT_ECC)
.unwrap();
let mut model = run_fw_elf(&elf);
model.ecc_error_injection(ErrorInjectionMode::IccmDoubleBitEcc);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_EXCEPTION
);
let ext_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
assert_eq!(
ext_info.mcause,
harness::EXCEPTION_CAUSE_INSTRUCTION_ACCESS_FAULT
);
}
#[test]
fn test_dccm_double_bit_ecc_nmi_failure() {
// FPGA realtime model doesn't support ecc error injection
#![cfg_attr(feature = "fpga_realtime", ignore)]
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_DCCM_DOUBLE_BIT_ECC)
.unwrap();
let mut model = run_fw_elf(&elf);
model.ecc_error_injection(ErrorInjectionMode::DccmDoubleBitEcc);
model.step_until_exit_success().unwrap_err();
let soc_ifc: caliptra_registers::soc_ifc::RegisterBlock<_> = model.soc_ifc();
assert_eq!(
soc_ifc.cptra_fw_error_non_fatal().read(),
harness::ERROR_EXCEPTION
);
let ext_info = harness::ExtErrorInfo::from(soc_ifc.cptra_fw_extended_error_info().read());
assert_eq!(ext_info.mcause, harness::EXCEPTION_CAUSE_LOAD_ACCESS_FAULT);
}
#[test]
fn test_uninitialized_dccm_read() {
#![cfg_attr(not(feature = "verilator"), ignore)]
let mut model = run_fw_elf_with_rand_puf(
&caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_UNITIALIZED_READ)
.unwrap(),
);
const DCCM_ADDR: u32 = 0x5000_0000;
const DCCM_SIZE: u32 = 256 * 1024;
model.soc_ifc().cptra_rsvd_reg().at(0).write(|_| DCCM_ADDR);
model.soc_ifc().cptra_rsvd_reg().at(1).write(|_| DCCM_SIZE);
model.step_until_exit_failure().unwrap();
let ext_info =
harness::ExtErrorInfo::from(model.soc_ifc().cptra_fw_extended_error_info().read());
assert_eq!(ext_info.mcause, harness::EXCEPTION_CAUSE_LOAD_ACCESS_FAULT);
assert_eq!(
ext_info.mscause,
harness::MCAUSE_LOAD_ACCESS_FAULT_MSCAUSE_DCCM_DOUBLE_BIT_ECC
);
assert!(model.soc_ifc().cptra_hw_error_fatal().read().dccm_ecc_unc());
}
#[test]
fn test_uninitialized_iccm_read() {
#![cfg_attr(not(feature = "verilator"), ignore)]
let mut model = run_fw_elf_with_rand_puf(
&caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_UNITIALIZED_READ)
.unwrap(),
);
const ICCM_ADDR: u32 = 0x4000_0000;
const ICCM_SIZE: u32 = 256 * 1024;
model.soc_ifc().cptra_rsvd_reg().at(0).write(|_| ICCM_ADDR);
model.soc_ifc().cptra_rsvd_reg().at(1).write(|_| ICCM_SIZE);
model.step_until_exit_failure().unwrap();
let ext_info =
harness::ExtErrorInfo::from(model.soc_ifc().cptra_fw_extended_error_info().read());
assert_eq!(
ext_info.mcause,
harness::NMI_CAUSE_DBUS_NON_BLOCKING_LOAD_ERROR
);
assert_eq!(ext_info.mscause, 0);
}
#[test]
fn test_uninitialized_mbox_read() {
#![cfg_attr(not(feature = "verilator"), ignore)]
let mut model = run_fw_elf_with_rand_puf(
&caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_UNITIALIZED_READ)
.unwrap(),
);
#[cfg(feature = "verilator")]
model.corrupt_mailbox_ecc_double_bit();
const MBOX_ADDR: u32 = 0x3000_0000;
model.soc_ifc().cptra_rsvd_reg().at(0).write(|_| MBOX_ADDR);
model.soc_ifc().cptra_rsvd_reg().at(1).write(|_| 1024);
assert!(!model
.soc_ifc()
.cptra_hw_error_non_fatal()
.read()
.mbox_ecc_unc());
// NOTE: CPU execution will continue after the ECC error
model.step_until_exit_success().unwrap();
assert!(model
.soc_ifc()
.cptra_hw_error_non_fatal()
.read()
.mbox_ecc_unc());
}
#[test]
fn test_pcr_extend() {
let elf =
caliptra_builder::build_firmware_elf(&firmware::hw_model_tests::TEST_PCR_EXTEND).unwrap();
let mut model = run_fw_elf(&elf);
model.step_until_exit_success().unwrap();
}
#[test]
#[cfg(feature = "fpga_realtime")]
#[ignore] // TODO: this will hard crash the FPGA host in 2.0 until we update the test binary
fn test_mbox_pauser_sigbus() {
fn find_binary_path() -> Option<&'static str> {
// Use this path when running on github.
const TEST_BIN_PATH_SQUASHFS:&str = "/tmp/caliptra-test-binaries/target/aarch64-unknown-linux-gnu/release/fpga_realtime_mbox_pauser";
const TEST_BIN_PATH: &str = env!("CARGO_BIN_EXE_fpga_realtime_mbox_pauser");
if std::path::Path::new(TEST_BIN_PATH_SQUASHFS).exists() {
Some(TEST_BIN_PATH_SQUASHFS)
} else if std::path::Path::new(TEST_BIN_PATH).exists() {
Some(TEST_BIN_PATH)
} else {
None
}
}
let mut child = Command::new(find_binary_path().unwrap())
.spawn()
.expect("Failed to start mbox_pauser test utility");
let exit_code = wait_with_timeout(&mut child, Duration::from_secs(120));
// Check if the exit code is 42
assert_eq!(exit_code, Some(42));
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/mailbox_responder.rs | hw-model/test-fw/mailbox_responder.rs | // Licensed under the Apache-2.0 license
//! A very simple program that responds to the mailbox.
#![no_main]
#![no_std]
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
use caliptra_drivers::cprint;
use caliptra_registers::{self, mbox::MboxCsr, sha512_acc::Sha512AccCsr, soc_ifc::SocIfcReg};
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
#[no_mangle]
extern "C" fn main() {
let mut soc_ifc = unsafe { SocIfcReg::new() };
let mut mbox = unsafe { MboxCsr::new() };
let mbox = mbox.regs_mut();
let mut sha512acc = unsafe { Sha512AccCsr::new() };
let sha512acc = sha512acc.regs_mut();
soc_ifc
.regs_mut()
.cptra_flow_status()
.write(|w| w.ready_for_mb_processing(true));
let mut replay_buf_len = 0;
let mut replay_buf = [0u32; 2048];
loop {
while !mbox.status().read().mbox_fsm_ps().mbox_execute_uc() {
// Wait for a request from the SoC.
}
let cmd = mbox.cmd().read();
match cmd {
// Consumes input, and echoes the request back as the response with
// the command-id prepended.
0x1000_0000 => {
let dlen = mbox.dlen().read();
let dlen_words = usize::try_from((dlen + 3) / 4).unwrap();
let mut buf = [0u32; 8];
for i in 0..dlen_words {
buf[i] = mbox.dataout().read();
}
mbox.dlen().write(|_| dlen + 4);
mbox.datain().write(|_| cmd);
for i in 0..dlen_words {
mbox.datain().write(|_| buf[i]);
}
mbox.status().write(|w| w.status(|w| w.data_ready()));
}
// Returns a response of 7 hard-coded bytes; doesn't consume input.
0x1000_1000 => {
mbox.dlen().write(|_| 7);
mbox.datain().write(|_| 0x6745_2301);
mbox.datain().write(|_| 0xefcd_ab89);
mbox.status().write(|w| w.status(|w| w.data_ready()));
}
// Returns a response of 0 bytes; doesn't consume input.
0x1000_2000 => {
mbox.dlen().write(|_| 0);
mbox.status().write(|w| w.status(|w| w.data_ready()));
}
// Returns a success response; doesn't consume input.
0x2000_0000 => {
mbox.status().write(|w| w.status(|w| w.cmd_complete()));
}
// Store a buf to be returned by 0x3000_0001
0x3000_0000 => {
let dlen = mbox.dlen().read();
let dlen_words = usize::try_from((dlen + 3) / 4).unwrap();
for i in 0..usize::min(dlen_words, replay_buf.len()) {
replay_buf[i] = mbox.dataout().read();
}
replay_buf_len = u32::min(dlen, u32::try_from(replay_buf.len()).unwrap());
mbox.status().write(|w| w.status(|w| w.cmd_complete()));
}
0x3000_0001 => {
cprint!("|");
let dlen = mbox.dlen().read();
let dlen_words = usize::try_from((dlen + 3) / 4).unwrap();
for i in 0..(dlen_words) {
if i == dlen_words - 1 && dlen % 4 != 0 {
let word_bytes = mbox.dataout().read().to_le_bytes();
for byte in &word_bytes[..dlen as usize % 4] {
cprint!("{:02x}", *byte);
}
} else {
cprint!("{:08x}", mbox.dataout().read().to_be());
}
}
cprint!("|");
mbox.dlen().write(|_| replay_buf_len);
let dlen_words = usize::try_from((replay_buf_len + 3) / 4).unwrap();
for i in 0..dlen_words {
mbox.datain().write(|_| replay_buf[i]);
}
mbox.status().write(|w| w.status(|w| w.data_ready()));
}
0x5000_0000 => {
// Unlock sha512acc peripheral by writing 1
sha512acc.lock().write(|w| w.lock(true));
mbox.status().write(|w| w.status(|w| w.cmd_complete()));
}
// Everything else returns a failure response; doesn't consume input.
_ => {
mbox.status().write(|w| w.status(|w| w.cmd_failure()));
}
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_dccm_double_bit_ecc.rs | hw-model/test-fw/test_dccm_double_bit_ecc.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use ::core::arch::global_asm;
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
global_asm!(
r#"
main:
lui t0, 0x50000
li t2, 0x100
writeloop:
// Write data to DCCM t2/4 times
sw t0, 0(t0)
addi t0, t0, 4
addi t2, t2, -4
bgtz t2, writeloop
lui t0, 0x50000
li t2, 0x100
readloop:
// Read data from DCCM t2/4 times
lw a0, 0(t0)
addi t0, t0, 4
addi t2, t2, -4
bgtz t2, readloop
ret
"#
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_iccm_unaligned_write.rs | hw-model/test-fw/test_iccm_unaligned_write.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use ::core::arch::global_asm;
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
global_asm!(
r#"
main:
lui t0, 0x40000
sw x0, 1(t0)
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ret
"#
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_write_to_rom.rs | hw-model/test-fw/test_write_to_rom.rs | // Licensed under the Apache-2.0 license
//! A very simple program to test the behavior of the CPU when trying to write to ROM.
#![no_main]
#![no_std]
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness::println;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
#[no_mangle]
extern "C" fn main() {
unsafe {
let rom_address = 0x00_u32;
let rom_address_ptr = rom_address as *mut u32;
*rom_address_ptr = 0xdeadbeef;
}
loop {}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_zbb.rs | hw-model/test-fw/test_zbb.rs | // Licensed under the Apache-2.0 license
//! Basic test for the zbb extensions
#![no_main]
#![no_std]
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
use caliptra_registers::{self, soc_ifc::SocIfcReg};
use core::arch::asm;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
let mut soc_ifc = unsafe { SocIfcReg::new() };
// Exit failure
soc_ifc
.regs_mut()
.cptra_generic_output_wires()
.at(0)
.write(|_| 0x01);
loop {}
}
#[no_mangle]
extern "C" fn main() {
unsafe {
let mut rd: u32;
asm!("andn {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x958b_c66d_u32, rs2 = in(reg) 0xdd74_23f1_u32);
assert_eq!(rd, 0x008b_c40c);
asm!("orn {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x4828_aacd_u32, rs2 = in(reg) 0x702d_7829_u32);
assert_eq!(rd, 0xcffa_afdf);
asm!("xnor {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0xc9b1_ad5c_u32, rs2 = in(reg) 0x2135_163d_u32);
assert_eq!(rd, 0x177b_449e);
asm!("clz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0018_1234_u32);
assert_eq!(rd, 11);
asm!("clz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0000_u32);
assert_eq!(rd, 32);
asm!("clz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x8000_0000_u32);
assert_eq!(rd, 0);
asm!("ctz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0002_3540_u32);
assert_eq!(rd, 6);
asm!("ctz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0000_u32);
assert_eq!(rd, 32);
asm!("ctz {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0001_u32);
assert_eq!(rd, 0);
asm!("cpop {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xf832_2501_u32);
assert_eq!(rd, 12);
asm!("cpop {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0000_u32);
assert_eq!(rd, 0);
asm!("cpop {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xffff_ffff_u32);
assert_eq!(rd, 32);
asm!("max {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) -5, rs2 = in(reg) 77);
assert_eq!(rd, 77 as u32);
asm!("max {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 238123, rs2 = in(reg) 912382);
assert_eq!(rd, 912382);
asm!("max {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 912382, rs2 = in(reg) 238123);
assert_eq!(rd, 912382);
asm!("maxu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0xffff_fffb_u32, rs2 = in(reg) 0x0000_004d);
assert_eq!(rd, 0xffff_fffb);
asm!("maxu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 238123, rs2 = in(reg) 912382);
assert_eq!(rd, 912382);
asm!("maxu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 912382, rs2 = in(reg) 238123);
assert_eq!(rd, 912382);
asm!("min {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) -5, rs2 = in(reg) 77);
assert_eq!(rd, -5_i32 as u32);
asm!("min {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 238123, rs2 = in(reg) 912382);
assert_eq!(rd, 238123);
asm!("min {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 912382, rs2 = in(reg) 238123);
assert_eq!(rd, 238123);
asm!("minu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0xffff_fffb_u32, rs2 = in(reg) 0x0000_004d);
assert_eq!(rd, 0x0000_004d);
asm!("minu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 238123, rs2 = in(reg) 912382);
assert_eq!(rd, 238123);
asm!("minu {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 912382, rs2 = in(reg) 238123);
assert_eq!(rd, 238123);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x00);
assert_eq!(rd, 0x00);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x7d);
assert_eq!(rd, 0x7d);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_337d);
assert_eq!(rd, 0x7d);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x7f);
assert_eq!(rd, 0x7f);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x80);
assert_eq!(rd, 0xffff_ff80);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xae);
assert_eq!(rd, 0xffff_ffae);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xff);
assert_eq!(rd, 0xffff_ffff);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_3380);
assert_eq!(rd, 0xffff_ff80);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_33ae);
assert_eq!(rd, 0xffff_ffae);
asm!("sext.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_33ff);
assert_eq!(rd, 0xffff_ffff);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000);
assert_eq!(rd, 0x0000);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x7f);
assert_eq!(rd, 0x7f);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x7fff);
assert_eq!(rd, 0x7fff);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_7fff);
assert_eq!(rd, 0x7fff);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x8000);
assert_eq!(rd, 0xffff_8000);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xaeae);
assert_eq!(rd, 0xffff_aeae);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xffff);
assert_eq!(rd, 0xffff_ffff);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_8000);
assert_eq!(rd, 0xffff_8000);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_aeae);
assert_eq!(rd, 0xffff_aeae);
asm!("sext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_ffff);
assert_eq!(rd, 0xffff_ffff);
asm!("zext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x1122_3344);
assert_eq!(rd, 0x0000_3344);
asm!("zext.h {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xffff_ffff_u32);
assert_eq!(rd, 0x0000_ffff);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 0);
assert_eq!(rd, 0x5678_9abc);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 4);
assert_eq!(rd, 0x6789_abc5);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 12);
assert_eq!(rd, 0x89ab_c567);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 31);
assert_eq!(rd, 0x2b3c_4d5e);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 32);
assert_eq!(rd, 0x5678_9abc);
asm!("rol {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 36);
assert_eq!(rd, 0x6789_abc5);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 0);
assert_eq!(rd, 0x5678_9abc);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 4);
assert_eq!(rd, 0xc567_89ab);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 12);
assert_eq!(rd, 0xabc5_6789);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 31);
assert_eq!(rd, 0xacf1_3578);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 32);
assert_eq!(rd, 0x5678_9abc);
asm!("ror {rd}, {rs1}, {rs2}", rd = out(reg) rd, rs1 = in(reg) 0x5678_9abc, rs2 = in(reg) 36);
assert_eq!(rd, 0xc567_89ab);
asm!("rori {rd}, {rs}, 0", rd = out(reg) rd, rs = in(reg) 0x5678_9abc);
assert_eq!(rd, 0x5678_9abc);
asm!("rori {rd}, {rs}, 4", rd = out(reg) rd, rs = in(reg) 0x5678_9abc);
assert_eq!(rd, 0xc567_89ab);
asm!("rori {rd}, {rs}, 12", rd = out(reg) rd, rs = in(reg) 0x5678_9abc);
assert_eq!(rd, 0xabc5_6789);
asm!("rori {rd}, {rs}, 31", rd = out(reg) rd, rs = in(reg) 0x5678_9abc);
assert_eq!(rd, 0xacf1_3578);
asm!("orc.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0000_u32);
assert_eq!(rd, 0x0000_0000);
asm!("orc.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0000_0001_u32);
assert_eq!(rd, 0x0000_00ff);
asm!("orc.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x4000_0100_u32);
assert_eq!(rd, 0xff00_ff00);
asm!("orc.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x8044_0073_u32);
assert_eq!(rd, 0xffff_00ff);
asm!("orc.b {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x8044_0273_u32);
assert_eq!(rd, 0xffff_ffff);
asm!("rev8 {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0x0102_0304_u32);
assert_eq!(rd, 0x0403_0201);
asm!("rev8 {rd}, {rs}", rd = out(reg) rd, rs = in(reg) 0xe58d_d63f_u32);
assert_eq!(rd, 0x3fd6_8de5);
}
// Exit success
let mut soc_ifc = unsafe { SocIfcReg::new() };
soc_ifc
.regs_mut()
.cptra_generic_output_wires()
.at(0)
.write(|_| 0xff);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_uninitialized_read.rs | hw-model/test-fw/test_uninitialized_read.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use caliptra_registers::{self, mbox::MboxCsr, soc_ifc::SocIfcReg};
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
#[no_mangle]
extern "C" fn main() {
let mut mbox = unsafe { MboxCsr::new() };
let mut soc_ifc = unsafe { SocIfcReg::new() };
// To prevent a race condition, wait until the SoC has written a value to
// this register.
let size = loop {
let size = soc_ifc.regs_mut().cptra_rsvd_reg().at(1).read() as usize;
if size > 0 {
break size;
}
};
let ptr = soc_ifc.regs_mut().cptra_rsvd_reg().at(0).read() as *const u32;
// Lock the mailbox so we can access the mailbox SRAM if necessary
mbox.regs_mut().lock().read();
let mut i = 0;
while i < size / 4 {
unsafe { ptr.add(i).read_volatile() };
i += 1;
}
// Exit success
soc_ifc
.regs_mut()
.cptra_generic_output_wires()
.at(0)
.write(|_| 0xff);
loop {}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/mcu_hitless_update_flow.rs | hw-model/test-fw/mcu_hitless_update_flow.rs | // Licensed under the Apache-2.0 license
//! A very simple program that tests all of the steps in the MCU hitless update
//! flow. This needs to be paired with a test rom in the MCU repo to manipulate
//! the MCU side of the flow.
#![no_main]
#![no_std]
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
use caliptra_drivers::{Dma, DmaMmio, SocIfc};
use caliptra_registers::{self, soc_ifc::SocIfcReg};
use caliptra_test_harness::println;
use ureg::{Mmio, MmioMut};
const MCI_TOP_REG_RESET_REASON_OFFSET: u32 = 0x38;
const MCI_TOP_REG_RESET_STATUS_OFFSET: u32 = 0x3c;
const MCI_TOP_REG_MCU_SRAM_OFFSET: u32 = 0xc00000;
const FW_HITLESS_UPD_RESET: u32 = 0b1 << 0;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
caliptra_drivers::ExitCtrl::exit(1)
}
fn write_mcu_word(mmio: &DmaMmio, offset: u32, value: u32) {
unsafe {
mmio.write_volatile(offset as *mut u32, value);
}
}
fn read_mcu_word(mmio: &DmaMmio, offset: u32) -> u32 {
unsafe { mmio.read_volatile(offset as *const u32) }
}
fn write_mcu_sram_word(mmio: &DmaMmio, value: u32) {
write_mcu_word(mmio, MCI_TOP_REG_MCU_SRAM_OFFSET, value)
}
#[no_mangle]
extern "C" fn main() {
println!("[cptra] Hello from mcu_hitless_udpate_flow");
let mut soc_ifc = SocIfc::new(unsafe { SocIfcReg::new() });
let dma = Dma::default();
let mmio = &DmaMmio::new(soc_ifc.mci_base_addr().into(), &dma);
// Set known pattern in MCU SRAM
write_mcu_sram_word(mmio, u32::from_be_bytes(*b"BFOR"));
// Allow MCU to access SRAM
soc_ifc.set_mcu_firmware_ready();
soc_ifc.flow_status_set_ready_for_mb_processing();
println!("[cptra] Waiting for MCU to acknowledge firmware");
while read_mcu_word(mmio, MCI_TOP_REG_MCU_SRAM_OFFSET) != u32::from_be_bytes(*b"CONT") {}
println!("[cptra] Sending \"Hitless Update\"");
// Clear FW_EXEC_CTRL to notify MCU it has an update available
soc_ifc.set_ss_generic_fw_exec_ctrl(&[0; 4]);
// Wait for MCU reset status to be set
while read_mcu_word(mmio, MCI_TOP_REG_RESET_STATUS_OFFSET) & 0b1 << 1 == 0 {}
// Set new known pattern in MCU SRAM
write_mcu_sram_word(mmio, u32::from_be_bytes(*b"AFTR"));
// Set reset reason to hitless update
write_mcu_word(mmio, MCI_TOP_REG_RESET_REASON_OFFSET, FW_HITLESS_UPD_RESET);
// Notify MCU that hitless update is ready. Also releases MCU from reset in this case.
soc_ifc.set_mcu_firmware_ready();
println!("[cptra] Released MCU SRAM to MCU");
loop {}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_iccm_double_bit_ecc.rs | hw-model/test-fw/test_iccm_double_bit_ecc.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use ::core::arch::global_asm;
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
global_asm!(
r#"
main:
lui t0, 0x40000
lui t1, 0x40000
li t2, 0x100
// Write (nop, nop) to ICCM t2/4 times
li a0, 0x00010001
loop:
sw a0, 0(t1)
addi t1, t1, 4
addi t2, t2, -4
bgtz t2, loop
// Write (ret) to ICCM
li a0, 0x00008082
sw a0, 0(t1)
fence
// Jump to ICCM
jr t0
"#
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/build.rs | hw-model/test-fw/build.rs | // Licensed under the Apache-2.0 license
fn main() {
println!("cargo:rerun-if-changed=../../test-harness/scripts/rom.ld");
println!("cargo:rustc-link-arg=-Ttest-harness/scripts/rom.ld");
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_invalid_instruction.rs | hw-model/test-fw/test_invalid_instruction.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use ::core::arch::global_asm;
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
global_asm!(
r#"
main:
C.UNIMP
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ret
"#
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/mailbox_sender.rs | hw-model/test-fw/mailbox_sender.rs | // Licensed under the Apache-2.0 license
//! A very simple program that sends mailbox transactions.
#![no_main]
#![no_std]
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness::println;
use caliptra_registers::mbox::MboxCsr;
use caliptra_registers::soc_ifc::SocIfcReg;
use caliptra_registers::{self};
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
struct Response {
cmd: u32,
dlen: u32,
buf: &'static [u32],
}
const RESPONSES: [Response; 3] = [
Response {
cmd: 0xe000_0000,
dlen: 8,
buf: &[0x6745_2301, 0xefcd_ab89],
},
Response {
cmd: 0xe000_1000,
dlen: 3,
buf: &[0xaabbccdd],
},
Response {
cmd: 0xe000_2000,
dlen: 0,
buf: &[],
},
];
#[no_mangle]
extern "C" fn main() {
let mut soc_ifc = unsafe { SocIfcReg::new() };
let soc_ifc = soc_ifc.regs_mut();
let mut mbox = unsafe { MboxCsr::new() };
let mbox = mbox.regs_mut();
soc_ifc
.cptra_flow_status()
.write(|w| w.ready_for_mb_processing(true));
let mut response_iter = RESPONSES.iter().cycle();
loop {
soc_ifc.cptra_fw_extended_error_info().at(0).write(|_| 0);
assert!(!mbox.lock().read().lock());
let response = response_iter.next().unwrap();
mbox.cmd().write(|_| response.cmd);
mbox.dlen().write(|_| response.dlen);
for word in response.buf.iter() {
mbox.datain().write(|_| *word);
}
mbox.execute().write(|w| w.execute(true));
while mbox.status().read().status().cmd_busy() {}
let status = mbox.status().read().status();
soc_ifc
.cptra_fw_extended_error_info()
.at(1)
.write(|_| mbox.dlen().read());
soc_ifc
.cptra_fw_extended_error_info()
.at(2)
.write(|_| mbox.dataout().read());
soc_ifc
.cptra_fw_extended_error_info()
.at(3)
.write(|_| mbox.dataout().read());
soc_ifc
.cptra_fw_extended_error_info()
.at(4)
.write(|_| mbox.dataout().read());
soc_ifc
.cptra_fw_extended_error_info()
.at(0)
.write(|_| status.into());
mbox.execute().write(|w| w.execute(false));
// Wait for the "SoC" to see error_info
while soc_ifc.cptra_rsvd_reg().at(0).read() == 0 {}
soc_ifc.cptra_rsvd_reg().at(0).write(|_| 0);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_iccm_byte_write.rs | hw-model/test-fw/test_iccm_byte_write.rs | // Licensed under the Apache-2.0 license
#![no_main]
#![no_std]
use ::core::arch::global_asm;
// Needed to bring in startup code
#[allow(unused)]
use caliptra_test_harness;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
global_asm!(
r#"
main:
lui t0, 0x40000
sb x0, 0(t0)
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ret
"#
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_iccm_write_locked.rs | hw-model/test-fw/test_iccm_write_locked.rs | // Licensed under the Apache-2.0 license
//! A very simple program that sends mailbox transactions.
#![no_main]
#![no_std]
// Needed to bring in startup code
use caliptra_registers::soc_ifc::SocIfcReg;
#[allow(unused)]
use caliptra_test_harness::println;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
#[no_mangle]
extern "C" fn main() {
let mut soc_ifc = unsafe { SocIfcReg::new() };
soc_ifc
.regs_mut()
.internal_iccm_lock()
.modify(|w| w.lock(true));
unsafe {
let iccm_start = 0x40000000_u32;
let iccm_ptr = iccm_start as *mut u32;
*iccm_ptr = 0xdeadbeef;
}
loop {}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/test-fw/test_pcr_extend.rs | hw-model/test-fw/test_pcr_extend.rs | // Licensed under the Apache-2.0 license
//! A very simple program that extends to a PCR and then computes a hash.
#![no_main]
#![no_std]
use caliptra_cfi_lib::CfiCounter;
use caliptra_drivers::{Array4x12, PcrBank, PcrId, Sha2_512_384};
use caliptra_registers::{pv::PvReg, sha512::Sha512Reg};
#[allow(unused)]
use caliptra_test_harness::println;
#[panic_handler]
pub fn panic(_info: &core::panic::PanicInfo) -> ! {
caliptra_drivers::ExitCtrl::exit(1)
}
#[no_mangle]
extern "C" fn cfi_panic_handler(code: u32) -> ! {
println!("[test_pcr_extend] CFI Panic code=0x{:08X}", code);
caliptra_drivers::report_fw_error_fatal(0xdead2);
caliptra_drivers::ExitCtrl::exit(u32::MAX)
}
#[no_mangle]
extern "C" fn main() {
// Init CFI
CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef)));
let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) };
let pcr_bank = unsafe { PcrBank::new(PvReg::new()) };
pcr_bank
.extend_pcr(PcrId::PcrId1, &mut sha2, &[0_u8; 4])
.unwrap();
let pcr1 = pcr_bank.read_pcr(PcrId::PcrId1);
let expected_pcr1 = [
0x1a, 0xe0, 0x93, 0xc2, 0xc1, 0x3b, 0xbe, 0xea, 0x8a, 0xbe, 0x39, 0xe0, 0xfc, 0x3a, 0x03,
0x40, 0xbd, 0xaf, 0x0a, 0x0b, 0x55, 0xf0, 0x93, 0x61, 0x66, 0xfd, 0x32, 0x5b, 0x2d, 0x4c,
0xbf, 0x7a, 0x95, 0x25, 0xf9, 0x3a, 0x92, 0x60, 0x38, 0xf7, 0x0a, 0x1a, 0xc5, 0x7d, 0x32,
0x86, 0xff, 0xab,
];
assert_eq!(pcr1, Array4x12::from(expected_pcr1));
let digest = sha2.sha384_digest(&expected_pcr1).unwrap();
let expected_digest = [
0x5f, 0xeb, 0xea, 0xe8, 0x58, 0x75, 0x73, 0x40, 0x29, 0x58, 0xa9, 0x24, 0xba, 0x75, 0xc7,
0x50, 0x39, 0x73, 0xee, 0x94, 0x76, 0xfb, 0xac, 0xb5, 0xba, 0xfe, 0x69, 0x53, 0xbf, 0xde,
0x06, 0xa2, 0xdf, 0x89, 0x5e, 0xff, 0xd8, 0x13, 0xc5, 0x38, 0x9a, 0x4b, 0xed, 0x4b, 0x37,
0x11, 0x03, 0xc1,
];
assert_eq!(digest, Array4x12::from(expected_digest));
// Assert PCR1 is still the expected value.
let pcr1 = pcr_bank.read_pcr(PcrId::PcrId1);
assert_eq!(pcr1, Array4x12::from(expected_pcr1));
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/c-binding/build.rs | hw-model/c-binding/build.rs | // Licensed under the Apache-2.0 license
extern crate cbindgen;
use std::path::PathBuf;
use std::{env, str::FromStr};
fn main() {
// Get Crate dir
let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
// Generate Config
let config = cbindgen::Config {
header: Some(String::from_str("// Licensed under the Apache-2.0 license").unwrap()),
language: cbindgen::Language::C,
include_guard: Some("HW_MODEL_C_BINDING_OUT_CALIPTRA_MODEL_H".to_string()),
cpp_compat: true,
..Default::default()
};
// Generate Output file
let out_file = PathBuf::from(&crate_dir)
.join("out")
.join("caliptra_model.h");
// Generate caliptra_model.h
cbindgen::Builder::new()
.with_crate(crate_dir)
.with_config(config)
.generate()
.expect("Unable to generate bindings")
.write_to_file(out_file);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/c-binding/src/lib.rs | hw-model/c-binding/src/lib.rs | // Licensed under the Apache-2.0 license
pub mod caliptra_model;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/c-binding/src/caliptra_model.rs | hw-model/c-binding/src/caliptra_model.rs | // Licensed under the Apache-2.0 license
use caliptra_api::soc_mgr::SocManager;
use caliptra_cfi_lib::CfiState;
use caliptra_emu_bus::Bus;
use caliptra_emu_periph::MailboxRequester;
use caliptra_emu_types::RvSize;
use caliptra_hw_model::{DefaultHwModel, HwModel, InitParams, SecurityState};
use caliptra_hw_model_types::DEFAULT_CPTRA_OBF_KEY;
use core::mem::size_of_val;
use std::ffi::*;
use std::slice;
// These are needed if CFI is enabled.
#[no_mangle]
pub extern "C" fn cfi_panic_handler(code: u32) -> ! {
std::process::exit(code as i32);
}
#[allow(unused)]
#[no_mangle]
static mut CFI_STATE_ORG: [u8; std::mem::size_of::<CfiState>()] =
[0; std::mem::size_of::<CfiState>()];
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct caliptra_model {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct caliptra_buffer {
pub data: *const u8,
pub len: usize,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct caliptra_model_init_params {
pub rom: caliptra_buffer,
pub dccm: caliptra_buffer,
pub iccm: caliptra_buffer,
pub security_state: u8,
pub soc_user: u32,
// When data is null, DEFAULT_CPTRA_OBF_KEY is used.
pub optional_obf_key: caliptra_buffer,
}
pub const CALIPTRA_SEC_STATE_DBG_UNLOCKED_UNPROVISIONED: c_int = 0b000;
pub const CALIPTRA_SEC_STATE_DBG_LOCKED_MANUFACTURING: c_int = 0b101;
pub const CALIPTRA_SEC_STATE_DBG_UNLOCKED_PRODUCTION: c_int = 0b011;
pub const CALIPTRA_SEC_STATE_DBG_LOCKED_PRODUCTION: c_int = 0b111;
pub const CALIPTRA_MODEL_STATUS_OK: c_int = 0;
pub const CALIPTRA_MODEL_INVALID_OBF_KEY_SIZE: c_int = -1;
/// # Safety
///
/// `rom`, `dccm`, and `iccm` in `params` must be non-null. `model` must be
/// non-null.
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_init_default(
params: caliptra_model_init_params,
model: *mut *mut caliptra_model,
) -> c_int {
// Parameter check
assert!(!model.is_null());
let cptra_obf_key = if params.optional_obf_key.data.is_null() {
DEFAULT_CPTRA_OBF_KEY
} else if params.optional_obf_key.len != size_of_val(&DEFAULT_CPTRA_OBF_KEY) {
return CALIPTRA_MODEL_INVALID_OBF_KEY_SIZE;
} else {
slice::from_raw_parts(
params.optional_obf_key.data as *const u32,
params.optional_obf_key.len / 4,
)
.try_into()
.unwrap()
};
// Generate Model and cast to caliptra_model
*model = Box::into_raw(Box::new(
caliptra_hw_model::new_unbooted(InitParams {
rom: slice::from_raw_parts(params.rom.data, params.rom.len),
dccm: slice::from_raw_parts(params.dccm.data, params.dccm.len),
iccm: slice::from_raw_parts(params.iccm.data, params.iccm.len),
security_state: SecurityState::from(params.security_state as u32),
soc_user: MailboxRequester::SocUser(params.soc_user),
cptra_obf_key,
..Default::default()
})
.unwrap(),
)) as *mut caliptra_model;
CALIPTRA_MODEL_STATUS_OK
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_destroy(model: *mut caliptra_model) {
// Parameter check
assert!(!model.is_null());
// This will force model to be freed. Needs the cast to know how much memory to be freed.
drop(Box::from_raw(model as *mut DefaultHwModel));
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_apb_read_u32(
model: *mut caliptra_model,
addr: c_uint,
data: *mut c_uint,
) -> c_int {
// Parameter check
assert!(!model.is_null() || !data.is_null());
*data = (*{ model as *mut DefaultHwModel })
.apb_bus()
.read(RvSize::Word, addr)
.unwrap();
CALIPTRA_MODEL_STATUS_OK
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_apb_write_u32(
model: *mut caliptra_model,
addr: c_uint,
data: c_uint,
) -> c_int {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel })
.apb_bus()
.write(RvSize::Word, addr, data)
.unwrap();
CALIPTRA_MODEL_STATUS_OK
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_ready_for_fuses(model: *mut caliptra_model) -> bool {
// Parameter check
assert!(!model.is_null());
!(*{ model as *mut DefaultHwModel })
.soc_ifc()
.cptra_fuse_wr_done()
.read()
.done()
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_ready_for_fw(model: *mut caliptra_model) -> bool {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel }).ready_for_fw()
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_step(model: *mut caliptra_model) -> c_int {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel }).step();
CALIPTRA_MODEL_STATUS_OK
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_exit_requested(model: *mut caliptra_model) -> bool {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel })
.output()
.exit_requested()
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_output_peek(model: *mut caliptra_model) -> caliptra_buffer {
// Parameter check
assert!(!model.is_null());
let peek_str = (*{ model as *mut DefaultHwModel }).output().peek();
caliptra_buffer {
data: peek_str.as_ptr(),
len: peek_str.len(),
}
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_step_until_boot_status(
model: *mut caliptra_model,
boot_status: c_uint,
) {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel }).step_until_boot_status(boot_status, true);
}
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn caliptra_model_set_axi_user(model: *mut caliptra_model, pauser: c_uint) {
// Parameter check
assert!(!model.is_null());
(*{ model as *mut DefaultHwModel }).set_axi_user(pauser);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/hw-model/types/src/lib.rs | hw-model/types/src/lib.rs | // Licensed under the Apache-2.0 license
use caliptra_api_types::{self};
use std::array;
pub use caliptra_api_types::DeviceLifecycle;
use rand::{
rngs::{StdRng, ThreadRng},
RngCore, SeedableRng,
};
// Rationale behind this choice
//
// * The constant should be easily recognizable in waveforms and debug logs
// * Every word must be different to ensure that a "stuck word" bug is noticed.
// * Each byte in a word must be unique to ensure an endianness bug is noticed.
pub const DEFAULT_UDS_SEED: [u32; 16] = [
0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f,
0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f,
];
pub const DEFAULT_FIELD_ENTROPY: [u32; 8] = [
0x80818283, 0x84858687, 0x88898a8b, 0x8c8d8e8f, 0x90919293, 0x94959697, 0x98999a9b, 0x9c9d9e9f,
];
pub const DEFAULT_CPTRA_OBF_KEY: [u32; 8] = [
0xa0a1a2a3, 0xb0b1b2b3, 0xc0c1c2c3, 0xd0d1d2d3, 0xe0e1e2e3, 0xf0f1f2f3, 0xa4a5a6a7, 0xb4b5b6b7,
];
pub const DEFAULT_CSR_HMAC_KEY: [u32; 16] = [
0x14552AD, 0x19550757, 0x50C602DD, 0x85DE4E9B, 0x815CC9EF, 0xBA81A35, 0x7A05D7C0, 0x7F5EFAEB,
0xF76DD9D2, 0x9E38197F, 0x4052537, 0x25B568F4, 0x432665F1, 0xD11D02A7, 0xBFB9279F, 0xA2EB96D7,
];
pub const DEFAULT_MANUF_DEBUG_UNLOCK_TOKEN: [u32; 8] = [
0x552c92d8, 0x7f732b79, 0xe5f31329, 0x7554e6cb, 0x6e015262, 0xa163e9ae, 0x3a754edd, 0x96f087f7,
];
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum U4 {
#[default]
X0 = 0x0,
X1 = 0x1,
X2 = 0x2,
X3 = 0x3,
X4 = 0x4,
X5 = 0x5,
X6 = 0x6,
X7 = 0x7,
X8 = 0x8,
X9 = 0x9,
Xa = 0xa,
Xb = 0xb,
Xc = 0xc,
Xd = 0xd,
Xe = 0xe,
Xf = 0xf,
}
impl U4 {
pub const B0000: Self = Self::X0;
pub const B0001: Self = Self::X1;
pub const B0010: Self = Self::X2;
pub const B0011: Self = Self::X3;
pub const B0100: Self = Self::X4;
pub const B0101: Self = Self::X5;
pub const B0110: Self = Self::X6;
pub const B0111: Self = Self::X7;
pub const B1000: Self = Self::X8;
pub const B1001: Self = Self::X9;
pub const B1010: Self = Self::Xa;
pub const B1011: Self = Self::Xb;
pub const B1100: Self = Self::Xc;
pub const B1101: Self = Self::Xd;
pub const B1110: Self = Self::Xe;
pub const B1111: Self = Self::Xf;
}
impl From<U4> for u32 {
fn from(value: U4) -> Self {
value as u32
}
}
impl TryFrom<u32> for U4 {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0b0000 => Ok(Self::X0),
0b0001 => Ok(Self::X1),
0b0010 => Ok(Self::X2),
0b0011 => Ok(Self::X3),
0b0100 => Ok(Self::X4),
0b0101 => Ok(Self::X5),
0b0110 => Ok(Self::X6),
0b0111 => Ok(Self::X7),
0b1000 => Ok(Self::X8),
0b1001 => Ok(Self::X9),
0b1010 => Ok(Self::Xa),
0b1011 => Ok(Self::Xb),
0b1100 => Ok(Self::Xc),
0b1101 => Ok(Self::Xd),
0b1110 => Ok(Self::Xe),
0b1111 => Ok(Self::Xf),
16_u32..=u32::MAX => Err(()),
}
}
}
pub struct HexSlice<'a, T: std::fmt::LowerHex + PartialEq>(pub &'a [T]);
impl<T: std::fmt::LowerHex + PartialEq> std::fmt::Debug for HexSlice<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let width = std::mem::size_of::<T>() * 2 + 2;
if self.0.len() > 1 && self.0.iter().all(|item| item == &self.0[0]) {
write!(f, "[{:#0width$x}; {}]", self.0[0], self.0.len())?;
return Ok(());
}
write!(f, "[")?;
for (i, val) in self.0.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{:#0width$x}", val)?;
}
write!(f, "]")?;
Ok(())
}
}
pub struct HexBytes<'a>(pub &'a [u8]);
impl std::fmt::Debug for HexBytes<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "\"")?;
for val in self.0.iter() {
write!(f, "{val:02x}")?;
}
write!(f, "\"")?;
Ok(())
}
}
pub struct RandomNibbles<R: RngCore>(pub R);
impl RandomNibbles<ThreadRng> {
pub fn new_from_thread_rng() -> Self {
Self(rand::thread_rng())
}
}
impl<R: RngCore> Iterator for RandomNibbles<R> {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
Some((self.0.next_u32() & 0xf) as u8)
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct EtrngResponse {
pub delay: u32,
pub data: [u32; 12],
}
pub struct RandomEtrngResponses<R: RngCore>(pub R);
impl RandomEtrngResponses<StdRng> {
pub fn new_from_stdrng() -> Self {
Self(StdRng::from_entropy())
}
}
impl<R: RngCore> Iterator for RandomEtrngResponses<R> {
type Item = EtrngResponse;
fn next(&mut self) -> Option<Self::Item> {
Some(EtrngResponse {
delay: 0,
data: array::from_fn(|_| self.0.next_u32()),
})
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum ErrorInjectionMode {
#[default]
None,
IccmDoubleBitEcc,
DccmDoubleBitEcc,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_hex_bytes() {
assert_eq!("\"\"", format!("{:?}", HexBytes(&[])));
assert_eq!("\"ab1f\"", format!("{:?}", HexBytes(&[0xab, 0x1f])))
}
#[test]
fn test_hex_slice() {
assert_eq!("[]", format!("{:?}", HexSlice(&[0_u8; 0])));
assert_eq!("[]", format!("{:?}", HexSlice(&[0_u16; 0])));
assert_eq!("[]", format!("{:?}", HexSlice(&[0_u32; 0])));
assert_eq!("[0x84]", format!("{:?}", HexSlice(&[0x84_u8])));
assert_eq!("[0x7c63]", format!("{:?}", HexSlice(&[0x7c63_u16])));
assert_eq!("[0x47dbaa30]", format!("{:?}", HexSlice(&[0x47dbaa30_u32])));
assert_eq!(
"[0x97f48c6bf52f06bb]",
format!("{:?}", HexSlice(&[0x97f48c6bf52f06bb_u64]))
);
assert_eq!("[0x00; 32]", format!("{:?}", HexSlice(&[0x00_u8; 32])));
assert_eq!("[0x7c63; 32]", format!("{:?}", HexSlice(&[0x7c63_u16; 32])));
assert_eq!(
"[0x47dbaa30; 32]",
format!("{:?}", HexSlice(&[0x47dbaa30_u32; 32]))
);
assert_eq!(
"[0x97f48c6bf52f06bb; 32]",
format!("{:?}", HexSlice(&[0x97f48c6bf52f06bb_u64; 32]))
);
assert_eq!("[0xab, 0x1f]", format!("{:?}", HexSlice(&[0xab_u8, 0x1f])));
assert_eq!(
"[0x00ab, 0x001f]",
format!("{:?}", HexSlice(&[0xab_u16, 0x1f]))
);
assert_eq!(
"[0x000000ab, 0x0000001f]",
format!("{:?}", HexSlice(&[0xab_u32, 0x1f]))
);
assert_eq!(
"[0x00000000000000ab, 0x000000000000001f]",
format!("{:?}", HexSlice(&[0xab_u64, 0x1f]))
);
assert_eq!(
"[0x0b, 0x2a, 0x40]",
format!("{:?}", HexSlice(&[0x0b_u8, 0x2a, 0x40]))
);
assert_eq!(
"[0xad83, 0xa91f, 0x9c8b]",
format!("{:?}", HexSlice(&[0xad83_u16, 0xa91f, 0x9c8b]))
);
assert_eq!(
"[0xde85388f, 0xda448d4c, 0x329c1f58]",
format!("{:?}", HexSlice(&[0xde85388f_u32, 0xda448d4c, 0x329c1f58]))
);
assert_eq!(
"[0x8ab6401e7f681569, 0xc60f65a019714215, 0xbc24d103aeecad40]",
format!(
"{:?}",
HexSlice(&[
0x8ab6401e7f681569_u64,
0xc60f65a019714215,
0xbc24d103aeecad40
])
)
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/lexer.rs | systemrdl/src/lexer.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::str::{Chars, FromStr};
use crate::{token::Token, Bits};
pub type Span = std::ops::Range<usize>;
pub struct Lexer<'a> {
start_ptr: *const u8,
token_start_ptr: *const u8,
iter: std::str::Chars<'a>,
}
impl<'a> Lexer<'a> {
pub fn new(s: &'a str) -> Self {
Self {
start_ptr: s.as_bytes().as_ptr(),
token_start_ptr: s.as_bytes().as_ptr(),
iter: s.chars(),
}
}
pub fn span(&self) -> Span {
Span {
start: self.token_start_ptr as usize - self.start_ptr as usize,
end: self.iter.as_str().as_ptr() as usize - self.start_ptr as usize,
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = Token<'a>;
fn next(&mut self) -> Option<Token<'a>> {
let mut iter = self.iter.clone();
loop {
let result = match iter.next() {
Some(' ' | '\t' | '\n' | '\r') => Some(Token::Skip),
Some('/') => {
match iter.next() {
Some('*') => {
// skip comments
loop {
match iter.next() {
Some('*') => match iter.next() {
Some('/') => break Some(Token::Skip),
Some(_) => continue,
None => break Some(Token::Error),
},
Some(_) => continue,
None => break Some(Token::Error),
}
}
}
Some('/') => loop {
match iter.next() {
Some('\n') => break Some(Token::Skip),
Some(_) => continue,
None => break None,
}
},
_ => Some(Token::Error),
}
}
Some('"') => loop {
match iter.next() {
Some('"') => {
break Some(Token::StringLiteral(str_between(&self.iter, &iter)))
}
Some('\\') => match iter.next() {
Some(_) => continue,
None => break Some(Token::Error),
},
Some(_) => continue,
None => break Some(Token::Error),
}
},
Some(ch) if ch.is_ascii_alphabetic() || ch == '_' => {
next_while(&mut iter, |ch| ch.is_ascii_alphanumeric() || ch == '_');
match str_between(&self.iter, &iter) {
"field" => Some(Token::Field),
"external" => Some(Token::External),
"reg" => Some(Token::Reg),
"regfile" => Some(Token::RegFile),
"addrmap" => Some(Token::AddrMap),
"signal" => Some(Token::Signal),
"enum" => Some(Token::Enum),
"mem" => Some(Token::Mem),
"constraint" => Some(Token::Constraint),
ident => Some(Token::Identifier(ident)),
}
}
Some(ch) if ch.is_ascii_digit() => {
if ch == '0' && iter.peek() == Some('x') {
iter.next();
let num_start = iter.clone();
next_while(&mut iter, |ch| ch.is_ascii_hexdigit() || ch == '_');
Some(parse_num(str_between(&num_start, &iter), 16))
} else {
next_while(&mut iter, |ch| ch.is_ascii_digit() || ch == '_');
let mut peek = iter.clone();
if let Some('\'') = peek.next() {
iter = peek;
next_while(&mut iter, |ch| {
ch == 'b' || ch == 'o' || ch == 'd' || ch == 'h'
});
next_while(&mut iter, |ch| ch.is_ascii_hexdigit() || ch == '_');
match Bits::from_str(str_between(&self.iter, &iter)) {
Ok(bits) => Some(Token::Bits(bits)),
Err(_) => Some(Token::Error),
}
} else {
Some(parse_num(str_between(&self.iter, &iter), 10))
}
}
}
Some('!') => match iter.next() {
Some('=') => Some(Token::NotEquals),
_ => Some(Token::Error),
},
Some('&') => match iter.next() {
Some('&') => Some(Token::And),
_ => Some(Token::Error),
},
Some('{') => Some(Token::BraceOpen),
Some('}') => Some(Token::BraceClose),
Some('[') => Some(Token::BracketOpen),
Some(']') => Some(Token::BracketClose),
Some('(') => Some(Token::ParenOpen),
Some(')') => Some(Token::ParenClose),
Some(';') => Some(Token::Semicolon),
Some(',') => Some(Token::Comma),
Some('.') => Some(Token::Period),
Some('=') => Some(Token::Equals),
Some('@') => Some(Token::At),
Some('#') => Some(Token::Hash),
Some(':') => Some(Token::Colon),
Some('?') => Some(Token::QuestionMark),
Some('`') => {
let keyword_start = iter.clone();
next_while(&mut iter, |ch| ch.is_ascii_alphabetic() || ch == '_');
match str_between(&keyword_start, &iter) {
"include" => Some(Token::PreprocInclude),
_ => Some(Token::Error),
}
}
Some('+') => match iter.next() {
Some('=') => Some(Token::PlusEqual),
_ => return Some(Token::Error),
},
Some('%') => match iter.next() {
Some('=') => Some(Token::PercentEqual),
_ => Some(Token::Error),
},
Some('-') => match iter.next() {
Some('>') => Some(Token::Pointer),
_ => Some(Token::Error),
},
None => None,
_ => Some(Token::Error),
};
match result {
Some(Token::Skip) => {
self.iter = iter.clone();
continue;
}
Some(token) => {
self.token_start_ptr = self.iter.as_str().as_ptr();
self.iter = iter;
return Some(token);
}
None => return None,
}
}
}
}
fn next_while(iter: &mut Chars, mut f: impl FnMut(char) -> bool) {
loop {
let mut peek = iter.clone();
if let Some(ch) = peek.next() {
if f(ch) {
*iter = peek;
continue;
} else {
break;
}
} else {
break;
}
}
}
fn parse_num(s: &str, radix: u32) -> Token {
let replaced;
let s = if s.contains('_') {
replaced = s.replace('_', "");
&replaced
} else {
s
};
if let Ok(val) = u64::from_str_radix(s, radix) {
Token::Number(val)
} else {
Token::Error
}
}
trait PeekableChar {
fn peek(&self) -> Option<char>;
}
impl PeekableChar for std::str::Chars<'_> {
fn peek(&self) -> Option<char> {
self.clone().next()
}
}
fn str_between<'a>(start: &Chars<'a>, end: &Chars<'a>) -> &'a str {
let first_ptr = start.as_str().as_ptr();
let second_ptr = end.as_str().as_ptr();
&start.as_str()[0..second_ptr as usize - first_ptr as usize]
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_foo() {
let tokens: Vec<Token> = Lexer::new("!= && ? __id external field 35\tiDentifier2_ 0x24\n\r 0xf00_bad 100_200 2'b01 5'o27 4'd9 16'h1caf 32'h3CAB_FFB0 /* ignore comment */ %= // line comment\n += \"string 1\" \"string\\\"2\" {}[]();:,.=@#reg field regfile addrmap signal enum mem constraint").take(42).collect();
assert_eq!(
tokens,
vec![
Token::NotEquals,
Token::And,
Token::QuestionMark,
Token::Identifier("__id"),
Token::External,
Token::Field,
Token::Number(35),
Token::Identifier("iDentifier2_"),
Token::Number(0x24),
Token::Number(0xf00bad),
Token::Number(100_200),
Token::Bits(Bits::new(2, 1)),
Token::Bits(Bits::new(5, 0o27)),
Token::Bits(Bits::new(4, 9)),
Token::Bits(Bits::new(16, 0x1caf)),
Token::Bits(Bits::new(32, 0x3cab_ffb0)),
Token::PercentEqual,
Token::PlusEqual,
Token::StringLiteral("\"string 1\""),
Token::StringLiteral("\"string\\\"2\""),
Token::BraceOpen,
Token::BraceClose,
Token::BracketOpen,
Token::BracketClose,
Token::ParenOpen,
Token::ParenClose,
Token::Semicolon,
Token::Colon,
Token::Comma,
Token::Period,
Token::Equals,
Token::At,
Token::Hash,
Token::Reg,
Token::Field,
Token::RegFile,
Token::AddrMap,
Token::Signal,
Token::Enum,
Token::Mem,
Token::Constraint,
]
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/lib.rs | systemrdl/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
--*/
//! General-purpose parser for systemrdl files.
//!
//! Not yet implemented:
//! - dynamic assignment
//! - instance parameters
//!
//! Examples
//!
//! ```no_run
//! use caliptra_systemrdl::{ComponentType, EnumReference, FileSource, FsFileSource, InstanceRef, Scope, ScopeType};
//!
//! let fs = FsFileSource::new();
//! let scope = Scope::parse_root(&fs, &["/tmp/foo.rdl".into()]).unwrap();
//! let parent = scope.as_parent();
//!
//! let clp = parent.lookup_typedef("clp").unwrap();
//! for iref in clp.instance_iter() {
//! print_instance(iref, "");
//! }
//!
//! fn print_instance(iref: InstanceRef, padding: &str) {
//! let inst = iref.instance;
//! match inst.scope.ty {
//! ScopeType::Component(ComponentType::Field) => {
//! println!("{}{}: field {}", padding, inst.offset.unwrap(), inst.name);
//! if let Ok(Some(EnumReference(eref))) = inst.scope.property_val_opt("encode") {
//! if let Some(enm) = iref.scope.lookup_typedef(&eref) {
//! println!("{} enum {}", padding, eref);
//! for variant in enm.instance_iter() {
//! print_instance(variant, &format!("{padding} "));
//! }
//! }
//! }
//! }
//! ScopeType::Component(ComponentType::Reg) => {
//! println!("{}{:#x?}: reg {}", padding, inst.offset.unwrap(), inst.name);
//! }
//! ScopeType::Component(ComponentType::RegFile) => {
//! println!("{}{:x?}: regfile {}", padding, inst.offset.unwrap(), inst.name);
//! }
//! ScopeType::Component(ComponentType::AddrMap) => {
//! println!("{}{:#x?}: addrmap {}", padding, inst.offset.unwrap(), inst.name);
//! }
//! ScopeType::Component(ComponentType::EnumVariant) => {
//! println!("{}{}: variant {}", padding, inst.reset.as_ref().unwrap().val(), inst.name);
//! }
//! _ => {}
//! }
//! for sub_inst in iref.scope.instance_iter() {
//! print_instance(sub_inst, &format!("{padding} "));
//! }
//! }
//!
//! ```
//!
mod bits;
mod component_meta;
mod error;
mod file_source;
mod lexer;
mod scope;
mod string_arena;
mod token;
mod token_iter;
mod value;
use lexer::Span;
pub use scope::Scope;
pub use value::Value;
pub use error::RdlError;
pub use file_source::{FileSource, FsFileSource};
pub use scope::{Instance, InstanceRef, ParentScope};
pub use value::AccessType;
pub use value::AddressingType;
pub use value::ComponentType;
pub use value::EnumReference;
pub use value::ScopeType;
pub use crate::bits::Bits;
use std::fmt::{Debug, Display};
use std::path::Path;
use std::path::PathBuf;
pub type Result<'a, T> = std::result::Result<T, RdlError<'a>>;
#[derive(Debug)]
pub struct FileLocation<'a> {
line: usize,
column: usize,
line_val: &'a str,
}
#[derive(Debug)]
pub enum FileParseError<'a> {
Parse(ParseError<'a>),
Io(std::io::Error),
CouldNotCalculateOffsets,
}
pub struct ParseError<'a> {
file_id: PathBuf,
file_text: &'a str,
span: Span,
pub error: RdlError<'a>,
}
impl<'a> ParseError<'a> {
fn new(file_id: &Path, file_text: &'a str, mut span: Span, error: RdlError<'a>) -> Self {
span.start = Ord::min(file_text.len(), span.start);
span.end = Ord::min(file_text.len(), span.end);
Self {
file_id: file_id.into(),
file_text,
span,
error,
}
}
pub fn location(&self) -> FileLocation {
let mut line = 1;
let mut column = 1;
let mut line_start: &str = self.file_text;
for (offset, ch) in self.file_text.as_bytes()[0..self.span.start]
.iter()
.enumerate()
{
if *ch == b'\n' {
line += 1;
column = 1;
line_start = &self.file_text[offset + 1..];
} else {
column += 1;
}
}
FileLocation {
line,
column,
line_val: line_start.lines().next().unwrap(),
}
}
}
impl Debug for ParseError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FileParseError")
.field("span", &self.span)
.field("error", &self.error)
.field("location", &self.location())
.finish()
}
}
impl Display for ParseError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let location = self.location();
writeln!(
f,
"At {:?} line {} column {}, {}:",
self.file_id, location.line, location.column, self.error
)?;
writeln!(f, " {}", location.line_val)?;
write!(f, " {}^", " ".repeat(location.column - 1))
}
}
impl Display for FileParseError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FileParseError::Parse(e) => Display::fmt(e, f),
FileParseError::Io(e) => Display::fmt(e, f),
FileParseError::CouldNotCalculateOffsets => write!(f, "Could not calculate offsets"),
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/value.rs | systemrdl/src/value.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use crate::{
scope::{lookup_parameter_of_type, ParameterScope},
token::Token,
token_iter::TokenIter,
Bits, RdlError, Result,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Value {
U64(u64),
Bool(bool),
Bits(Bits),
String(String),
EnumReference(String),
Reference(Reference),
PrecedenceType(PrecedenceType),
AccessType(AccessType),
OnReadType(OnReadType),
OnWriteType(OnWriteType),
AddressingType(AddressingType),
InterruptType(InterruptType),
}
impl Value {
pub fn property_type(&self) -> PropertyType {
match self {
Value::U64(_) => PropertyType::U64,
Value::Bool(_) => PropertyType::Boolean,
Value::Bits(_) => PropertyType::Bits,
Value::String(_) => PropertyType::String,
Value::EnumReference(_) => PropertyType::EnumReference,
Value::Reference(_) => PropertyType::Reference,
Value::PrecedenceType(_) => PropertyType::PrecedenceType,
Value::AccessType(_) => PropertyType::AccessType,
Value::OnReadType(_) => PropertyType::OnReadType,
Value::OnWriteType(_) => PropertyType::OnWriteType,
Value::AddressingType(_) => PropertyType::AddressingType,
Value::InterruptType(_) => PropertyType::FieldInterrupt,
}
}
}
impl From<u64> for Value {
fn from(val: u64) -> Self {
Value::U64(val)
}
}
impl From<bool> for Value {
fn from(val: bool) -> Self {
Value::Bool(val)
}
}
impl From<Bits> for Value {
fn from(val: Bits) -> Self {
Value::Bits(val)
}
}
impl From<String> for Value {
fn from(val: String) -> Self {
Value::String(val)
}
}
impl From<EnumReference> for Value {
fn from(val: EnumReference) -> Self {
Value::EnumReference(val.0)
}
}
impl From<&str> for Value {
fn from(val: &str) -> Self {
Value::String(val.into())
}
}
impl From<Reference> for Value {
fn from(val: Reference) -> Self {
Value::Reference(val)
}
}
impl From<PrecedenceType> for Value {
fn from(val: PrecedenceType) -> Self {
Value::PrecedenceType(val)
}
}
impl From<AccessType> for Value {
fn from(val: AccessType) -> Self {
Value::AccessType(val)
}
}
impl From<OnReadType> for Value {
fn from(val: OnReadType) -> Self {
Value::OnReadType(val)
}
}
impl From<OnWriteType> for Value {
fn from(val: OnWriteType) -> Self {
Value::OnWriteType(val)
}
}
impl From<AddressingType> for Value {
fn from(val: AddressingType) -> Self {
Value::AddressingType(val)
}
}
impl From<InterruptType> for Value {
fn from(val: InterruptType) -> Self {
Value::InterruptType(val)
}
}
impl TryFrom<Value> for u64 {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::U64(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::U64,
value,
}),
}
}
}
impl TryFrom<Value> for bool {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::Bool(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Boolean,
value,
}),
}
}
}
impl TryFrom<Value> for Bits {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::Bits(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Bits,
value,
}),
}
}
}
impl TryFrom<Value> for String {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::String(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::String,
value,
}),
}
}
}
impl TryFrom<Value> for EnumReference {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::EnumReference(value) => Ok(EnumReference(value)),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::String,
value,
}),
}
}
}
impl TryFrom<Value> for AddressingType {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::AddressingType(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::AddressingType,
value,
}),
}
}
}
impl TryFrom<Value> for AccessType {
type Error = RdlError<'static>;
fn try_from(value: Value) -> Result<'static, Self> {
match value {
Value::AccessType(value) => Ok(value),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::AccessType,
value,
}),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Reference {
path: Vec<String>,
property: Option<String>,
}
impl Reference {
pub fn new(path: Vec<String>) -> Self {
Self {
path,
property: None,
}
}
pub fn parse<'a>(tokens: &mut TokenIter<'a>) -> Result<'a, Self> {
let mut path = vec![];
loop {
path.push(tokens.expect_identifier()?.to_string());
if *tokens.peek(0) != Token::Period {
break;
}
tokens.next();
}
let property = if *tokens.peek(0) == Token::Pointer {
tokens.next();
Some(tokens.expect_identifier()?.to_string())
} else {
None
};
Ok(Self { path, property })
}
}
pub struct EnumReference(pub String);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrecedenceType {
Hw,
Sw,
}
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq)]
pub enum AccessType {
#[default]
Rw,
R,
W,
Rw1,
W1,
Na,
}
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnReadType {
RClr,
RSet,
RUser,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnWriteType {
WoSet,
WoClr,
Wot,
Wzs,
Wzc,
Wzt,
WClr,
WSet,
WUser,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AddressingType {
Compact,
RegAlign,
FullAlign,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum InterruptType {
#[default]
Level,
PosEdge,
NegEdge,
BothEdge,
NonSticky,
Sticky,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ComponentType {
Field,
Reg,
RegFile,
AddrMap,
Signal,
Enum,
EnumVariant,
Mem,
Constraint,
}
impl From<ComponentType> for ScopeType {
fn from(ty: ComponentType) -> Self {
ScopeType::Component(ty)
}
}
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq)]
pub enum ScopeType {
#[default]
Root,
Component(ComponentType),
}
pub fn parse_str_literal(s: &str) -> Result<String> {
if s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') {
return Err(RdlError::BadStringLiteral);
}
Ok(s[1..s.len() - 1]
.replace("\\\"", "\"")
.replace("\\\\", "\\"))
}
fn to_bool<'a>(v: Value, parameters: Option<&'_ ParameterScope<'_>>) -> Result<'a, bool> {
match v {
Value::Bool(b) => Ok(b),
Value::Reference(r) => {
let r = r.path[0].clone();
match lookup_parameter_of_type(parameters, &r, PropertyType::Boolean) {
Ok(Value::Bool(b)) => Ok(*b),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Boolean,
value: Value::Bool(false),
}),
}
}
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Boolean,
value: v,
}),
}
}
fn to_bit<'a>(v: Value, parameters: Option<&'_ ParameterScope<'_>>) -> Result<'a, Bits> {
match v {
Value::Bits(b) => Ok(b),
Value::Reference(r) => {
let r = r.path[0].clone();
match lookup_parameter_of_type(parameters, &r, PropertyType::Bits) {
Ok(Value::Bits(b)) => Ok(*b),
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Bits,
value: Value::Bool(false),
}),
}
}
_ => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Bits,
value: v,
}),
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PropertyType {
U64,
Bits,
Boolean,
BooleanOrReference,
BitOrReference,
EnumReference,
// has posedge | negedge | bothedge | level | nonsticky modifiers
FieldInterrupt,
PrecedenceType,
String,
AccessType,
Reference,
OnReadType,
OnWriteType,
AddressingType,
}
impl PropertyType {
pub fn parse_type<'a>(tokens: &mut TokenIter<'a>) -> Result<'a, PropertyType> {
match tokens.next() {
Token::Identifier("boolean") => Ok(PropertyType::Boolean),
Token::Identifier("string") => Ok(PropertyType::String),
Token::Identifier("bit") => Ok(PropertyType::Bits),
Token::Identifier("longint") => {
tokens.expect(Token::Identifier("unsigned"))?;
Ok(PropertyType::U64)
}
Token::Identifier("accesstype") => Ok(PropertyType::AccessType),
Token::Identifier("addressingtype") => Ok(PropertyType::AddressingType),
Token::Identifier("onreadtype") => Ok(PropertyType::OnReadType),
Token::Identifier("onwritetype") => Ok(PropertyType::OnWriteType),
Token::Identifier("precedencetype") => Ok(PropertyType::PrecedenceType),
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
}
}
/// Special case expression parser and evaluator that only supports singleton, ternary, &&, and != expressions.
pub fn eval<'a>(
self,
tokens: &mut TokenIter<'a>,
parameters: Option<&'_ ParameterScope<'_>>,
) -> Result<'a, Value> {
let first = tokens.peek(0).clone();
if *tokens.peek(1) == Token::NotEquals {
match self {
PropertyType::BitOrReference => {}
_ => {
return Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Boolean,
value: self.parse_or_lookup(tokens, parameters)?,
})
}
}
let a = to_bit(self.parse_or_lookup(tokens, parameters)?, parameters)?;
tokens.expect(Token::NotEquals)?;
let b = to_bit(self.parse_or_lookup(tokens, parameters)?, parameters)?;
Ok(Value::Bool(a != b))
} else if *tokens.peek(1) == Token::And {
match self {
PropertyType::Boolean => {}
PropertyType::BitOrReference => {}
_ => {
return Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::Boolean,
value: self.parse_or_lookup(tokens, parameters)?,
})
}
}
let a = to_bool(self.parse_or_lookup(tokens, parameters)?, parameters)?;
tokens.expect(Token::And)?;
let b = to_bool(self.parse_or_lookup(tokens, parameters)?, parameters)?;
Ok(Value::Bool(a && b))
} else if *tokens.peek(1) == Token::QuestionMark && *tokens.peek(3) == Token::Colon {
tokens.next();
tokens.next();
let name = match first {
Token::Identifier(name) => name,
_ => Err(RdlError::BadTernaryExpression(format!(
"Expected identifier but got {:?}",
first
)))?,
};
let cond = lookup_parameter_of_type(parameters, name, PropertyType::Boolean)?;
match cond {
Value::Bool(true) => {
let ret = self.parse_or_lookup(tokens, parameters);
tokens.expect(Token::Colon)?;
tokens.next();
ret
}
Value::Bool(false) => {
tokens.next();
tokens.expect(Token::Colon)?;
let ret = self.parse_or_lookup(tokens, parameters);
ret
}
_ => Err(RdlError::BadTernaryExpression(format!(
"Expected boolean but got {:?}",
name
)))?,
}
} else {
self.parse_or_lookup(tokens, parameters)
}
}
pub fn parse_or_lookup<'a>(
self,
tokens: &mut TokenIter<'a>,
parameters: Option<&'_ ParameterScope<'_>>,
) -> Result<'a, Value> {
match self {
PropertyType::U64 => match tokens.next() {
Token::Number(val) => Ok(val.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::Bits => match tokens.next() {
Token::Bits(val) => Ok(val.into()),
Token::Number(val) => Ok(val.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::Boolean => match tokens.next() {
Token::Number(0) => Ok(false.into()),
Token::Number(1) => Ok(true.into()),
Token::Identifier("false") => Ok(false.into()),
Token::Identifier("true") => Ok(true.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::String => Ok(parse_str_literal(tokens.expect_string()?)?.into()),
PropertyType::Reference => Ok(Reference::parse(tokens)?.into()),
PropertyType::AccessType => match tokens.next() {
Token::Identifier("na") => Ok(AccessType::Na.into()),
Token::Identifier("r") => Ok(AccessType::R.into()),
Token::Identifier("rw") => Ok(AccessType::Rw.into()),
Token::Identifier("rw1") => Ok(AccessType::Rw1.into()),
Token::Identifier("w") => Ok(AccessType::W.into()),
Token::Identifier("w1") => Ok(AccessType::W1.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::OnReadType => match tokens.next() {
Token::Identifier("rclr") => Ok(OnReadType::RClr.into()),
Token::Identifier("rset") => Ok(OnReadType::RSet.into()),
Token::Identifier("ruser") => Ok(OnReadType::RUser.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::OnWriteType => match tokens.next() {
Token::Identifier("woset") => Ok(OnWriteType::WoSet.into()),
Token::Identifier("woclr") => Ok(OnWriteType::WoClr.into()),
Token::Identifier("wot") => Ok(OnWriteType::Wot.into()),
Token::Identifier("wzs") => Ok(OnWriteType::Wzs.into()),
Token::Identifier("wzc") => Ok(OnWriteType::Wzc.into()),
Token::Identifier("wzt") => Ok(OnWriteType::Wzt.into()),
Token::Identifier("wclr") => Ok(OnWriteType::WClr.into()),
Token::Identifier("wset") => Ok(OnWriteType::WSet.into()),
Token::Identifier("wuser") => Ok(OnWriteType::WUser.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::AddressingType => match tokens.next() {
Token::Identifier("compact") => Ok(AddressingType::Compact.into()),
Token::Identifier("fullalign") => Ok(AddressingType::FullAlign.into()),
Token::Identifier("regalign") => Ok(AddressingType::RegAlign.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
PropertyType::BooleanOrReference => match tokens.peek(0) {
Token::Identifier(_) => PropertyType::Reference.parse_or_lookup(tokens, parameters),
_ => PropertyType::Boolean.parse_or_lookup(tokens, parameters),
},
PropertyType::BitOrReference => match tokens.peek(0) {
Token::Identifier(_) => PropertyType::Reference.parse_or_lookup(tokens, parameters),
Token::Number(_) => PropertyType::U64.parse_or_lookup(tokens, parameters),
_ => PropertyType::Bits.parse_or_lookup(tokens, parameters),
},
PropertyType::EnumReference => {
let ident = tokens.expect_identifier()?;
// TODO: ensure that enum exists?
Ok(Value::EnumReference(ident.into()))
}
PropertyType::FieldInterrupt => todo!(),
PropertyType::PrecedenceType => match tokens.next() {
Token::Identifier("hw") => Ok(PrecedenceType::Hw.into()),
Token::Identifier("sw") => Ok(PrecedenceType::Sw.into()),
Token::Identifier(ident) => {
Ok(lookup_parameter_of_type(parameters, ident, self)?.clone())
}
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
},
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/bits.rs | systemrdl/src/bits.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::{fmt::Display, str::FromStr};
fn mask(w: u64) -> Result<u64, ()> {
if w > 64 {
return Err(());
}
if w == 64 {
return Ok(0xffff_ffff_ffff_ffff);
}
Ok((1 << w) - 1)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Bits {
w: u64,
val: u64,
}
impl Bits {
pub fn new(w: u64, val: u64) -> Bits {
let mask = if w < 64 {
(1 << w) - 1
} else {
0xffff_ffff_ffff_ffff
};
Self { w, val: val & mask }
}
pub fn w(&self) -> u64 {
self.w
}
pub fn val(&self) -> u64 {
self.val
}
}
impl FromStr for Bits {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
let Some(i) = s.find(|ch: char| !ch.is_numeric()) else {
return Err(());
};
let w = u64::from_str(&s[0..i]).map_err(|_| ())?;
let mut i = s[i..].chars();
if i.next() != Some('\'') {
return Err(());
}
let radix = match i.next() {
Some('b') => 2,
Some('o') => 8,
Some('d') => 10,
Some('h') => 16,
_ => return Err(()),
};
let str_val = i.as_str().replace('_', "");
let val = u64::from_str_radix(&str_val, radix).map_err(|_| ())?;
if val > mask(w)? {
return Err(());
}
Ok(Bits::new(w, val))
}
}
impl Display for Bits {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}'x{:x}", self.w, self.val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
assert_eq!(Bits { w: 1, val: 0 }, Bits::new(1, 0));
assert_eq!(Bits { w: 1, val: 1 }, Bits::new(1, 1));
assert_eq!(Bits { w: 1, val: 0 }, Bits::new(1, 2));
assert_eq!(Bits { w: 1, val: 1 }, Bits::new(1, 3));
assert_eq!(Bits { w: 2, val: 0 }, Bits::new(2, 0));
assert_eq!(Bits { w: 2, val: 1 }, Bits::new(2, 1));
assert_eq!(Bits { w: 2, val: 2 }, Bits::new(2, 2));
assert_eq!(Bits { w: 2, val: 3 }, Bits::new(2, 3));
assert_eq!(Bits { w: 2, val: 0 }, Bits::new(2, 4));
assert_eq!(
Bits {
w: 64,
val: 0xffff_ffff_ffff_ffff
},
Bits::new(64, 0xffff_ffff_ffff_ffff)
);
}
#[test]
fn test_from_str() {
assert_eq!(Ok(Bits::new(1, 0)), Bits::from_str("1'b0"));
assert_eq!(Ok(Bits::new(1, 1)), Bits::from_str("1'b1"));
assert_eq!(Err(()), Bits::from_str("1'b2"));
assert_eq!(Ok(Bits::new(3, 0o0)), Bits::from_str("3'o0"));
assert_eq!(Ok(Bits::new(3, 0o7)), Bits::from_str("3'o7"));
assert_eq!(Err(()), Bits::from_str("3'o8"));
assert_eq!(Err(()), Bits::from_str("3'o10"));
assert_eq!(Ok(Bits::new(12, 0o7263)), Bits::from_str("12'o7263"));
assert_eq!(Ok(Bits::new(4, 0)), Bits::from_str("4'd0"));
assert_eq!(Ok(Bits::new(4, 9)), Bits::from_str("4'd9"));
assert_eq!(Err(()), Bits::from_str("4'da"));
assert_eq!(Ok(Bits::new(4, 10)), Bits::from_str("4'd10"));
assert_eq!(Ok(Bits::new(12, 139)), Bits::from_str("12'd139"));
assert_eq!(Ok(Bits::new(4, 0x0)), Bits::from_str("4'h0"));
assert_eq!(Ok(Bits::new(4, 0xf)), Bits::from_str("4'hf"));
assert_eq!(Ok(Bits::new(4, 0xf)), Bits::from_str("4'hF"));
assert_eq!(Err(()), Bits::from_str("4'h10"));
assert_eq!(Ok(Bits::new(32, 0xf00d)), Bits::from_str("32'hf00d"));
assert_eq!(
Ok(Bits::new(32, 0xf00d_baaf)),
Bits::from_str("32'hf00d_baaf")
);
assert_eq!(
Ok(Bits::new(32, 0xf00d_baaf)),
Bits::from_str("32'hf0_0d_ba_af")
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/error.rs | systemrdl/src/error.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::{error::Error, fmt::Display};
use crate::{token::Token, value::PropertyType, ComponentType, Value};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RdlError<'a> {
UnexpectedToken(Token<'a>),
UnknownIdentifier(&'a str),
DuplicateInstanceName(String),
DuplicateTypeName(&'a str),
DuplicatePropertyName(&'a str),
DuplicateParameterName(&'a str),
UnknownTypeName(&'a str),
UnknownPropertyName(&'a str),
UnknownInstanceName(&'a str),
CantSetPropertyInRootScope,
BadStringLiteral,
ExpectedPropertyNotFound(&'a str),
UnexpectedPropertyType {
expected_type: PropertyType,
value: Value,
},
NotImplemented,
MsbLessThanLsb,
ComponentTypeCantBeInstantiated(ComponentType),
RootCantBeInstantiated,
DefaultPropertiesMustBeDefinedBeforeComponents,
StrideIsLessThanElementSize,
MultidimensionalFieldsNotSupported,
BadTernaryExpression(String),
}
impl Error for RdlError<'_> {}
impl Display for RdlError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BadTernaryExpression(v) => write!(
f,
"Ternary expression takes boolean value for first argument but bot {v:?}"
),
Self::UnexpectedToken(t) => write!(f, "Unexpected token {t:?}"),
Self::UnknownIdentifier(s) => write!(f, "Unexpected identifier {s:?}"),
Self::DuplicateInstanceName(s) => write!(f, "Dupicate instance name {s:?}"),
Self::DuplicateTypeName(s) => write!(f, "Dupicate type name {s:?}"),
Self::DuplicatePropertyName(s) => write!(f, "Dupicate property name {s:?}"),
Self::DuplicateParameterName(s) => write!(f, "Dupicate parameter name {s:?}"),
Self::UnknownTypeName(s) => write!(f, "Unknown type name {s:?}"),
Self::UnknownPropertyName(s) => write!(f, "Unknown property name {s:?}"),
Self::UnknownInstanceName(s) => write!(f, "Unknown instance name {s:?}"),
Self::CantSetPropertyInRootScope => write!(f, "Can't set property in root scope"),
Self::BadStringLiteral => write!(f, "Bad string literal"),
Self::ExpectedPropertyNotFound(s) => {
write!(f, "Required property {s:?} wasn't defined")
}
Self::UnexpectedPropertyType {
expected_type,
value,
} => write!(
f,
"Expected property of type {expected_type:?}, found {value:?}"
),
Self::NotImplemented => write!(f, "NOT IMPLEMENTED"),
Self::MsbLessThanLsb => write!(f, "msb less than lsb; big-endian not supported"),
Self::StrideIsLessThanElementSize => write!(f, "stride is less than element size"),
Self::DefaultPropertiesMustBeDefinedBeforeComponents => {
write!(f, "default properties must be defined before components")
}
Self::MultidimensionalFieldsNotSupported => {
write!(f, "Multidimensional fields not supported")
}
Self::ComponentTypeCantBeInstantiated(ty) => {
write!(f, "Component type {ty:?} can't be instantiated")
}
Self::RootCantBeInstantiated => write!(f, "Root can't be instantiated"),
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/scope.rs | systemrdl/src/scope.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::collections::HashMap;
use std::path::PathBuf;
use crate::component_meta::PropertyMeta;
use crate::file_source::FileSource;
use crate::value::{
AddressingType, ComponentType, InterruptType, PropertyType, Reference, ScopeType,
};
use crate::ParseError;
use crate::{
component_meta, token::Token, token_iter::TokenIter, Bits, FileParseError, RdlError, Result,
Value,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DynamicAssignment {
instance_path: Vec<String>,
prop_name: String,
value: Value,
}
impl DynamicAssignment {
fn parse<'a>(
tokens: &mut TokenIter<'a>,
scope: &Scope,
parameters: Option<&'_ ParameterScope<'_>>,
) -> Result<'a, Self> {
let mut instance_path = vec![];
loop {
instance_path.push(tokens.expect_identifier()?);
if *tokens.peek(0) != Token::Period {
break;
}
tokens.next();
}
let instance = scope.lookup_instance_by_path(instance_path.iter().cloned())?;
let ScopeType::Component(instance_ty) = instance.ty else {
return Err(RdlError::CantSetPropertyInRootScope);
};
tokens.expect(Token::Pointer)?;
let prop_name = tokens.expect_identifier()?;
let prop_meta = component_meta::property(instance_ty, prop_name)?;
let value = if *tokens.peek(0) == Token::Semicolon {
Value::Bool(true)
} else {
tokens.expect(Token::Equals)?;
prop_meta.ty.parse_or_lookup(tokens, parameters)?
};
Ok(Self {
instance_path: instance_path.into_iter().map(|s| s.to_string()).collect(),
prop_name: prop_name.into(),
value,
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterDefinition {
ty: PropertyType,
default: Value,
}
impl ParameterDefinition {
fn parse_map<'a>(
tokens: &mut TokenIter<'a>,
) -> Result<'a, HashMap<String, ParameterDefinition>> {
tokens.expect(Token::Hash)?;
tokens.expect(Token::ParenOpen)?;
let mut result = HashMap::new();
loop {
let ty = PropertyType::parse_type(tokens)?;
let name = tokens.expect_identifier()?;
// default value for bits is 0
let default = if tokens.peek(0) == &Token::Comma || tokens.peek(0) == &Token::ParenClose
{
if ty == PropertyType::Bits {
Value::Bits(Bits::new(32, 0))
} else {
return Err(RdlError::NotImplemented);
}
} else {
tokens.expect(Token::Equals)?;
ty.parse_or_lookup(tokens, None)?
};
if result.contains_key(name) {
return Err(RdlError::DuplicateParameterName(name));
}
result.insert(name.into(), ParameterDefinition { ty, default });
if tokens.peek(0) == &Token::ParenClose {
break;
}
tokens.expect(Token::Comma)?;
}
tokens.expect(Token::ParenClose)?;
Ok(result)
}
}
fn uses_property(ty: ScopeType, name: &str) -> bool {
if component_meta::default_property(ty, name).is_ok() {
return true;
}
let ScopeType::Component(ty) = ty else {
return false;
};
component_meta::property(ty, name).is_ok()
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Scope {
pub ty: ScopeType,
pub types: HashMap<String, Scope>,
pub instances: Vec<Instance>,
pub default_properties: HashMap<String, Value>,
pub properties: HashMap<String, Value>,
pub dynamic_assignments: Vec<DynamicAssignment>,
}
impl Scope {
fn new(ty: ScopeType) -> Self {
Scope {
ty,
..Default::default()
}
}
pub fn property_val<'a, T: TryFrom<Value, Error = RdlError<'static>>>(
&self,
name: &'a str,
) -> Result<'a, T> {
match self.property_val_opt(name)? {
Some(val) => Ok(val),
None => Err(RdlError::ExpectedPropertyNotFound(name)),
}
}
pub fn property_val_opt<T: TryFrom<Value, Error = RdlError<'static>>>(
&self,
name: &str,
) -> Result<'static, Option<T>> {
match self.properties.get(name) {
Some(val) => Ok(Some(T::try_from(val.clone())?)),
None => Ok(None),
}
}
pub fn lookup_instance_by_path<'a>(
&self,
mut path_iter: impl Iterator<Item = &'a str>,
) -> Result<'a, &Scope> {
if let Some(instance_name) = path_iter.next() {
if let Some(instance) = self.instances.iter().find(|e| e.name == instance_name) {
instance.scope.lookup_instance_by_path(path_iter)
} else {
Err(RdlError::UnknownInstanceName(instance_name))
}
} else {
Ok(self)
}
}
fn set_property_defaults(&mut self, parent: Option<&ParentScope<'_>>) {
if let ScopeType::Component(ty) = self.ty {
let mut next_parent = parent;
while let Some(parent_scope) = next_parent {
for (prop_name, val) in parent_scope.scope.default_properties.iter() {
if self.properties.contains_key(prop_name) {
continue;
}
if component_meta::property(ty, prop_name).is_err() {
continue;
}
self.properties.insert(prop_name.into(), val.clone());
}
next_parent = parent_scope.parent;
}
}
}
pub fn as_parent(&self) -> ParentScope {
ParentScope {
scope: self,
parent: None,
}
}
fn calculate_offsets(&mut self) -> Result<'static, ()> {
let addr_mode = AddressingType::Compact;
let default_alignment = self.property_val_opt::<u64>("alignment").ok().flatten();
// Set reg offsets, accounting for both registers and memory regions
let mut next_offset = 0;
for instance in self.instances.iter_mut() {
match instance.scope.ty {
ScopeType::Component(ComponentType::Reg) => {
let reg_width = instance
.scope
.property_val_opt("regwidth")
.ok()
.flatten()
.unwrap_or(32u64);
let access_width = instance
.scope
.property_val_opt("accesswidth")
.ok()
.flatten()
.unwrap_or(reg_width);
let align = if let Some(next_alignment) = instance.next_alignment {
next_alignment
} else if let Some(default_alignment) = default_alignment {
default_alignment
} else {
match addr_mode {
AddressingType::Compact => access_width / 8,
AddressingType::RegAlign => instance.element_size(),
AddressingType::FullAlign => instance.total_size()?,
}
};
if instance.offset.is_none() {
if next_offset % align != 0 {
next_offset = ((next_offset / align) + 1) * align;
}
instance.offset = Some(next_offset);
}
if let Some(offset) = instance.offset {
next_offset = offset + instance.total_size()?;
}
}
ScopeType::Component(ComponentType::Mem) => {
// Calculate memory size from mementries and memwidth
let mem_width = instance
.scope
.property_val_opt("memwidth")
.ok()
.flatten()
.unwrap_or(32u64);
let mem_entries = instance
.scope
.property_val_opt("mementries")
.ok()
.flatten()
.unwrap_or(1u64);
let mem_size = (mem_width / 8) * mem_entries;
if instance.offset.is_none() {
// Align memory to its natural boundary (power of 2)
let align = mem_size.next_power_of_two();
if next_offset % align != 0 {
next_offset = ((next_offset / align) + 1) * align;
}
instance.offset = Some(next_offset);
}
if let Some(offset) = instance.offset {
next_offset = offset + mem_size;
}
}
_ => continue,
}
}
let mut next_offset = 0;
for instance in self.instances.iter_mut() {
if instance.scope.ty != ComponentType::Field.into() {
continue;
}
if instance.dimension_sizes.len() > 1 {
return Err(RdlError::MultidimensionalFieldsNotSupported);
}
let field_width = if instance.dimension_sizes.len() == 1 {
instance.dimension_sizes[0]
} else {
instance
.scope
.property_val_opt("fieldwidth")
.ok()
.flatten()
.unwrap_or(1u64)
};
if instance.offset.is_none() {
instance.offset = Some(next_offset);
}
if let Some(offset) = instance.offset {
next_offset = offset + field_width;
}
}
for ty in self.types.values_mut() {
ty.calculate_offsets()?;
}
for el in self.instances.iter_mut() {
el.scope.calculate_offsets()?;
}
Ok(())
}
fn parse<'a>(
&mut self,
tokens: &mut TokenIter<'a>,
parent: Option<&ParentScope<'_>>,
parameters: Option<&ParameterScope<'_>>,
) -> Result<'a, ()> {
loop {
if self.ty == ScopeType::Root && *tokens.peek(0) == Token::EndOfFile {
break;
}
if *tokens.peek(0) == Token::BraceClose {
break;
}
let peek0 = tokens.peek(0).clone();
let peek1 = tokens.peek(1).clone();
if let Ok(component_type) = component_keyword(&peek0, &peek1) {
if tokens.next() == Token::External {
let token = tokens.next();
if token != Token::Reg && token != Token::Mem {
return Err(RdlError::UnexpectedToken(token));
}
}
let type_name = if *tokens.peek(0) == Token::BraceOpen {
None
} else {
Some(tokens.expect_identifier()?)
};
let pscope;
let parameters = if type_name.is_some() && tokens.peek(0) == &Token::Hash {
pscope = ParameterScope {
parent: parameters,
parameters: ParameterDefinition::parse_map(tokens)?,
};
Some(&pscope)
} else {
parameters
};
let mut ty_scope = Self::new(ScopeType::Component(component_type));
tokens.expect(Token::BraceOpen)?;
ty_scope.parse(
tokens,
Some(&ParentScope {
parent,
scope: self,
}),
parameters,
)?;
ty_scope.set_property_defaults(Some(&ParentScope {
parent,
scope: self,
}));
tokens.expect(Token::BraceClose)?;
if let Some(type_name) = type_name {
if self.types.contains_key(type_name) {
return Err(RdlError::DuplicateTypeName(type_name));
}
self.types.insert(type_name.into(), ty_scope.clone());
}
if *tokens.peek(0) != Token::Semicolon {
if *tokens.peek(0) == Token::External {
tokens.next(); // ignore external keyword
}
loop {
let instance = Instance::parse(ty_scope.clone(), tokens, parameters)?;
if self.instances.iter().any(|e| e.name == instance.name) {
return Err(RdlError::DuplicateInstanceName(instance.name));
}
self.instances.push(instance);
if *tokens.peek(0) == Token::Comma {
tokens.next();
continue;
}
break;
}
}
tokens.expect(Token::Semicolon)?;
continue;
}
if *tokens.peek(0) == Token::Identifier("default") {
tokens.next();
let prop = PropertyAssignment::parse(tokens, parameters, |prop_name| {
component_meta::default_property(self.ty, prop_name)
})?;
#[rustfmt::skip]
let prev_components_use_property =
self.instances.iter().any(|i| uses_property(i.scope.ty, prop.prop_name)) ||
self.types.values().any(|s| uses_property(s.ty, prop.prop_name));
if prev_components_use_property {
// Error if this default value could have been used by
// previously defined components in this scope (the spec
// isn't clear whether defaults apply to previously defined
// components, so discourage users from doing ambiguous
// things).
return Err(RdlError::DefaultPropertiesMustBeDefinedBeforeComponents);
}
self.default_properties
.insert(prop.prop_name.into(), prop.value);
continue;
}
if (is_intr_modifier(tokens.peek(0)) && *tokens.peek(1) == Token::Identifier("intr"))
|| tokens.peek(0).is_identifier()
&& (*tokens.peek(1) == Token::Equals || *tokens.peek(1) == Token::Semicolon)
{
match self.ty {
ScopeType::Component(ComponentType::Enum) => {
let enum_variant_name = tokens.expect_identifier()?;
// Enums don't have properties
let mut variant_scope = Scope {
ty: ScopeType::Component(ComponentType::EnumVariant),
..Default::default()
};
let mut value = None;
if *tokens.peek(0) == Token::Equals {
tokens.next();
value = match tokens.next() {
Token::Bits(bits) => Some(bits),
Token::Number(num) => {
// When a plain number is provided for enum values,
// use a default width (let's use 32 bits as default)
Some(Bits::new(32, num))
}
unexpected => return Err(RdlError::UnexpectedToken(unexpected)),
};
if *tokens.peek(0) == Token::BraceOpen {
tokens.next();
variant_scope =
Self::new(ScopeType::Component(ComponentType::EnumVariant));
variant_scope.parse(
tokens,
Some(&ParentScope {
parent,
scope: self,
}),
parameters,
)?;
tokens.expect(Token::BraceClose)?;
}
}
self.instances.push(Instance {
name: enum_variant_name.into(),
reset: value,
scope: variant_scope,
..Default::default()
});
tokens.expect(Token::Semicolon)?;
continue;
}
_ => {
// This is a property
let ScopeType::Component(ty) = self.ty else {
return Err(RdlError::CantSetPropertyInRootScope);
};
let assignment =
PropertyAssignment::parse(tokens, parameters, |prop_name| {
component_meta::property(ty, prop_name)
})?;
if self.properties.contains_key(assignment.prop_name) {
return Err(RdlError::DuplicatePropertyName(assignment.prop_name));
}
self.properties
.insert(assignment.prop_name.into(), assignment.value);
continue;
}
}
}
if tokens.peek(0).is_identifier() && *tokens.peek(1) == Token::Period
|| *tokens.peek(1) == Token::Pointer
{
let assignment = DynamicAssignment::parse(tokens, self, parameters)?;
tokens.expect(Token::Semicolon)?;
self.dynamic_assignments.push(assignment);
continue;
}
let type_name = tokens.expect_identifier()?;
// This is a template instantiation
let ty_scope = lookup_typedef(self, parent, type_name)?.clone();
let mut instance = Instance::parse(ty_scope, tokens, parameters)?;
instance.type_name = Some(type_name.into());
if self.instances.iter().any(|e| e.name == instance.name) {
return Err(RdlError::DuplicateInstanceName(instance.name));
}
self.instances.push(instance);
tokens.expect(Token::Semicolon)?;
}
Ok(())
}
pub fn parse_root<'a>(
file_source: &'a dyn FileSource,
input_files: &[PathBuf],
) -> std::result::Result<Self, FileParseError<'a>> {
let mut result = Self::parse_root_internal(file_source, input_files)?;
result
.calculate_offsets()
.map_err(|_| FileParseError::CouldNotCalculateOffsets)?;
Ok(result)
}
fn parse_root_internal<'a>(
file_source: &'a dyn FileSource,
input_files: &[PathBuf],
) -> std::result::Result<Self, FileParseError<'a>> {
let mut result = Self::new(ScopeType::Root);
for path in input_files.iter() {
let mut tokens = TokenIter::from_path(file_source, path).map_err(FileParseError::Io)?;
match result.parse(&mut tokens, None, None) {
Ok(()) => {}
Err(error) => {
return Err(FileParseError::Parse(ParseError::new(
tokens.current_file_path(),
tokens.current_file_contents(),
tokens.last_span().clone(),
error,
)));
}
}
}
Ok(result)
}
}
fn component_keyword<'a>(token: &Token<'a>, token2: &Token<'a>) -> Result<'a, ComponentType> {
match (token, token2) {
(Token::Field, _) => Ok(ComponentType::Field),
(Token::External, Token::Reg) => Ok(ComponentType::Reg),
(Token::External, Token::Mem) => Ok(ComponentType::Mem),
(Token::Reg, _) => Ok(ComponentType::Reg),
(Token::RegFile, _) => Ok(ComponentType::RegFile),
(Token::AddrMap, _) => Ok(ComponentType::AddrMap),
(Token::Signal, _) => Ok(ComponentType::Signal),
(Token::Enum, _) => Ok(ComponentType::Enum),
(Token::Mem, _) => Ok(ComponentType::Mem),
(Token::Constraint, _) => Ok(ComponentType::Constraint),
(unexpected, _) => Err(RdlError::UnexpectedToken(unexpected.clone())),
}
}
pub struct ParameterScope<'a> {
parent: Option<&'a ParameterScope<'a>>,
parameters: HashMap<String, ParameterDefinition>,
}
#[derive(Copy, Clone)]
pub struct ParentScope<'a> {
parent: Option<&'a ParentScope<'a>>,
pub scope: &'a Scope,
}
impl<'a> ParentScope<'a> {
pub fn instance_iter(&'a self) -> impl Iterator<Item = InstanceRef<'a>> {
self.scope.instances.iter().map(|i| InstanceRef {
instance: i,
scope: ParentScope {
parent: Some(self),
scope: &i.scope,
},
})
}
pub fn type_iter(&'a self) -> impl Iterator<Item = (&'a str, ParentScope<'a>)> {
self.scope.types.iter().map(|(name, scope)| {
(
name.as_str(),
ParentScope {
parent: Some(self),
scope,
},
)
})
}
pub fn lookup_typedef(&'a self, name: &'_ str) -> Option<ParentScope<'a>> {
let mut parent = self;
loop {
if let Some(result) = parent.scope.types.get(name) {
return Some(ParentScope {
scope: result,
parent: Some(parent),
});
}
if let Some(new_parent) = parent.parent {
parent = new_parent;
} else {
return None;
}
}
}
}
fn lookup_typedef<'a, 'b>(
mut scope: &'b Scope,
mut parent: Option<&'b ParentScope<'_>>,
name: &'a str,
) -> Result<'a, &'b Scope> {
loop {
if let Some(result) = scope.types.get(name) {
return Ok(result);
}
if let Some(parent_scope) = parent {
scope = parent_scope.scope;
parent = parent_scope.parent;
} else {
return Err(RdlError::UnknownTypeName(name));
}
}
}
#[derive(Copy, Clone)]
pub struct InstanceRef<'a> {
pub instance: &'a Instance,
pub scope: ParentScope<'a>,
}
pub fn lookup_parameter<'a, 'b>(
parameters: Option<&'b ParameterScope<'b>>,
name: &'a str,
) -> Result<'a, &'b Value> {
if let Some(p) = parameters {
if let Some(val) = p.parameters.get(name) {
return Ok(&val.default);
}
return lookup_parameter(p.parent, name);
}
Err(RdlError::UnknownIdentifier(name))
}
pub fn lookup_parameter_of_type<'a, 'b>(
parameters: Option<&'b ParameterScope<'b>>,
name: &'a str,
ty: PropertyType,
) -> Result<'a, &'b Value> {
let value = lookup_parameter(parameters, name)?;
if value.property_type() != ty {
return Err(RdlError::UnexpectedPropertyType {
expected_type: ty,
value: value.clone(),
});
}
Ok(value)
}
fn expect_number<'a>(
i: &mut TokenIter<'a>,
parameters: Option<&ParameterScope<'_>>,
) -> Result<'a, u64> {
match i.next() {
Token::Number(val) => Ok(val),
Token::Identifier(name) => match lookup_parameter(parameters, name)? {
Value::U64(val) => Ok(*val),
unexpected => Err(RdlError::UnexpectedPropertyType {
expected_type: PropertyType::U64,
value: unexpected.clone(),
}),
},
unexpected => Err(RdlError::UnexpectedToken(unexpected)),
}
}
fn parse_parameter_map<'a>(i: &mut TokenIter<'a>) -> Result<'a, HashMap<String, Value>> {
i.expect(Token::Hash)?;
i.expect(Token::ParenOpen)?;
if *i.peek(0) == Token::ParenClose {
i.next();
return Ok(HashMap::new());
}
let mut map: HashMap<String, Value> = HashMap::new();
loop {
i.expect(Token::Period)?;
let name = i.expect_identifier()?;
i.expect(Token::ParenOpen)?;
let token = i.peek(0).clone();
let value = match token {
Token::Bits(n) => {
i.next();
Value::Bits(n)
}
Token::Identifier(_) => {
let reference = Reference::parse(i)?;
Value::Reference(reference)
}
unexpected => return Err(RdlError::UnexpectedToken(unexpected)),
};
map.insert(name.into(), value);
i.expect(Token::ParenClose)?;
if *i.peek(0) == Token::ParenClose {
i.next();
return Ok(map);
}
i.expect(Token::Comma)?;
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Instance {
pub name: String,
// If this instance was instantiated from a common type, this is the name of
// that type
pub type_name: Option<String>,
// [2][4] parses to vec![2, 4], which means there is an array of 2 elements,
// where each element is an array of 4 values. In rust notation this would be [[u32; 4]; 2].
pub dimension_sizes: Vec<u64>,
pub reset: Option<Bits>,
pub offset: Option<u64>,
pub stride: Option<u64>,
pub next_alignment: Option<u64>,
pub scope: Scope,
pub parameters: HashMap<String, Value>,
}
impl Instance {
pub fn element_size(&self) -> u64 {
if let Ok(Some(w)) = self.scope.property_val_opt::<u64>("regwidth") {
w / 8
} else {
// According to section 10.1 of the SystemRDL 2.0 spec, the default regwidth is 32-bits
4
}
}
pub fn total_size(&self) -> Result<'static, u64> {
let stride = if let Some(stride) = self.stride {
stride
} else {
self.element_size()
};
if stride < self.element_size() {
return Err(RdlError::StrideIsLessThanElementSize);
}
let total_elements: u64 = self.dimension_sizes.iter().product();
Ok(total_elements * stride)
}
fn parse<'a>(
scope: Scope,
i: &mut TokenIter<'a>,
parameters: Option<&ParameterScope<'_>>,
) -> Result<'a, Self> {
let ScopeType::Component(component_type) = scope.ty else {
return Err(RdlError::RootCantBeInstantiated);
};
let component_meta = component_meta::get_component_meta(component_type);
if !component_meta.can_instantiate {
return Err(RdlError::ComponentTypeCantBeInstantiated(component_type));
}
// check for parameters
let specified_params = if *i.peek(0) == Token::Hash {
parse_parameter_map(i)?
} else {
HashMap::new()
};
let mut result = Self {
name: i.expect_identifier()?.to_string(),
scope,
parameters: specified_params,
..Default::default()
};
if component_type == ComponentType::Field
&& *i.peek(0) == Token::BracketOpen
&& *i.peek(2) == Token::Colon
{
i.next();
let msb = expect_number(i, parameters)?;
i.expect(Token::Colon)?;
let lsb = expect_number(i, parameters)?;
if msb < lsb {
return Err(RdlError::MsbLessThanLsb);
}
result.dimension_sizes.push(msb - lsb + 1);
result.offset = Some(lsb);
i.expect(Token::BracketClose)?;
} else {
while *i.peek(0) == Token::BracketOpen {
i.next();
result.dimension_sizes.push(expect_number(i, parameters)?);
i.expect(Token::BracketClose)?;
}
}
if *i.peek(0) == Token::Equals {
i.next();
result.reset = match i.next() {
Token::Bits(bits) => Some(bits),
Token::Number(num) => Some(Bits::new(result.dimension_sizes.iter().product(), num)),
unexpected => return Err(RdlError::UnexpectedToken(unexpected)),
}
}
if result.scope.ty == ComponentType::Reg.into()
|| result.scope.ty == ComponentType::RegFile.into()
|| result.scope.ty == ComponentType::AddrMap.into()
|| result.scope.ty == ComponentType::Mem.into()
{
if *i.peek(0) == Token::At {
i.next();
result.offset = Some(expect_number(i, parameters)?);
}
if *i.peek(0) == Token::PlusEqual {
i.next();
result.stride = Some(expect_number(i, parameters)?);
}
if *i.peek(0) == Token::PercentEqual {
i.next();
result.next_alignment = Some(expect_number(i, parameters)?);
}
}
Ok(result)
}
}
fn is_intr_modifier(token: &Token) -> bool {
matches!(
*token,
Token::Identifier("posedge" | "negedge" | "bothedge" | "level" | "nonsticky" | "sticky")
)
}
struct PropertyAssignment<'a> {
prop_name: &'a str,
value: Value,
}
static INTR_BOOL_PROPERTY: PropertyMeta = PropertyMeta {
name: "intr",
ty: PropertyType::Boolean,
};
fn intr_bool_property<'a>(_name: &str) -> Result<'a, &'static PropertyMeta> {
Ok(&INTR_BOOL_PROPERTY)
}
impl<'a> PropertyAssignment<'a> {
fn parse(
tokens: &mut TokenIter<'a>,
parameters: Option<&ParameterScope<'_>>,
meta_lookup_fn: impl Fn(&'a str) -> Result<'a, &'static PropertyMeta>,
) -> Result<'a, Self> {
if is_intr_modifier(tokens.peek(0)) && *tokens.peek(1) == Token::Identifier("intr") {
let intr_modifier = tokens.expect_identifier()?;
// skip the bool tokens...
PropertyAssignment::parse(tokens, parameters, intr_bool_property)?;
return Ok(Self {
prop_name: "intr",
value: match intr_modifier {
"posedge" => InterruptType::PosEdge.into(),
"negedge" => InterruptType::NegEdge.into(),
"bothedge" => InterruptType::BothEdge.into(),
"level" => InterruptType::Level.into(),
"nonsticky" => InterruptType::NonSticky.into(),
"sticky" => InterruptType::Sticky.into(),
_ => InterruptType::Level.into(),
},
});
}
let prop_name = tokens.expect_identifier()?;
let prop_meta = meta_lookup_fn(prop_name)?;
let value = if *tokens.peek(0) == Token::Semicolon {
// This must be a boolean property set to true or an intr
if prop_meta.ty != PropertyType::Boolean
&& prop_meta.ty != PropertyType::BooleanOrReference
&& prop_meta.ty != PropertyType::FieldInterrupt
{
return Err(RdlError::UnexpectedPropertyType {
expected_type: prop_meta.ty,
value: true.into(),
});
}
true.into()
} else {
tokens.expect(Token::Equals)?;
prop_meta.ty.eval(tokens, parameters)?
};
tokens.expect(Token::Semicolon)?;
Ok(Self { prop_name, value })
}
}
#[cfg(test)]
mod tests {
use crate::{file_source::MemFileSource, value::AccessType, EnumReference};
use super::*;
#[test]
fn test_scope_def() {
let fs = MemFileSource::from_entries(&[(
"main.rdl".into(),
r#"
field {} some_field;
field a_field_ty {};
"#
.into(),
)]);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/file_source.rs | systemrdl/src/file_source.rs | // Licensed under the Apache-2.0 license
use crate::string_arena::StringArena;
use std::{cell::RefCell, path::Path};
#[cfg(test)]
use std::{
collections::HashMap,
io::{Error, ErrorKind},
path::PathBuf,
};
pub trait FileSource {
fn read_to_string(&self, path: &Path) -> std::io::Result<&str>;
}
#[derive(Default)]
pub struct FsFileSource {
arena: StringArena,
patches: RefCell<Vec<(String, String, String)>>,
}
impl FsFileSource {
pub fn new() -> Self {
FsFileSource {
arena: StringArena::new(),
patches: RefCell::new(Vec::new()),
}
}
pub fn add_patch(&self, path: &Path, from: &str, to: &str) {
self.patches.borrow_mut().push((
path.display().to_string(),
from.to_owned(),
to.to_owned(),
));
}
}
impl FileSource for FsFileSource {
fn read_to_string(&self, path: &Path) -> std::io::Result<&str> {
let mut contents = std::fs::read_to_string(path)?;
for (patch_path, from, to) in self.patches.borrow().iter() {
if path.display().to_string() == *patch_path {
contents = contents.replace(from, to);
}
}
Ok(self.arena.add(contents))
}
}
#[cfg(test)]
pub struct MemFileSource {
arena: crate::string_arena::StringArena,
map: HashMap<PathBuf, String>,
}
#[cfg(test)]
impl MemFileSource {
pub fn from_entries(entries: &[(PathBuf, String)]) -> Self {
Self {
arena: StringArena::new(),
map: entries.iter().cloned().collect(),
}
}
}
#[cfg(test)]
impl FileSource for MemFileSource {
fn read_to_string(&self, path: &Path) -> std::io::Result<&str> {
Ok(self.arena.add(
self.map
.get(path)
.ok_or(Error::new(ErrorKind::NotFound, path.to_string_lossy()))?
.clone(),
))
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/token_iter.rs | systemrdl/src/token_iter.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use crate::file_source::FileSource;
use crate::lexer::{Lexer, Span};
use crate::token::Token;
use crate::value::parse_str_literal;
use crate::{Bits, RdlError, Result};
struct IncludeStackEntry<'a> {
lex: Lexer<'a>,
file_path: PathBuf,
file_contents: &'a str,
}
pub struct TokenIter<'a> {
lex: Lexer<'a>,
fifo: VecDeque<(Token<'a>, Span)>,
last_span: Span,
current_file_contents: &'a str,
current_file_path: PathBuf,
file_source: Option<&'a dyn FileSource>,
iter_stack: Vec<IncludeStackEntry<'a>>,
}
impl<'a> TokenIter<'a> {
pub fn from_path(file_source: &'a dyn FileSource, file_path: &Path) -> std::io::Result<Self> {
let file_contents = file_source.read_to_string(file_path)?;
let lex = Lexer::new(file_contents);
Ok(Self {
lex,
fifo: VecDeque::new(),
last_span: 0..0,
current_file_path: file_path.into(),
current_file_contents: file_contents,
iter_stack: Vec::new(),
file_source: Some(file_source),
})
}
pub fn from_str(s: &'a str) -> Self {
Self {
lex: Lexer::new(s),
fifo: Default::default(),
last_span: Default::default(),
current_file_path: Default::default(),
current_file_contents: s,
file_source: Default::default(),
iter_stack: Default::default(),
}
}
fn lex_next(&mut self) -> Option<Token<'a>> {
const INCLUDE_DEPTH_LIMIT: usize = 100;
loop {
match self.lex.next() {
Some(Token::PreprocInclude) => {
let Some(Token::StringLiteral(filename)) = self.lex.next() else {
return Some(Token::Error);
};
let Some(file_source) = self.file_source else {
return Some(Token::UnableToOpenFile(filename));
};
let Ok(parsed_filename) = parse_str_literal(filename) else {
return Some(Token::UnableToOpenFile(filename));
};
let file_path = if let Some(parent) = self.current_file_path.parent() {
parent.join(parsed_filename)
} else {
PathBuf::from(parsed_filename)
};
let Ok(file_contents) = file_source.read_to_string(&file_path) else {
return Some(Token::UnableToOpenFile(filename));
};
if self.iter_stack.len() >= INCLUDE_DEPTH_LIMIT {
return Some(Token::IncludeDepthLimitReached);
}
let old_lex = std::mem::replace(&mut self.lex, Lexer::new(file_contents));
let old_file_path =
std::mem::replace(&mut self.current_file_path, filename.into());
let old_file_contents =
std::mem::replace(&mut self.current_file_contents, file_contents);
self.iter_stack.push(IncludeStackEntry {
lex: old_lex,
file_path: old_file_path,
file_contents: old_file_contents,
});
self.current_file_path = file_path;
// Retry with new lexer
continue;
}
None => {
let stack_entry = self.iter_stack.pop()?;
// this file was included from another file; resume
// processing the original file.
self.lex = stack_entry.lex;
self.current_file_path = stack_entry.file_path;
self.current_file_contents = stack_entry.file_contents;
continue;
}
token => return token,
}
}
}
pub fn peek(&mut self, lookahead: usize) -> &Token<'a> {
while self.fifo.len() < lookahead + 1 {
let token = self.lex_next().unwrap_or(Token::EndOfFile);
self.fifo.push_back((token, self.lex.span()));
}
&self.fifo[lookahead].0
}
pub fn next(&mut self) -> Token<'a> {
let next = if self.fifo.is_empty() {
(self.lex_next().unwrap_or(Token::EndOfFile), self.lex.span())
} else {
self.fifo.pop_front().unwrap()
};
self.last_span = next.1.clone();
next.0
}
pub fn expect(&mut self, expected: Token) -> Result<'a, ()> {
let token = self.next();
if token != expected {
return Err(RdlError::UnexpectedToken(token));
}
Ok(())
}
pub fn expect_identifier(&mut self) -> Result<'a, &'a str> {
match self.next() {
Token::Identifier(name) => Ok(name),
token => Err(RdlError::UnexpectedToken(token)),
}
}
pub fn expect_number(&mut self) -> Result<'a, u64> {
match self.next() {
Token::Number(val) => Ok(val),
token => Err(RdlError::UnexpectedToken(token)),
}
}
pub fn expect_string(&mut self) -> Result<'a, &'a str> {
match self.next() {
Token::StringLiteral(val) => Ok(val),
token => Err(RdlError::UnexpectedToken(token)),
}
}
pub fn expect_bits(&mut self) -> Result<'a, Bits> {
match self.next() {
Token::Bits(bits) => Ok(bits),
token => Err(RdlError::UnexpectedToken(token)),
}
}
pub fn last_span(&self) -> &Span {
&self.last_span
}
pub fn current_file_contents(&self) -> &'a str {
self.current_file_contents
}
pub fn current_file_path(&self) -> &Path {
&self.current_file_path
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/string_arena.rs | systemrdl/src/string_arena.rs | // Licensed under the Apache-2.0 license
use std::collections::HashSet;
// TODO: Consider using elsa/FrozenVec to remove unsafe code
#[derive(Default)]
pub struct StringArena {
// SAFETY: To maintain soundness, strings in this HashSet MUST NOT be removed or mutated.
strings: std::cell::RefCell<HashSet<String>>,
}
impl StringArena {
#[allow(dead_code)]
pub fn new() -> Self {
Default::default()
}
pub fn add<'a>(&'a self, s: String) -> &'a str {
let mut map = self.strings.borrow_mut();
if let Some(existing) = map.get(&s) {
unsafe { std::mem::transmute::<&'_ str, &'a str>(existing.as_str()) }
} else {
let slice = unsafe { std::mem::transmute::<&'_ str, &'a str>(s.as_str()) };
map.insert(s);
slice
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn foo() {
let arena = StringArena::new();
let a = arena.add("Hello world".into());
let b = arena.add("Foo".into());
let c = arena.add("Foo".into());
assert_eq!(a, "Hello world");
assert_eq!(b, "Foo");
assert_eq!(c, "Foo");
assert_eq!(b.as_ptr(), c.as_ptr());
drop(arena);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/component_meta.rs | systemrdl/src/component_meta.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use crate::value::{ComponentType, PropertyType, ScopeType};
use crate::{RdlError, Result};
#[derive(Debug)]
pub struct PropertyMeta {
pub name: &'static str,
pub ty: PropertyType,
}
pub struct ComponentMeta {
ty: ComponentType,
pub can_instantiate: bool,
deep_subelement_types: &'static [&'static ComponentMeta],
properties: &'static [PropertyMeta],
}
#[rustfmt::skip]
static SIGNAL: ComponentMeta = ComponentMeta {
ty: ComponentType::Signal,
can_instantiate: true,
deep_subelement_types: &[],
properties: &[
PropertyMeta{name: "signalwidth", ty: PropertyType::U64},
PropertyMeta{name: "sync", ty: PropertyType::Boolean},
PropertyMeta{name: "async", ty: PropertyType::Boolean},
PropertyMeta{name: "cpuif_reset", ty: PropertyType::Boolean},
PropertyMeta{name: "field_reset", ty: PropertyType::Boolean},
PropertyMeta{name: "activelow", ty: PropertyType::Boolean},
PropertyMeta{name: "activehigh", ty: PropertyType::Boolean},
],
};
#[rustfmt::skip]
static FIELD: ComponentMeta = ComponentMeta {
ty: ComponentType::Field,
can_instantiate: true,
deep_subelement_types: &[],
properties: &[
// Structural properties
PropertyMeta{name: "donttest", ty: PropertyType::Bits},
PropertyMeta{name: "dontcompare", ty: PropertyType::Bits},
// Field access properties
PropertyMeta{name: "hw", ty: PropertyType::AccessType},
PropertyMeta{name: "sw", ty: PropertyType::AccessType},
// Hardware signal properties
PropertyMeta{name: "next", ty: PropertyType::Reference},
PropertyMeta{name: "reset", ty: PropertyType::BitOrReference},
PropertyMeta{name: "resetsignal", ty: PropertyType::Reference},
// Software access properties
PropertyMeta{name: "rclr", ty: PropertyType::Boolean},
PropertyMeta{name: "rset", ty: PropertyType::Boolean},
PropertyMeta{name: "onread", ty: PropertyType::OnReadType},
PropertyMeta{name: "woset", ty: PropertyType::Boolean},
PropertyMeta{name: "woclr", ty: PropertyType::Boolean},
PropertyMeta{name: "onwrite", ty: PropertyType::OnWriteType},
PropertyMeta{name: "swwe", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "swwel", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "swmod", ty: PropertyType::Boolean},
PropertyMeta{name: "swacc", ty: PropertyType::Boolean},
PropertyMeta{name: "singlepulse", ty: PropertyType::Boolean},
// Hardware access properties
PropertyMeta{name: "we", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "wel", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "anded", ty: PropertyType::Boolean},
PropertyMeta{name: "ored", ty: PropertyType::Boolean},
PropertyMeta{name: "xored", ty: PropertyType::Boolean},
PropertyMeta{name: "fieldwidth", ty: PropertyType::U64},
PropertyMeta{name: "hwclr", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "hwset", ty: PropertyType::BooleanOrReference},
PropertyMeta{name: "hwenable", ty: PropertyType::Reference},
PropertyMeta{name: "hwmask", ty: PropertyType::Reference},
// Counter field properties
PropertyMeta{name: "counter", ty: PropertyType::Boolean},
PropertyMeta{name: "threshold", ty: PropertyType::BitOrReference}, // alias incrthreshold
PropertyMeta{name: "saturate", ty: PropertyType::BitOrReference}, // alias incrsaturate
PropertyMeta{name: "incrthreshold", ty: PropertyType::BitOrReference},
PropertyMeta{name: "incrsaturate", ty: PropertyType::BitOrReference},
PropertyMeta{name: "overflow", ty: PropertyType::Boolean},
PropertyMeta{name: "underflow", ty: PropertyType::Boolean},
PropertyMeta{name: "incrvalue", ty: PropertyType::BitOrReference},
PropertyMeta{name: "incr", ty: PropertyType::Reference},
PropertyMeta{name: "incrwidth", ty: PropertyType::U64},
PropertyMeta{name: "decrvalue", ty: PropertyType::BitOrReference},
PropertyMeta{name: "decr", ty: PropertyType::Reference},
PropertyMeta{name: "decrwidth", ty: PropertyType::U64},
PropertyMeta{name: "decrsaturate", ty: PropertyType::BitOrReference},
PropertyMeta{name: "decrthreshold", ty: PropertyType::BitOrReference},
// Field access interrupt properties
PropertyMeta{name: "intr" , ty: PropertyType::FieldInterrupt}, // also
PropertyMeta{name: "enable", ty: PropertyType::Reference},
PropertyMeta{name: "mask", ty: PropertyType::Reference},
PropertyMeta{name: "haltenable", ty: PropertyType::Reference},
PropertyMeta{name: "haltmask", ty: PropertyType::Reference},
PropertyMeta{name: "sticky", ty: PropertyType::Boolean},
PropertyMeta{name: "stickybit", ty: PropertyType::Boolean},
// Miscellaneous field properties
PropertyMeta{name: "encode", ty: PropertyType::EnumReference},
PropertyMeta{name: "precedence", ty: PropertyType::PrecedenceType},
PropertyMeta{name: "paritycheck", ty: PropertyType::Boolean},
],
};
#[rustfmt::skip]
static REG: ComponentMeta = ComponentMeta {
ty: ComponentType::Reg,
can_instantiate: true,
deep_subelement_types: &[&FIELD],
properties: &[
PropertyMeta{name: "regwidth", ty: PropertyType::U64},
PropertyMeta{name: "accesswidth", ty: PropertyType::U64},
PropertyMeta{name: "errextbus", ty: PropertyType::Boolean},
PropertyMeta{name: "shared", ty: PropertyType::Boolean},
],
};
#[rustfmt::skip]
static MEM: ComponentMeta = ComponentMeta {
ty: ComponentType::Mem,
can_instantiate: true,
deep_subelement_types: &[],
properties: &[
PropertyMeta{name: "mementries", ty: PropertyType::U64},
PropertyMeta{name: "memwidth", ty: PropertyType::U64},
PropertyMeta{name: "sw", ty: PropertyType::AccessType},
],
};
#[rustfmt::skip]
static REGFILE: ComponentMeta = ComponentMeta {
ty: ComponentType::RegFile,
can_instantiate: true,
deep_subelement_types: &[®, ®FILE, &FIELD, &SIGNAL],
properties: &[
PropertyMeta{name: "alignment", ty: PropertyType::U64},
PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean},
PropertyMeta{name: "errextbus", ty: PropertyType::Boolean},
],
};
#[rustfmt::skip]
static ADDRMAP: ComponentMeta = ComponentMeta {
ty: ComponentType::AddrMap,
can_instantiate: true,
deep_subelement_types: &[®, ®FILE, &FIELD, &SIGNAL],
properties: &[
PropertyMeta{name: "alignment", ty: PropertyType::U64},
PropertyMeta{name: "sharedextbus", ty: PropertyType::Boolean},
PropertyMeta{name: "errextbus", ty: PropertyType::Boolean},
PropertyMeta{name: "bigendian", ty: PropertyType::Boolean},
PropertyMeta{name: "littleendian", ty: PropertyType::Boolean},
PropertyMeta{name: "addressing", ty: PropertyType::AddressingType},
PropertyMeta{name: "rsvdset", ty: PropertyType::Boolean},
PropertyMeta{name: "rsvdsetX", ty: PropertyType::Boolean},
PropertyMeta{name: "msb0", ty: PropertyType::Boolean},
PropertyMeta{name: "lsb0", ty: PropertyType::Boolean},
],
};
static CONSTRAINT: ComponentMeta = ComponentMeta {
ty: ComponentType::Constraint,
can_instantiate: true,
deep_subelement_types: &[],
properties: &[],
};
static ENUM: ComponentMeta = ComponentMeta {
ty: ComponentType::Enum,
can_instantiate: false,
deep_subelement_types: &[],
properties: &[],
};
static ENUM_VARIANT: ComponentMeta = ComponentMeta {
ty: ComponentType::EnumVariant,
can_instantiate: false,
deep_subelement_types: &[],
properties: &[],
};
pub fn get_component_meta(component_type: ComponentType) -> &'static ComponentMeta {
let result = match component_type {
ComponentType::Field => &FIELD,
ComponentType::Reg => ®,
ComponentType::RegFile => ®FILE,
ComponentType::AddrMap => &ADDRMAP,
ComponentType::Signal => &SIGNAL,
ComponentType::Mem => &MEM,
ComponentType::Constraint => &CONSTRAINT,
ComponentType::Enum => &ENUM,
ComponentType::EnumVariant => &ENUM_VARIANT,
};
assert!(result.ty == component_type);
result
}
static ALL_COMPONENTS: [&ComponentMeta; 8] = [
&FIELD,
®,
®FILE,
&ADDRMAP,
&SIGNAL,
&MEM,
&ENUM,
&CONSTRAINT,
];
static GENERAL_PROPERTIES: [PropertyMeta; 2] = [
PropertyMeta {
name: "name",
ty: PropertyType::String,
},
PropertyMeta {
name: "desc",
ty: PropertyType::String,
},
];
pub(crate) fn property(
component_type: ComponentType,
name: &str,
) -> Result<'_, &'static PropertyMeta> {
if let Some(p) = GENERAL_PROPERTIES.iter().find(|m| m.name == name) {
return Ok(p);
}
if let Some(p) = get_component_meta(component_type)
.properties
.iter()
.find(|m| m.name == name)
{
return Ok(p);
}
Err(RdlError::UnknownPropertyName(name))
}
pub(crate) fn default_property(
scope_type: ScopeType,
name: &str,
) -> Result<'_, &'static PropertyMeta> {
if let Some(p) = GENERAL_PROPERTIES.iter().find(|m| m.name == name) {
return Ok(p);
}
let ScopeType::Component(component_type) = scope_type else {
for subcomponent_meta in ALL_COMPONENTS.iter() {
if let Some(p) = subcomponent_meta.properties.iter().find(|m| m.name == name) {
return Ok(p);
}
}
return Err(RdlError::UnknownPropertyName(name));
};
for subcomponent_meta in get_component_meta(component_type)
.deep_subelement_types
.iter()
{
if let Some(p) = subcomponent_meta.properties.iter().find(|m| m.name == name) {
return Ok(p);
}
}
Err(RdlError::UnknownPropertyName(name))
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/token.rs | systemrdl/src/token.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use crate::Bits;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Token<'a> {
Field,
External,
Reg,
RegFile,
AddrMap,
Signal,
Enum,
Mem,
Constraint,
BraceOpen,
BraceClose,
BracketOpen,
BracketClose,
ParenOpen,
ParenClose,
Semicolon,
Comma,
Period,
Equals,
NotEquals,
At,
Colon,
Hash,
Pointer,
PlusEqual,
PercentEqual,
QuestionMark,
And,
Identifier(&'a str),
StringLiteral(&'a str),
Number(u64),
Bits(Bits),
EndOfFile,
Skip,
PreprocInclude,
UnableToOpenFile(&'a str),
IncludeDepthLimitReached,
Error,
}
impl Token<'_> {
pub fn is_identifier(&self) -> bool {
matches!(self, Self::Identifier(_))
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/systemrdl/src/bin/parse.rs | systemrdl/src/bin/parse.rs | /*++
Licensed under the Apache-2.0 license.
--*/
use std::fmt::Write;
use std::{error::Error, path::PathBuf};
use caliptra_systemrdl::{ComponentType, EnumReference, FsFileSource, InstanceRef, ScopeType};
fn dimension_suffix(dimensions: &[u64]) -> String {
let mut result = String::new();
for dimension in dimensions {
write!(&mut result, "[{}]", dimension).unwrap();
}
result
}
fn print_instance(iref: InstanceRef, padding: &str) {
let inst = iref.instance;
match inst.scope.ty {
ScopeType::Component(ComponentType::Field) => {
println!(
"{}{}: field {}{}",
padding,
inst.offset.unwrap(),
inst.name,
dimension_suffix(&inst.dimension_sizes)
);
if let Ok(Some(EnumReference(eref))) = inst.scope.property_val_opt("encode") {
if let Some(enm) = iref.scope.lookup_typedef(&eref) {
println!("{} enum {}", padding, eref);
for variant in enm.instance_iter() {
print_instance(variant, &format!("{padding} "));
}
}
}
}
ScopeType::Component(ComponentType::Reg) => {
println!(
"{}{:#x?}: reg {}{}",
padding,
inst.offset.unwrap(),
inst.name,
dimension_suffix(&inst.dimension_sizes)
);
}
ScopeType::Component(ComponentType::RegFile) => {
println!(
"{}{:x?}: regfile {}{}",
padding,
inst.offset,
inst.name,
dimension_suffix(&inst.dimension_sizes)
);
}
ScopeType::Component(ComponentType::AddrMap) => {
println!(
"{}{:#x?}: addrmap {}{}",
padding,
inst.offset.unwrap(),
inst.name,
dimension_suffix(&inst.dimension_sizes)
);
}
ScopeType::Component(ComponentType::EnumVariant) => {
println!(
"{}{}: variant {}",
padding,
inst.reset.as_ref().unwrap().val(),
inst.name
);
}
_ => {}
}
for sub_inst in iref.scope.instance_iter() {
print_instance(sub_inst, &format!("{padding} "));
}
}
fn real_main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
Err("Usage: parse <file.rdl>...")?;
}
let files: Vec<PathBuf> = args[1..].iter().map(PathBuf::from).collect();
let fs = FsFileSource::new();
let scope = caliptra_systemrdl::Scope::parse_root(&fs, &files).map_err(|s| s.to_string())?;
let scope = scope.as_parent();
let addrmap = scope.lookup_typedef("clp").unwrap();
for inst in addrmap.instance_iter() {
print_instance(inst, "");
}
Ok(())
}
fn main() {
if let Err(err) = real_main() {
eprintln!("{}", err);
std::process::exit(1);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/verify/src/lib.rs | image/verify/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
Caliptra Image Verification library.
--*/
#![cfg_attr(not(feature = "std"), no_std)]
mod verifier;
use caliptra_drivers::*;
use caliptra_image_types::*;
use core::ops::Range;
pub use verifier::ImageVerifier;
pub const MAX_FIRMWARE_SVN: u32 = 128;
/// Image Verifification Executable Info
#[derive(Default, Debug)]
pub struct FirmwareSvnLogInfo {
pub manifest_svn: u32,
pub reserved: u32,
pub fuse_svn: u32,
}
/// Image Verification Executable Info
#[derive(Default, Debug)]
pub struct ImageVerificationExeInfo {
/// Load address
pub load_addr: u32,
/// Length
pub size: u32,
/// Entry Point
pub entry_point: u32,
/// Digest of the image
pub digest: ImageDigest384,
}
/// Information To Be Logged For The Verified Image
#[derive(Default, Debug)]
pub struct ImageVerificationLogInfo {
// ECC Vendor Public Key Index To Log
pub vendor_ecc_pub_key_idx: u32,
/// Vendor ECC Public Key Revocation Fuse
pub fuse_vendor_ecc_pub_key_revocation: VendorEccPubKeyRevocation,
// PQC (LMS or MLDSA) Vendor Public Key Index
pub vendor_pqc_pub_key_idx: u32,
/// Vendor PQC (LMS or MLDSA) Public Key Revocation Fuse
pub fuse_vendor_pqc_pub_key_revocation: u32,
/// Firmware's SVN logging information
pub fw_log_info: FirmwareSvnLogInfo,
}
/// Verified image information
#[derive(Default, Debug)]
pub struct ImageVerificationInfo {
/// Vendor ECC public key index
pub vendor_ecc_pub_key_idx: u32,
/// Vendor PQC (LMS or MLDSA) public key index
pub vendor_pqc_pub_key_idx: u32,
/// PQC Key Type
pub pqc_key_type: FwVerificationPqcKeyType,
/// Digest of owner public keys that verified the image
pub owner_pub_keys_digest: ImageDigest384,
/// Whether `owner_pub_keys_digest` was in fuses
pub owner_pub_keys_digest_in_fuses: bool,
/// The SVN for this firmware bundle
pub fw_svn: u32,
/// The effective fuse SVN for this firmware bundle
pub effective_fuse_svn: u32,
/// First mutable code
pub fmc: ImageVerificationExeInfo,
/// Runtime
pub runtime: ImageVerificationExeInfo,
/// Information Returned To Be Logged
pub log_info: ImageVerificationLogInfo,
}
/// Image Verification Environment
pub trait ImageVerificationEnv {
/// Calculate SHA-384 Digest
fn sha384_digest(&mut self, offset: u32, len: u32) -> CaliptraResult<ImageDigest384>;
/// Calculate SHA-512 Digest
fn sha512_digest(&mut self, offset: u32, len: u32) -> CaliptraResult<ImageDigest512>;
/// Calculate SHA-384 Digest with accelerator
fn sha384_acc_digest(
&mut self,
offset: u32,
len: u32,
digest_failure: CaliptraError,
) -> CaliptraResult<ImageDigest384>;
/// Calculate SHA-512 Digest with accelerator
fn sha512_acc_digest(
&mut self,
offset: u32,
len: u32,
digest_failure: CaliptraError,
) -> CaliptraResult<ImageDigest512>;
/// Perform ECC-384 Verification
fn ecc384_verify(
&mut self,
digest: &ImageDigest384,
pub_key: &ImageEccPubKey,
sig: &ImageEccSignature,
) -> CaliptraResult<Array4xN<12, 48>>;
/// Perform LMS Verification
fn lms_verify(
&mut self,
digest: &ImageDigest384,
pub_key: &ImageLmsPublicKey,
sig: &ImageLmsSignature,
) -> CaliptraResult<HashValue<SHA192_DIGEST_WORD_SIZE>>;
fn mldsa87_verify(
&mut self,
msg: &[u8],
pub_key: &ImageMldsaPubKey,
sig: &ImageMldsaSignature,
) -> CaliptraResult<Mldsa87Result>;
/// Get Vendor Public Key Digest from fuses
fn vendor_pub_key_info_digest_fuses(&self) -> ImageDigest384;
/// Get Vendor ECC Public Key Revocation list
fn vendor_ecc_pub_key_revocation(&self) -> VendorEccPubKeyRevocation;
/// Get Vendor LMS Public Key Revocation list
fn vendor_lms_pub_key_revocation(&self) -> u32;
/// Get Vendor MLDSA Public Key Revocation list
fn vendor_mldsa_pub_key_revocation(&self) -> u32;
/// Get Owner Public Key Digest from fuses
fn owner_pub_key_digest_fuses(&self) -> ImageDigest384;
/// Get Anti-Rollback disable setting
fn anti_rollback_disable(&self) -> bool;
// Get Device Lifecycle state
fn dev_lifecycle(&self) -> Lifecycle;
// Get the vendor ECC key index saved on cold boot in data vault
fn vendor_ecc_pub_key_idx_dv(&self) -> u32;
// Get the vendor PQC (LMS or MLDSA) key index saved on cold boot in data vault
fn vendor_pqc_pub_key_idx_dv(&self) -> u32;
// Get the owner key digest saved on cold boot in data vault
fn owner_pub_key_digest_dv(&self) -> ImageDigest384;
// Save the fmc digest in the data vault on cold boot
fn get_fmc_digest_dv(&self) -> ImageDigest384;
// Get FW SVN fuse value
fn fw_fuse_svn(&self) -> u32;
// ICCM Range
fn iccm_range(&self) -> Range<u32>;
// Set the extended error code
fn set_fw_extended_error(&mut self, err: u32);
// Get the PQC Key Type from the fuse.
fn pqc_key_type_fuse(&self) -> CaliptraResult<FwVerificationPqcKeyType>;
fn dot_owner_pk_hash(&self) -> Option<&ImageDigest384>;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/verify/src/verifier.rs | image/verify/src/verifier.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
verifier.rs
Abstract:
This file is the main implementation of Caliptra Image Verifier.
--*/
use core::num::NonZeroU32;
use crate::*;
#[cfg(all(not(test), not(feature = "no-cfi")))]
use caliptra_cfi_derive::cfi_impl_fn;
use caliptra_cfi_lib::{
cfi_assert, cfi_assert_bool, cfi_assert_eq, cfi_assert_ge, cfi_assert_ne, cfi_launder,
};
use caliptra_drivers::*;
use caliptra_image_types::*;
use memoffset::{offset_of, span_of};
use zerocopy::{FromBytes, IntoBytes};
const ZERO_DIGEST: &ImageDigest384 = &[0u32; SHA384_DIGEST_WORD_SIZE];
/// PQC public key and signature
enum PqcKeyInfo<'a> {
Lms(&'a ImageLmsPublicKey, &'a ImageLmsSignature),
Mldsa(&'a ImageMldsaPubKey, &'a ImageMldsaSignature),
}
/// Header Info
struct HeaderInfo<'a> {
vendor_ecc_pub_key_idx: u32,
vendor_pqc_pub_key_idx: u32,
vendor_ecc_pub_key_revocation: VendorEccPubKeyRevocation,
vendor_ecc_info: (&'a ImageEccPubKey, &'a ImageEccSignature),
vendor_pqc_info: PqcKeyInfo<'a>,
vendor_pqc_pub_key_revocation: u32,
owner_ecc_info: (&'a ImageEccPubKey, &'a ImageEccSignature),
owner_pqc_info: PqcKeyInfo<'a>,
owner_pub_keys_digest: ImageDigest384,
owner_pub_keys_digest_in_fuses: bool,
}
/// TOC Info
struct TocInfo<'a> {
len: u32,
digest: &'a ImageDigest384,
}
/// Image Info
struct ImageInfo<'a> {
fmc: &'a ImageTocEntry,
runtime: &'a ImageTocEntry,
}
/// Image Verifier
pub struct ImageVerifier<Env: ImageVerificationEnv> {
/// Verification Environment
env: Env,
}
impl<Env: ImageVerificationEnv> ImageVerifier<Env> {
/// Create a new instance `ImageVerifier`
///
/// # Arguments
///
/// * `env` - Environment
pub fn new(env: Env) -> Self {
Self { env }
}
/// Verify Caliptra image
///
/// # Arguments
///
/// * `manifest` - Image Manifest
/// * `image` - Image to verify
/// * `reason` - Reset Reason
///
/// # Returns
///
/// * `ImageVerificationInfo` - Image verification information success
#[cfg_attr(all(not(test), not(feature = "no-cfi")), cfi_impl_fn)]
#[inline(never)]
pub fn verify(
&mut self,
manifest: &ImageManifest,
img_bundle_sz: u32,
reason: ResetReason,
) -> CaliptraResult<ImageVerificationInfo> {
// Check if manifest has required marker
if manifest.marker != MANIFEST_MARKER {
Err(CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_MARKER_MISMATCH)?;
}
// Check if manifest size is valid
if manifest.size as usize != core::mem::size_of::<ImageManifest>() {
Err(CaliptraError::IMAGE_VERIFIER_ERR_MANIFEST_SIZE_MISMATCH)?;
}
// Check if the PQC key type is valid.
let pqc_key_type = FwVerificationPqcKeyType::from_u8(manifest.pqc_key_type)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_INVALID)?;
// Check if the PQC key type matches the fuse value. Skip this check if unprovisioned.
if self.env.dev_lifecycle() != Lifecycle::Unprovisioned {
let pqc_key_type_fuse = self.env.pqc_key_type_fuse()?;
if pqc_key_type != pqc_key_type_fuse {
Err(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_TYPE_MISMATCH)?;
}
}
// Verify the preamble
let preamble = &manifest.preamble;
let header_info = self.verify_preamble(preamble, reason, pqc_key_type);
let header_info = okref(&header_info)?;
// Verify Header
let header = &manifest.header;
let toc_info = self.verify_header(header, header_info);
let toc_info = okref(&toc_info)?;
// Verify TOC
let image_info = self.verify_toc(manifest, toc_info, img_bundle_sz);
let image_info = okref(&image_info)?;
// Verify FMC
let fmc_info = self.verify_fmc(image_info.fmc, reason)?;
// Verify Runtime
let runtime_info = self.verify_runtime(image_info.runtime)?;
self.verify_svn(manifest.header.svn)?;
let effective_fuse_svn = self.effective_fuse_svn();
let info = ImageVerificationInfo {
vendor_ecc_pub_key_idx: header_info.vendor_ecc_pub_key_idx,
vendor_pqc_pub_key_idx: header_info.vendor_pqc_pub_key_idx,
owner_pub_keys_digest: header_info.owner_pub_keys_digest,
owner_pub_keys_digest_in_fuses: header_info.owner_pub_keys_digest_in_fuses,
fmc: fmc_info,
runtime: runtime_info,
fw_svn: manifest.header.svn,
effective_fuse_svn,
log_info: ImageVerificationLogInfo {
vendor_ecc_pub_key_idx: header_info.vendor_ecc_pub_key_idx,
fuse_vendor_ecc_pub_key_revocation: header_info.vendor_ecc_pub_key_revocation,
fuse_vendor_pqc_pub_key_revocation: header_info.vendor_pqc_pub_key_revocation,
vendor_pqc_pub_key_idx: header_info.vendor_pqc_pub_key_idx,
fw_log_info: FirmwareSvnLogInfo {
manifest_svn: manifest.header.svn,
reserved: 0,
fuse_svn: self.env.fw_fuse_svn(),
},
},
pqc_key_type,
};
Ok(info)
}
/// If an SVN check is required, verifies that the given SVN is greater than
/// or equal to the fuse SVN.
fn verify_svn(&mut self, fw_svn: u32) -> CaliptraResult<()> {
if self.svn_check_required() {
if fw_svn > MAX_FIRMWARE_SVN {
Err(CaliptraError::IMAGE_VERIFIER_ERR_FIRMWARE_SVN_GREATER_THAN_MAX_SUPPORTED)?;
}
if cfi_launder(fw_svn) < self.env.fw_fuse_svn() {
Err(CaliptraError::IMAGE_VERIFIER_ERR_FIRMWARE_SVN_LESS_THAN_FUSE)?;
} else {
cfi_assert_ge(fw_svn, self.env.fw_fuse_svn());
}
}
Ok(())
}
/// Calculates the effective fuse SVN.
///
/// If anti-rollback is disabled, the effective fuse-SVN is zero.
/// Otherwise, it is the value in fuses.
fn effective_fuse_svn(&mut self) -> u32 {
if cfi_launder(self.env.anti_rollback_disable()) {
cfi_assert!(self.env.anti_rollback_disable());
0_u32
} else {
cfi_assert!(!self.env.anti_rollback_disable());
self.env.fw_fuse_svn()
}
}
/// Verify Preamble
#[cfg_attr(all(not(test), not(feature = "no-cfi")), cfi_impl_fn)]
fn verify_preamble<'a>(
&mut self,
preamble: &'a ImagePreamble,
reason: ResetReason,
pqc_key_type: FwVerificationPqcKeyType,
) -> CaliptraResult<HeaderInfo<'a>> {
// Verify Vendor Public Key Info Digest
self.verify_vendor_pub_key_info_digest(preamble, pqc_key_type)?;
// Verify Owner Public Key Info Digest
let (owner_pub_keys_digest, owner_pub_keys_digest_in_fuses) =
self.verify_owner_pk_digest(reason)?;
// Verify ECC Vendor Key Index
let (vendor_ecc_pub_key_idx, vendor_ecc_pub_key_revocation) =
self.verify_vendor_ecc_pk_idx(preamble, reason)?;
// ECC Vendor Information
let vendor_ecc_info = (
&preamble.vendor_ecc_active_pub_key,
&preamble.vendor_sigs.ecc_sig,
);
struct PubKeyIndexInfo {
key_idx: u32,
key_revocation: u32,
}
// Verify PQC Vendor Key Index
let vendor_pqc_info: PqcKeyInfo<'a>;
let vendor_pqc_pub_key_idx_info = match pqc_key_type {
FwVerificationPqcKeyType::LMS => {
// Read the LMS public key and signature from the preamble
let (lms_pub_key, _) = ImageLmsPublicKey::ref_from_prefix(
preamble.vendor_pqc_active_pub_key.0.as_bytes(),
)
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_LMS_VENDOR_PUB_KEY_INVALID,
))?;
let (lms_sig, _) =
ImageLmsSignature::ref_from_prefix(preamble.vendor_sigs.pqc_sig.0.as_bytes())
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_LMS_VENDOR_SIG_INVALID,
))?;
vendor_pqc_info = PqcKeyInfo::Lms(lms_pub_key, lms_sig);
// Verify the vendor LMS public key index and revocation status
let key_revocation = self.env.vendor_lms_pub_key_revocation();
let vendor_pqc_pub_key_idx =
self.verify_vendor_pqc_pk_idx(preamble, reason, key_revocation)?;
// Return the public key index information
PubKeyIndexInfo {
key_idx: vendor_pqc_pub_key_idx,
key_revocation,
}
}
FwVerificationPqcKeyType::MLDSA => {
let (mldsa_pub_key, _) = ImageMldsaPubKey::ref_from_prefix(
preamble.vendor_pqc_active_pub_key.0.as_bytes(),
)
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_VENDOR_PUB_KEY_READ_FAILED,
))?;
let (mldsa_sig, _) =
ImageMldsaSignature::ref_from_prefix(preamble.vendor_sigs.pqc_sig.0.as_bytes())
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_VENDOR_SIG_READ_FAILED,
))?;
vendor_pqc_info = PqcKeyInfo::Mldsa(mldsa_pub_key, mldsa_sig);
// Verify the vendor MLDSA public key index and revocation status
let key_revocation = self.env.vendor_mldsa_pub_key_revocation();
let vendor_pqc_pub_key_idx =
self.verify_vendor_pqc_pk_idx(preamble, reason, key_revocation)?;
// Return the public key index information
PubKeyIndexInfo {
key_idx: vendor_pqc_pub_key_idx,
key_revocation,
}
}
};
// Owner Information
let owner_ecc_info = (
&preamble.owner_pub_keys.ecc_pub_key,
&preamble.owner_sigs.ecc_sig,
);
let owner_pqc_info: PqcKeyInfo<'a> = match pqc_key_type {
FwVerificationPqcKeyType::LMS => {
let (lms_pub_key, _) = ImageLmsPublicKey::ref_from_prefix(
preamble.owner_pub_keys.pqc_pub_key.0.as_bytes(),
)
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_LMS_OWNER_PUB_KEY_INVALID,
))?;
let (lms_sig, _) =
ImageLmsSignature::ref_from_prefix(preamble.owner_sigs.pqc_sig.0.as_bytes())
.or(Err(CaliptraError::IMAGE_VERIFIER_ERR_LMS_OWNER_SIG_INVALID))?;
PqcKeyInfo::Lms(lms_pub_key, lms_sig)
}
FwVerificationPqcKeyType::MLDSA => {
let (mldsa_pub_key, _) = ImageMldsaPubKey::ref_from_prefix(
preamble.owner_pub_keys.pqc_pub_key.0.as_bytes(),
)
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_OWNER_PUB_KEY_READ_FAILED,
))?;
let (mldsa_sig, _) =
ImageMldsaSignature::ref_from_prefix(preamble.owner_sigs.pqc_sig.0.as_bytes())
.or(Err(
CaliptraError::IMAGE_VERIFIER_ERR_MLDSA_OWNER_SIG_READ_FAILED,
))?;
PqcKeyInfo::Mldsa(mldsa_pub_key, mldsa_sig)
}
};
let info = HeaderInfo {
vendor_ecc_pub_key_idx,
vendor_pqc_pub_key_idx: vendor_pqc_pub_key_idx_info.key_idx,
vendor_ecc_info,
vendor_pqc_info,
owner_pqc_info,
owner_pub_keys_digest,
owner_pub_keys_digest_in_fuses,
owner_ecc_info,
vendor_ecc_pub_key_revocation,
vendor_pqc_pub_key_revocation: vendor_pqc_pub_key_idx_info.key_revocation,
};
Ok(info)
}
/// Verify Vendor ECC Public Key Index
fn verify_vendor_ecc_pk_idx(
&mut self,
preamble: &ImagePreamble,
reason: ResetReason,
) -> CaliptraResult<(u32, VendorEccPubKeyRevocation)> {
let key_idx = preamble.vendor_ecc_pub_key_idx;
let revocation = self.env.vendor_ecc_pub_key_revocation();
let key_hash_count = preamble
.vendor_pub_key_info
.ecc_key_descriptor
.key_hash_count;
let last_key_idx: u32 = key_hash_count as u32 - 1;
// Check if the key index is within bounds.
if key_idx > last_key_idx {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS)?;
}
// Check if key idx is the last key index. Last key index is never revoked.
if key_idx == last_key_idx {
cfi_assert_eq(cfi_launder(key_idx), last_key_idx);
} else {
let key = VendorEccPubKeyRevocation::from_bits_truncate(0x01u32 << key_idx);
if cfi_launder(revocation).contains(cfi_launder(key)) {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_REVOKED)?;
} else {
cfi_assert!(!revocation.contains(key));
}
}
if cfi_launder(reason) == ResetReason::UpdateReset {
let expected = self.env.vendor_ecc_pub_key_idx_dv();
if cfi_launder(expected) != key_idx {
Err(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_ECC_PUB_KEY_IDX_MISMATCH,
)?;
} else {
cfi_assert_eq(self.env.vendor_ecc_pub_key_idx_dv(), key_idx);
}
} else {
cfi_assert_ne(reason, ResetReason::UpdateReset);
}
Ok((key_idx, revocation))
}
/// Verify Vendor PQC (LMS or MLDSA) Public Key Index
fn verify_vendor_pqc_pk_idx(
&mut self,
preamble: &ImagePreamble,
reason: ResetReason,
revocation: u32,
) -> CaliptraResult<u32> {
let key_idx = preamble.vendor_pqc_pub_key_idx;
let key_hash_count = preamble
.vendor_pub_key_info
.pqc_key_descriptor
.key_hash_count;
let last_key_idx: u32 = key_hash_count as u32 - 1;
// Check if the key index is within bounds.
if key_idx > last_key_idx {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS)?;
}
// Check if key idx is the last key index. Last key index is never revoked.
if key_idx == last_key_idx {
cfi_assert_eq(cfi_launder(key_idx), last_key_idx);
} else if (cfi_launder(revocation) & (0x01u32 << key_idx)) != 0 {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_REVOKED)?;
} else {
cfi_assert_eq(revocation & (0x01u32 << key_idx), 0);
}
if cfi_launder(reason) == ResetReason::UpdateReset {
let expected = self.env.vendor_pqc_pub_key_idx_dv();
if cfi_launder(expected) != key_idx {
Err(
CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_VENDOR_PQC_PUB_KEY_IDX_MISMATCH,
)?;
} else {
cfi_assert_eq(self.env.vendor_pqc_pub_key_idx_dv(), key_idx);
}
} else {
cfi_assert_ne(reason, ResetReason::UpdateReset);
}
Ok(key_idx)
}
/// Verify vendor public key info digest
fn verify_vendor_pub_key_info_digest(
&mut self,
preamble: &ImagePreamble,
pqc_key_type: FwVerificationPqcKeyType,
) -> Result<(), NonZeroU32> {
// We skip vendor public key check in unprovisioned state
if cfi_launder(self.env.dev_lifecycle() as u32) == Lifecycle::Unprovisioned as u32 {
cfi_assert_eq(
self.env.dev_lifecycle() as u32,
Lifecycle::Unprovisioned as u32,
);
return Ok(());
} else {
cfi_assert_ne(
self.env.dev_lifecycle() as u32,
Lifecycle::Unprovisioned as u32,
);
}
// Read expected value from the fuses
let expected = &self.env.vendor_pub_key_info_digest_fuses();
// Vendor public key digest from the fuses must never be zero
if cfi_launder(expected) == ZERO_DIGEST {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_INVALID)?;
} else {
cfi_assert_ne(expected, ZERO_DIGEST);
}
let pub_key_info = preamble.vendor_pub_key_info;
// Validate the ECC key descriptor.
if pub_key_info.ecc_key_descriptor.version != KEY_DESCRIPTOR_VERSION {
Err(CaliptraError::IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_VERSION_MISMATCH)?;
}
if pub_key_info.ecc_key_descriptor.key_hash_count == 0 {
Err(CaliptraError::IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_INVALID_HASH_COUNT)?;
}
if pub_key_info.ecc_key_descriptor.key_hash_count > VENDOR_ECC_MAX_KEY_COUNT as u8 {
Err(CaliptraError::IMAGE_VERIFIER_ERR_ECC_KEY_DESCRIPTOR_HASH_COUNT_GT_MAX)?;
}
// Validate the PQC key descriptor.
if pub_key_info.pqc_key_descriptor.version != KEY_DESCRIPTOR_VERSION {
Err(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_VERSION_MISMATCH)?;
}
if pub_key_info.pqc_key_descriptor.key_type != pqc_key_type as u8 {
Err(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_TYPE_MISMATCH)?;
}
if pub_key_info.pqc_key_descriptor.key_hash_count == 0 {
Err(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_INVALID_HASH_COUNT)?;
}
if (pqc_key_type == FwVerificationPqcKeyType::LMS
&& pub_key_info.pqc_key_descriptor.key_hash_count > VENDOR_LMS_MAX_KEY_COUNT as u8)
|| (pqc_key_type == FwVerificationPqcKeyType::MLDSA
&& pub_key_info.pqc_key_descriptor.key_hash_count
> VENDOR_MLDSA_MAX_KEY_COUNT as u8)
{
Err(CaliptraError::IMAGE_VERIFIER_ERR_PQC_KEY_DESCRIPTOR_HASH_COUNT_GT_MAX)?;
}
let range = ImageManifest::vendor_pub_key_descriptors_range();
#[cfg(feature = "fips-test-hooks")]
unsafe {
caliptra_drivers::FipsTestHook::update_hook_cmd_if_hook_set(
caliptra_drivers::FipsTestHook::FW_LOAD_VENDOR_PUB_KEY_DIGEST_FAILURE,
caliptra_drivers::FipsTestHook::SHA384_DIGEST_FAILURE,
)
};
let actual = &self.env.sha384_acc_digest(
range.start,
range.len() as u32,
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_FAILURE,
)?;
if cfi_launder(expected) != actual {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_MISMATCH)?;
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(expected, actual);
}
self.verify_active_ecc_pub_key_digest(preamble)?;
self.verify_active_pqc_pub_key_digest(preamble, pqc_key_type)?;
Ok(())
}
fn verify_active_ecc_pub_key_digest(&mut self, preamble: &ImagePreamble) -> CaliptraResult<()> {
let pub_key_info = preamble.vendor_pub_key_info;
let ecc_key_idx = preamble.vendor_ecc_pub_key_idx;
let expected = pub_key_info
.ecc_key_descriptor
.key_hash
.get(ecc_key_idx as usize)
.ok_or(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_OUT_OF_BOUNDS)?;
let range = {
let offset = offset_of!(ImageManifest, preamble) as u32;
let span = span_of!(ImagePreamble, vendor_ecc_active_pub_key);
span.start as u32 + offset..span.end as u32 + offset
};
let actual = &self.env.sha384_acc_digest(
range.start,
range.len() as u32,
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_FAILURE,
)?;
if cfi_launder(expected) != actual {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_DIGEST_MISMATCH)?;
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(expected, actual);
}
Ok(())
}
fn verify_active_pqc_pub_key_digest(
&mut self,
preamble: &ImagePreamble,
pqc_key_type: FwVerificationPqcKeyType,
) -> CaliptraResult<()> {
let pub_key_info = preamble.vendor_pub_key_info;
let pqc_key_idx = preamble.vendor_pqc_pub_key_idx;
let expected = pub_key_info
.pqc_key_descriptor
.key_hash
.get(pqc_key_idx as usize);
if expected.is_none()
|| (pqc_key_type == FwVerificationPqcKeyType::LMS
&& pqc_key_idx >= VENDOR_LMS_MAX_KEY_COUNT)
|| (pqc_key_type == FwVerificationPqcKeyType::MLDSA
&& pqc_key_idx >= VENDOR_MLDSA_MAX_KEY_COUNT)
{
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_OUT_OF_BOUNDS)?
}
let expected = expected.unwrap();
let start = {
let offset = offset_of!(ImageManifest, preamble) as u32;
let span = span_of!(ImagePreamble, vendor_pqc_active_pub_key);
span.start as u32 + offset
};
let size = if pqc_key_type == FwVerificationPqcKeyType::MLDSA {
MLDSA87_PUB_KEY_BYTE_SIZE
} else {
LMS_PUB_KEY_BYTE_SIZE
} as u32;
let actual = &self.env.sha384_acc_digest(
start,
size,
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PUB_KEY_DIGEST_FAILURE,
)?;
if cfi_launder(expected) != actual {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_DIGEST_MISMATCH)?;
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(expected, actual);
}
Ok(())
}
/// Verify owner public key digest.
/// Returns a bool indicating whether the digest was in fuses.
fn verify_owner_pk_digest(
&mut self,
reason: ResetReason,
) -> CaliptraResult<(ImageDigest384, bool)> {
let range = ImageManifest::owner_pub_key_range();
#[cfg(feature = "fips-test-hooks")]
unsafe {
caliptra_drivers::FipsTestHook::update_hook_cmd_if_hook_set(
caliptra_drivers::FipsTestHook::FW_LOAD_OWNER_PUB_KEY_DIGEST_FAILURE,
caliptra_drivers::FipsTestHook::SHA384_DIGEST_FAILURE,
)
};
let actual = &self.env.sha384_acc_digest(
range.start,
range.len() as u32,
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_FAILURE,
)?;
let fuses_digest = &self.env.owner_pub_key_digest_fuses();
if fuses_digest == ZERO_DIGEST {
if let Some(dot_owner_pk_hash) = self.env.dot_owner_pk_hash() {
// If the dot owner public key hash is set, compare it with the actual digest.
if dot_owner_pk_hash != actual {
return Err(
CaliptraError::IMAGE_VERIFIER_ERR_DOT_OWNER_PUB_KEY_DIGEST_MISMATCH,
);
}
}
caliptra_cfi_lib::cfi_assert_eq_12_words(fuses_digest, ZERO_DIGEST);
} else if fuses_digest != actual {
return Err(CaliptraError::IMAGE_VERIFIER_ERR_OWNER_PUB_KEY_DIGEST_MISMATCH);
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(fuses_digest, actual);
}
if cfi_launder(reason) == ResetReason::UpdateReset {
let cold_boot_digest = &self.env.owner_pub_key_digest_dv();
if cfi_launder(cold_boot_digest) != actual {
return Err(CaliptraError::IMAGE_VERIFIER_ERR_UPDATE_RESET_OWNER_DIGEST_FAILURE);
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(cold_boot_digest, actual);
}
} else {
cfi_assert_ne(reason, ResetReason::UpdateReset);
}
Ok((*actual, fuses_digest != ZERO_DIGEST))
}
/// Verify Header
#[cfg_attr(all(not(test), not(feature = "no-cfi")), cfi_impl_fn)]
fn verify_header<'a>(
&mut self,
header: &'a ImageHeader,
info: &HeaderInfo,
) -> CaliptraResult<TocInfo<'a>> {
// Calculate the digest for the header
let range = ImageManifest::header_range();
let vendor_header_len = offset_of!(ImageHeader, owner_data);
#[cfg(feature = "fips-test-hooks")]
unsafe {
caliptra_drivers::FipsTestHook::update_hook_cmd_if_hook_set(
caliptra_drivers::FipsTestHook::FW_LOAD_HEADER_DIGEST_FAILURE,
caliptra_drivers::FipsTestHook::SHA384_DIGEST_FAILURE,
)
};
// Vendor header digest is calculated up to the owner_data field.
let vendor_digest_384 = self.env.sha384_acc_digest(
range.start,
vendor_header_len as u32,
CaliptraError::IMAGE_VERIFIER_ERR_HEADER_DIGEST_FAILURE,
)?;
let mut vendor_signdata_holder = ImageSignData {
digest_384: &vendor_digest_384,
mldsa_msg: None,
};
let owner_digest_384 = self.env.sha384_acc_digest(
range.start,
range.len() as u32,
CaliptraError::IMAGE_VERIFIER_ERR_HEADER_DIGEST_FAILURE,
)?;
let mut owner_signdata_holder = ImageSignData {
digest_384: &owner_digest_384,
mldsa_msg: None,
};
// Update vendor_signdata_holder and owner_signdata_holder with data if MLDSA validation is required.
if let PqcKeyInfo::Mldsa(_, _) = info.vendor_pqc_info {
vendor_signdata_holder.mldsa_msg =
Some(header.as_bytes().get(..vendor_header_len).unwrap());
owner_signdata_holder.mldsa_msg = Some(header.as_bytes());
}
// Verify vendor signatures.
self.verify_vendor_sig(
&vendor_signdata_holder,
info.vendor_ecc_info,
&info.vendor_pqc_info,
)?;
// Verify the ECC public key index used to verify header signature is encoded
// in the header
if cfi_launder(header.vendor_ecc_pub_key_idx) != info.vendor_ecc_pub_key_idx {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INDEX_MISMATCH)?;
} else {
cfi_assert_eq(header.vendor_ecc_pub_key_idx, info.vendor_ecc_pub_key_idx);
}
// Verify the PQC (LMS or MLDSA) public key index used to verify header signature is encoded
// in the header
if cfi_launder(header.vendor_pqc_pub_key_idx) != info.vendor_pqc_pub_key_idx {
return Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_PQC_PUB_KEY_INDEX_MISMATCH);
} else {
cfi_assert_eq(header.vendor_pqc_pub_key_idx, info.vendor_pqc_pub_key_idx);
}
// Verify owner signatures.
self.verify_owner_sig(
&owner_signdata_holder,
info.owner_ecc_info,
&info.owner_pqc_info,
)?;
let verif_info = TocInfo {
len: header.toc_len,
digest: &header.toc_digest,
};
Ok(verif_info)
}
/// Verify Owner Signature
// Inlined to reduce ROM size
#[inline(always)]
fn verify_ecc_sig(
&mut self,
digest: &ImageDigest384,
pub_key: &ImageEccPubKey,
sig: &ImageEccSignature,
is_owner: bool,
) -> CaliptraResult<()> {
let (signature_invalid, pub_key_invalid_arg, sig_invalid_arg) = if is_owner {
(
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID,
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_PUB_KEY_INVALID_ARG,
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_SIGNATURE_INVALID_ARG,
)
} else {
(
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID,
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INVALID_ARG,
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID_ARG,
)
};
if &pub_key.x == ZERO_DIGEST || &pub_key.y == ZERO_DIGEST {
return Err(pub_key_invalid_arg);
}
if &sig.r == ZERO_DIGEST || &sig.s == ZERO_DIGEST {
return Err(sig_invalid_arg);
}
#[cfg(feature = "fips-test-hooks")]
unsafe {
let fips_verify_failure = if is_owner {
caliptra_drivers::FipsTestHook::FW_LOAD_OWNER_ECC_VERIFY_FAILURE
} else {
caliptra_drivers::FipsTestHook::FW_LOAD_VENDOR_ECC_VERIFY_FAILURE
};
caliptra_drivers::FipsTestHook::update_hook_cmd_if_hook_set(
fips_verify_failure,
caliptra_drivers::FipsTestHook::ECC384_VERIFY_FAILURE,
)
};
let verify_r = self
.env
.ecc384_verify(digest, pub_key, sig)
.map_err(|err| {
self.env.set_fw_extended_error(err.into());
if is_owner {
CaliptraError::IMAGE_VERIFIER_ERR_OWNER_ECC_VERIFY_FAILURE
} else {
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_VERIFY_FAILURE
}
})?;
if cfi_launder(verify_r) != caliptra_drivers::Array4xN(sig.r) {
return Err(signature_invalid);
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(&verify_r.0, &sig.r);
}
Ok(())
}
/// Verify Vendor Signature
fn verify_vendor_sig(
&mut self,
digest_holder: &ImageSignData,
ecc_info: (&ImageEccPubKey, &ImageEccSignature),
pqc_info: &PqcKeyInfo,
) -> CaliptraResult<()> {
let (ecc_pub_key, ecc_sig) = ecc_info;
if &ecc_pub_key.x == ZERO_DIGEST || &ecc_pub_key.y == ZERO_DIGEST {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_PUB_KEY_INVALID_ARG)?;
}
if &ecc_sig.r == ZERO_DIGEST || &ecc_sig.s == ZERO_DIGEST {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID_ARG)?;
}
#[cfg(feature = "fips-test-hooks")]
unsafe {
caliptra_drivers::FipsTestHook::update_hook_cmd_if_hook_set(
caliptra_drivers::FipsTestHook::FW_LOAD_VENDOR_ECC_VERIFY_FAILURE,
caliptra_drivers::FipsTestHook::ECC384_VERIFY_FAILURE,
)
};
let verify_r = self
.env
.ecc384_verify(digest_holder.digest_384, ecc_pub_key, ecc_sig)
.map_err(|err| {
self.env.set_fw_extended_error(err.into());
CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_VERIFY_FAILURE
})?;
if cfi_launder(verify_r) != caliptra_drivers::Array4xN(ecc_sig.r) {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_ECC_SIGNATURE_INVALID)?;
} else {
caliptra_cfi_lib::cfi_assert_eq_12_words(&verify_r.0, &ecc_sig.r);
}
// Verify PQC signature.
match pqc_info {
PqcKeyInfo::Lms(lms_pub_key, lms_sig) => {
self.verify_lms_sig(digest_holder.digest_384, lms_pub_key, lms_sig, false)?;
}
PqcKeyInfo::Mldsa(mldsa_pub_key, mldsa_sig) => {
if let Some(mldsa_msg) = digest_holder.mldsa_msg {
self.verify_mldsa_sig(mldsa_msg, mldsa_pub_key, mldsa_sig, false)?;
} else {
Err(CaliptraError::IMAGE_VERIFIER_ERR_VENDOR_MLDSA_MSG_MISSING)?;
}
}
}
Ok(())
}
fn verify_owner_sig(
&mut self,
digest_holder: &ImageSignData,
ecc_info: (&ImageEccPubKey, &ImageEccSignature),
pqc_info: &PqcKeyInfo,
) -> CaliptraResult<()> {
// Verify owner ECC signature
let (ecc_pub_key, ecc_sig) = ecc_info;
self.verify_ecc_sig(digest_holder.digest_384, ecc_pub_key, ecc_sig, true)?;
// Verify owner PQC signature
match pqc_info {
PqcKeyInfo::Lms(lms_pub_key, lms_sig) => {
self.verify_lms_sig(digest_holder.digest_384, lms_pub_key, lms_sig, true)?;
}
PqcKeyInfo::Mldsa(mldsa_pub_key, mldsa_sig) => {
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/verify/fuzz/src/fuzz_target_common.rs | image/verify/fuzz/src/fuzz_target_common.rs | // Licensed under the Apache-2.0 license
#[cfg(not(feature = "struct-aware"))]
use std::mem::size_of;
use caliptra_common::memory_layout::*;
use caliptra_drivers::*;
use caliptra_image_types::*;
use caliptra_image_verify::*;
use core::ops::Range;
#[cfg(feature = "struct-aware")]
const IMAGE_BUNDLE_SIZE: u32 = 131072;
/*
* NOTE: Copied from image/verify/src/verifier.rs, unable to import.
* - Possibly, because it is a required parameter for creating the object.
* - But not an inherent issue, will likely implement/wrap an appropriate environment.
*
* TODO: Is this environment no-op tests, or sufficiently extensive?
* - Ensures bundle is being fuzzed well (by offsets).
*/
struct TestEnv {
digest: ImageDigest384,
fmc_digest: ImageDigest384,
verify_result: bool,
verify_lms_result: bool,
vendor_pub_key_digest: ImageDigest384,
vendor_ecc_pub_key_revocation: VendorPubKeyRevocation,
vendor_lms_pub_key_revocation: u32,
owner_pub_key_digest: ImageDigest384,
lifecycle: Lifecycle,
}
impl Default for TestEnv {
fn default() -> Self {
TestEnv {
digest: ImageDigest384::default(),
fmc_digest: ImageDigest384::default(),
// PATCHED
verify_result: true,
// PATCHED
verify_lms_result: true,
vendor_pub_key_digest: ImageDigest384::default(),
vendor_ecc_pub_key_revocation: VendorPubKeyRevocation::default(),
vendor_lms_pub_key_revocation: 0,
owner_pub_key_digest: ImageDigest384::default(),
lifecycle: Lifecycle::Unprovisioned,
}
}
}
impl ImageVerificationEnv for TestEnv {
fn sha384_digest(&mut self, _offset: u32, _len: u32) -> CaliptraResult<ImageDigest384> {
Ok(self.digest)
}
fn ecc384_verify(
&mut self,
_digest: &ImageDigest384,
_pub_key: &ImageEccPubKey,
sig: &ImageEccSignature,
) -> CaliptraResult<Array4xN<12, 48>> {
if self.verify_result {
Ok(Array4x12::from(sig.r))
} else {
Ok(Array4x12::from(&[0xFF; 48]))
}
}
fn lms_verify(
&mut self,
_digest: &ImageDigest384,
pub_key: &ImageLmsPublicKey,
_sig: &ImageLmsSignature,
) -> CaliptraResult<HashValue<SHA192_DIGEST_WORD_SIZE>> {
if self.verify_lms_result {
Ok(HashValue::from(pub_key.digest))
} else {
Ok(HashValue::from(&[0xDEADBEEF; 6]))
}
}
fn vendor_pub_key_digest(&self) -> ImageDigest384 {
self.vendor_pub_key_digest
}
fn vendor_ecc_pub_key_revocation(&self) -> VendorPubKeyRevocation {
self.vendor_ecc_pub_key_revocation
}
fn vendor_lms_pub_key_revocation(&self) -> u32 {
self.vendor_lms_pub_key_revocation
}
fn owner_pub_key_digest_fuses(&self) -> ImageDigest384 {
self.owner_pub_key_digest
}
fn anti_rollback_disable(&self) -> bool {
false
}
fn dev_lifecycle(&self) -> Lifecycle {
self.lifecycle
}
fn vendor_ecc_pub_key_idx_dv(&self) -> u32 {
0
}
fn vendor_pqc_pub_key_idx_dv(&self) -> u32 {
0
}
fn owner_pub_key_digest_dv(&self) -> ImageDigest384 {
self.owner_pub_key_digest
}
fn get_fmc_digest_dv(&self) -> ImageDigest384 {
self.fmc_digest
}
fn iccm_range(&self) -> Range<u32> {
Range {
start: ICCM_ORG,
end: ICCM_ORG + ICCM_SIZE,
}
}
fn set_fw_extended_error(&mut self, _err: u32) {}
}
#[cfg(feature = "struct-aware")]
pub fn harness_structured(reset_reason: ResetReason, manifest: ImageManifest) {
let test_env = TestEnv::default();
let mut image_verifier = ImageVerifier::new(test_env);
//println!("{:?}", fuzz_bundle);
let _result = image_verifier.verify(&manifest, IMAGE_BUNDLE_SIZE, reset_reason);
//println!("{:?}", _result);
}
#[cfg(not(feature = "struct-aware"))]
pub fn harness_unstructured(reset_reason: ResetReason, data: &[u8]) {
let typed_fuzz_manifest: &ImageManifest;
// The null-case is too hard to fuzz (better statically)
// - Or, if we initialise with the `default()`, it's the test-case
if data.len() < size_of::<ImageManifest>() {
return;
}
unsafe {
typed_fuzz_manifest = &*(data.as_ptr() as *const ImageManifest);
}
let test_env = TestEnv::default();
let mut image_verifier = ImageVerifier::new(test_env);
//println!("{:?}", fuzz_bundle);
let _result = image_verifier.verify(
typed_fuzz_manifest,
data.len().try_into().unwrap(),
reset_reason,
);
//println!("{:?}", _result);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/verify/fuzz/src/fuzz_target_coldreset.rs | image/verify/fuzz/src/fuzz_target_coldreset.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(feature = "libfuzzer-sys", no_main)]
#[cfg(all(not(feature = "libfuzzer-sys"), not(feature = "afl")))]
compile_error!("Either feature \"libfuzzer-sys\" or \"afl\" must be enabled!");
#[cfg(feature = "libfuzzer-sys")]
use libfuzzer_sys::fuzz_target;
#[cfg(feature = "afl")]
use afl::fuzz;
// `arbitrary` is indirectly required by the `fuzz!` macro, but not imported by `derive`.
#[cfg(feature = "struct-aware")]
#[allow(unused_imports)]
use arbitrary::Arbitrary;
mod fuzz_target_common;
use caliptra_drivers::ResetReason::*;
#[cfg(feature = "struct-aware")]
use caliptra_image_types::ImageManifest;
#[cfg(feature = "struct-aware")]
use fuzz_target_common::harness_structured;
#[cfg(not(feature = "struct-aware"))]
use fuzz_target_common::harness_unstructured;
// cargo-fuzz target
#[cfg(all(feature = "libfuzzer-sys", not(feature = "struct-aware")))]
fuzz_target!(|data: &[u8]| {
harness_unstructured(ColdReset, data);
});
#[cfg(all(feature = "libfuzzer-sys", feature = "struct-aware"))]
fuzz_target!(|data: ImageManifest| {
harness_structured(ColdReset, data);
});
// cargo-afl target
#[cfg(all(feature = "afl", not(feature = "struct-aware")))]
fn main() {
fuzz!(|data: &[u8]| {
harness_unstructured(ColdReset, data);
});
}
#[cfg(all(feature = "afl", feature = "struct-aware"))]
fn main() {
fuzz!(|data: ImageManifest| {
harness_structured(ColdReset, data);
});
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/verify/fuzz/src/fuzz_target_updatereset.rs | image/verify/fuzz/src/fuzz_target_updatereset.rs | // Licensed under the Apache-2.0 license
#![cfg_attr(feature = "libfuzzer-sys", no_main)]
#[cfg(all(not(feature = "libfuzzer-sys"), not(feature = "afl")))]
compile_error!("Either feature \"libfuzzer-sys\" or \"afl\" must be enabled!");
#[cfg(feature = "libfuzzer-sys")]
use libfuzzer_sys::fuzz_target;
#[cfg(feature = "afl")]
use afl::fuzz;
// `arbitrary` is indirectly required by the `fuzz!` macro, but not imported by `derive`.
#[cfg(feature = "struct-aware")]
#[allow(unused_imports)]
use arbitrary::Arbitrary;
mod fuzz_target_common;
use caliptra_drivers::ResetReason::*;
#[cfg(feature = "struct-aware")]
use caliptra_image_types::ImageManifest;
#[cfg(feature = "struct-aware")]
use fuzz_target_common::harness_structured;
#[cfg(not(feature = "struct-aware"))]
use fuzz_target_common::harness_unstructured;
// cargo-fuzz target
#[cfg(all(feature = "libfuzzer-sys", not(feature = "struct-aware")))]
fuzz_target!(|data: &[u8]| {
harness_unstructured(ColdReset, data);
});
#[cfg(all(feature = "libfuzzer-sys", feature = "struct-aware"))]
fuzz_target!(|data: ImageManifest| {
harness_structured(ColdReset, data);
});
// cargo-afl target
#[cfg(all(feature = "afl", not(feature = "struct-aware")))]
fn main() {
fuzz!(|data: &[u8]| {
harness_unstructured(UpdateReset, data);
});
}
#[cfg(all(feature = "afl", feature = "struct-aware"))]
fn main() {
fuzz!(|data: ImageManifest| {
harness_structured(UpdateReset, data);
});
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/app/src/main.rs | image/app/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
Main entry point Caliptra Imaging application
--*/
use std::path::PathBuf;
use clap::{arg, value_parser, Command};
mod create;
/// Entry point
fn main() {
let sub_cmds = vec![Command::new("create")
.about("Create a new firmware image bundle")
.arg(
arg!(--"pqc-key-type" <U32> "Type of PQC key validation: 1: MLDSA; 3: LMS")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"key-config" <FILE> "Key Configuration file")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"ecc-pk-idx" <U32> "Vendor ECC Public Key Index")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"pqc-pk-idx" <U32> "Vendor PQC (LMS or MLDSA) Public Key Index")
.required(false)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"fmc" <FILE> "FMC ELF binary")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"fmc-rev" <SHA256HASH> "FMC GIT Revision")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"fmc-version" <U32> "FMC Firmware Version Number")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"rt" <FILE> "Runtime ELF binary")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"rt-rev" <SHA256HASH> "Runtime GIT Revision")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"rt-version" <U32> "Runtime Firmware Version Number")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"fw-svn" <U32> "Firmware Security Version Number")
.required(true)
.value_parser(value_parser!(u32)),
)
.arg(
arg!(--"out" <FILE> "Output file")
.required(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
arg!(--"own-from-date" <String> "Certificate Validity Start Date By Owner [YYYYMMDDHHMMSS - Zulu Time]")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"own-to-date" <String> "Certificate Validity End Date By Owner [YYYYMMDDHHMMSS - Zulu Time]")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"mfg-from-date" <String> "Certificate Validity Start Date By Manufacturer [YYYYMMDDHHMMSS - Zulu Time]")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"mfg-to-date" <String> "Certificate Validity End Date By Manufacturer [YYYYMMDDHHMMSS - Zulu Time]")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(--"print-hashes" "Print vendor and owner hashes").action(clap::ArgAction::SetTrue),
)
];
let cmd = Command::new("caliptra-image-app")
.arg_required_else_help(true)
.subcommands(sub_cmds)
.about("Caliptra firmware imaging tools")
.get_matches();
let result = match cmd.subcommand().unwrap() {
("create", args) => create::run_cmd(args),
(_, _) => unreachable!(),
};
result.unwrap();
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/app/src/create/config.rs | image/app/src/create/config.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
config.rs
Abstract:
File contains utilities for parsing configuration files
--*/
use anyhow::Context;
use serde_derive::{Deserialize, Serialize};
use std::path::PathBuf;
/// Vendor Key Configuration
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct VendorKeyConfig {
pub ecc_pub_keys: Vec<String>,
pub lms_pub_keys: Vec<String>,
pub mldsa_pub_keys: Vec<String>,
pub ecc_priv_keys: Option<Vec<String>>,
pub lms_priv_keys: Option<Vec<String>>,
pub mldsa_priv_keys: Option<Vec<String>>,
}
/// Owner Key Configuration
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct OwnerKeyConfig {
pub ecc_pub_key: String,
pub ecc_priv_key: Option<String>,
pub lms_pub_key: String,
pub lms_priv_key: Option<String>,
pub mldsa_pub_key: String,
pub mldsa_priv_key: Option<String>,
}
// Key Configuration
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct KeyConfig {
pub vendor: VendorKeyConfig,
pub owner: Option<OwnerKeyConfig>,
}
/// Load Key Configuration from file
pub(crate) fn load_key_config(path: &PathBuf) -> anyhow::Result<KeyConfig> {
let config_str = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read the config file {}", path.display()))?;
let config: KeyConfig = toml::from_str(&config_str)
.with_context(|| format!("Failed to parse config file {}", path.display()))?;
Ok(config)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/app/src/create/mod.rs | image/app/src/create/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mod.rs
Abstract:
File contains implementation Caliptra Image creation command.
--*/
mod config;
use anyhow::anyhow;
use anyhow::Context;
use caliptra_image_crypto::lms_priv_key_from_pem;
use caliptra_image_crypto::lms_pub_key_from_pem;
#[cfg(feature = "openssl")]
use caliptra_image_crypto::OsslCrypto as Crypto;
#[cfg(feature = "rustcrypto")]
use caliptra_image_crypto::RustCrypto as Crypto;
use caliptra_image_gen::*;
use caliptra_image_serde::ImageBundleWriter;
use caliptra_image_types::*;
use clap::ArgMatches;
use hex::ToHex;
use std::path::Path;
use std::path::PathBuf;
use zerocopy::IntoBytes;
use caliptra_image_elf::ElfExecutable;
use config::{OwnerKeyConfig, VendorKeyConfig};
use chrono::NaiveDate;
///
/// This function takes the string as the input
/// and extracts year, month and day from the string
/// and then performs some basic validity checks
///
fn check_date(from_date: &str, to_date: &str) -> anyhow::Result<bool> {
let time_fmt = "YYYYMMDDHHMMSS";
let current_date = chrono::Utc::now().date_naive();
if from_date.len() < time_fmt.len() || to_date.len() < time_fmt.len() {
return Err(anyhow!("Invalid Date Input Format"));
}
let from_date_str: &str = &from_date[0..8];
let to_date_str: &str = &to_date[0..8];
let from_date_in = match NaiveDate::parse_from_str(from_date_str, "%Y%m%d") {
Ok(d) => d,
Err(_) => return Err(anyhow!("Invalid From Date Input Format")),
};
let to_date_in = match NaiveDate::parse_from_str(to_date_str, "%Y%m%d") {
Ok(d) => d,
Err(_) => return Err(anyhow!("Invalid To Date Input Format")),
};
if from_date_in < current_date || to_date_in < current_date {
return Err(anyhow!("Invalid Input Date"));
}
if from_date_in > to_date_in {
return Err(anyhow!("From Date Is greater Than To Date"));
}
Ok(true)
}
/// Run the command
pub(crate) fn run_cmd(args: &ArgMatches) -> anyhow::Result<()> {
let pqc_key_type: &u32 = args
.get_one::<u32>("pqc-key-type")
.with_context(|| "pqc-key-type arg not specified")?;
let config_path: &PathBuf = args
.get_one::<PathBuf>("key-config")
.with_context(|| "key-config arg not specified")?;
let fmc_path: &PathBuf = args
.get_one::<PathBuf>("fmc")
.with_context(|| "fmc arg not specified")?;
let fmc_version: &u32 = args
.get_one::<u32>("fmc-version")
.with_context(|| "fmc-version arg not specified")?;
let fmc_rev: &String = args
.get_one::<String>("fmc-rev")
.with_context(|| "fmc-rev arg not specified")?;
let runtime_path: &PathBuf = args
.get_one::<PathBuf>("rt")
.with_context(|| "rt arg not specified")?;
let runtime_version: &u32 = args
.get_one::<u32>("rt-version")
.with_context(|| "rt-version arg not specified")?;
let runtime_rev: &String = args
.get_one::<String>("rt-rev")
.with_context(|| "rt-rev arg not specified")?;
let fw_svn: &u32 = args
.get_one::<u32>("fw-svn")
.with_context(|| "fw-svn arg not specified")?;
let ecc_key_idx: &u32 = args
.get_one::<u32>("ecc-pk-idx")
.with_context(|| "ecc-pk-idx arg not specified")?;
let pqc_key_idx: &u32 = args
.get_one::<u32>("pqc-pk-idx")
.with_context(|| "pqc-pk-idx arg not specified")?;
let out_path: &PathBuf = args
.get_one::<PathBuf>("out")
.with_context(|| "out arg not specified")?;
let print_hashes = args.get_flag("print-hashes");
//YYYYMMDDHHMMSS - Zulu Time
let mut own_from_date: [u8; 15] = [0u8; 15];
let mut own_to_date: [u8; 15] = [0u8; 15];
if let Some(from_date) = args.get_one::<String>("own-from-date") {
if let Some(to_date) = args.get_one::<String>("own-to-date") {
check_date(from_date, to_date)?;
own_from_date[0..14].copy_from_slice(&from_date.as_bytes()[0..14]);
own_from_date[14] = b'Z';
own_to_date[0..14].copy_from_slice(&to_date.as_bytes()[0..14]);
own_to_date[14] = b'Z';
}
}
//YYYYMMDDHHMMSS - Zulu Time
let mut mfg_from_date: [u8; 15] = [0u8; 15];
let mut mfg_to_date: [u8; 15] = [0u8; 15];
if let Some(from_date) = args.get_one::<String>("mfg-from-date") {
if let Some(to_date) = args.get_one::<String>("mfg-to-date") {
check_date(from_date, to_date)?;
mfg_from_date[0..14].copy_from_slice(&from_date.as_bytes()[0..14]);
mfg_from_date[14] = b'Z';
mfg_to_date[0..14].clone_from_slice(&to_date.as_bytes()[0..14]);
mfg_to_date[14] = b'Z';
}
}
let config = config::load_key_config(config_path)?;
let fmc_rev = hex::decode(fmc_rev)?;
let fmc = ElfExecutable::open(
fmc_path,
*fmc_version,
fmc_rev[..IMAGE_REVISION_BYTE_SIZE].try_into()?,
)?;
let runtime_rev = hex::decode(runtime_rev)?;
let runtime = ElfExecutable::open(
runtime_path,
*runtime_version,
runtime_rev[..IMAGE_REVISION_BYTE_SIZE].try_into()?,
)?;
let config_dir = config_path
.parent()
.with_context(|| "Invalid parent path")?;
let pqc_key_type = FwVerificationPqcKeyType::from_u8(*pqc_key_type as u8)
.ok_or_else(|| anyhow!("Unsupported PQC key type: {}", pqc_key_type))?;
let gen_config = ImageGeneratorConfig::<ElfExecutable> {
pqc_key_type,
vendor_config: vendor_config(
pqc_key_type,
config_dir,
&config.vendor,
*ecc_key_idx,
*pqc_key_idx,
mfg_from_date,
mfg_to_date,
)?,
owner_config: owner_config(
pqc_key_type,
config_dir,
&config.owner,
own_from_date,
own_to_date,
)?,
fmc,
runtime,
fw_svn: *fw_svn,
};
let gen = ImageGenerator::new(Crypto::default());
let image = gen.generate(&gen_config).unwrap();
if print_hashes {
let (vendor_pk_desc_hash, owner_pk_hash) = image_pk_desc_hash(&image.manifest);
println!("Vendor PK hash: {}", vendor_pk_desc_hash);
println!("Owner PK hash: {}", owner_pk_hash);
}
let out_file = std::fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(out_path)
.with_context(|| format!("Failed to create file {}", out_path.display()))?;
let mut writer = ImageBundleWriter::new(out_file);
writer.write(&image)?;
Ok(())
}
/// Generate Vendor Config
fn vendor_config(
pqc_key_type: FwVerificationPqcKeyType,
path: &Path,
config: &VendorKeyConfig,
ecc_key_idx: u32,
pqc_key_idx: u32,
from_date: [u8; 15],
to_date: [u8; 15],
) -> anyhow::Result<ImageGeneratorVendorConfig> {
let mut gen_config = ImageGeneratorVendorConfig::default();
let ecc_key_count = config.ecc_pub_keys.len() as u32;
let lms_key_count = config.lms_pub_keys.len() as u32;
let mldsa_key_count = config.mldsa_pub_keys.len() as u32;
if ecc_key_count > VENDOR_ECC_MAX_KEY_COUNT {
return Err(anyhow!("Invalid ECC Public Key Count"));
}
if ecc_key_idx >= ecc_key_count {
return Err(anyhow!("Invalid ECC Public Key Index"));
}
let ecc_pub_keys = &config.ecc_pub_keys;
for (i, pem_file) in ecc_pub_keys.iter().enumerate().take(ecc_key_count as usize) {
let pub_key_path = path.join(pem_file);
gen_config.pub_keys.ecc_pub_keys[i] = Crypto::ecc_pub_key_from_pem(&pub_key_path)?;
}
let mut priv_keys = ImageVendorPrivKeys::default();
if let Some(ecc_priv_keys) = &config.ecc_priv_keys {
for (i, pem_file) in ecc_priv_keys
.iter()
.enumerate()
.take(ecc_key_count as usize)
{
let priv_key_path = path.join(pem_file);
priv_keys.ecc_priv_keys[i] = Crypto::ecc_priv_key_from_pem(&priv_key_path)?;
}
gen_config.priv_keys = Some(priv_keys);
}
if pqc_key_type == FwVerificationPqcKeyType::LMS {
if lms_key_count > VENDOR_LMS_MAX_KEY_COUNT {
return Err(anyhow!("Invalid LMS Public Key Count"));
}
if pqc_key_idx >= lms_key_count {
return Err(anyhow!("Invalid LMS Public Key Index"));
}
let lms_pub_keys = &config.lms_pub_keys;
for (i, pem_file) in lms_pub_keys.iter().enumerate().take(lms_key_count as usize) {
let pub_key_path = path.join(pem_file);
gen_config.pub_keys.lms_pub_keys[i] = lms_pub_key_from_pem(&pub_key_path)?;
}
if let Some(lms_priv_keys) = &config.lms_priv_keys {
for (i, pem_file) in lms_priv_keys
.iter()
.enumerate()
.take(lms_key_count as usize)
{
let priv_key_path = path.join(pem_file);
priv_keys.lms_priv_keys[i] = lms_priv_key_from_pem(&priv_key_path)?;
}
gen_config.priv_keys = Some(priv_keys);
}
} else {
if mldsa_key_count > VENDOR_MLDSA_MAX_KEY_COUNT {
return Err(anyhow!("Invalid MLDSA Public Key Count"));
}
if pqc_key_idx >= mldsa_key_count {
return Err(anyhow!("Invalid MLDSA Public Key Index"));
}
let mldsa_pub_keys = &config.mldsa_pub_keys;
for (i, file) in mldsa_pub_keys
.iter()
.enumerate()
.take(mldsa_key_count as usize)
{
let pub_key_path = path.join(file);
gen_config.pub_keys.mldsa_pub_keys[i] = Crypto::mldsa_pub_key_from_file(&pub_key_path)?;
}
if let Some(mldsa_priv_keys) = &config.mldsa_priv_keys {
for (i, file) in mldsa_priv_keys
.iter()
.enumerate()
.take(mldsa_key_count as usize)
{
let priv_key_path = path.join(file);
priv_keys.mldsa_priv_keys[i] = Crypto::mldsa_priv_key_from_file(&priv_key_path)?;
}
gen_config.priv_keys = Some(priv_keys);
}
}
gen_config.ecc_key_idx = ecc_key_idx;
gen_config.pqc_key_idx = pqc_key_idx;
gen_config.not_before = from_date;
gen_config.not_after = to_date;
gen_config.ecc_key_count = ecc_key_count;
gen_config.lms_key_count = lms_key_count;
gen_config.mldsa_key_count = mldsa_key_count;
Ok(gen_config)
}
/// Generate owner config
fn owner_config(
pqc_key_type: FwVerificationPqcKeyType,
path: &Path,
config: &Option<OwnerKeyConfig>,
from_date: [u8; 15],
to_date: [u8; 15],
) -> anyhow::Result<Option<ImageGeneratorOwnerConfig>> {
if let Some(config) = config {
let mut gen_config = ImageGeneratorOwnerConfig::default();
let pem_file = &config.ecc_pub_key;
let pub_key_path = path.join(pem_file);
gen_config.pub_keys.ecc_pub_key = Crypto::ecc_pub_key_from_pem(&pub_key_path)?;
let mut priv_keys = ImageOwnerPrivKeys::default();
if let Some(pem_file) = &config.ecc_priv_key {
let pub_key_path = path.join(pem_file);
priv_keys.ecc_priv_key = Crypto::ecc_priv_key_from_pem(&pub_key_path)?;
gen_config.priv_keys = Some(priv_keys);
}
if pqc_key_type == FwVerificationPqcKeyType::LMS {
let pem_file = &config.lms_pub_key;
let pub_key_path = path.join(pem_file);
gen_config.pub_keys.lms_pub_key = lms_pub_key_from_pem(&pub_key_path)?;
if let Some(pem_file) = &config.lms_priv_key {
let priv_key_path = path.join(pem_file);
priv_keys.lms_priv_key = lms_priv_key_from_pem(&priv_key_path)?;
gen_config.priv_keys = Some(priv_keys);
}
} else {
let file = &config.mldsa_pub_key;
let pub_key_path = path.join(file);
gen_config.pub_keys.mldsa_pub_key = Crypto::mldsa_pub_key_from_file(&pub_key_path)?;
if let Some(file) = &config.mldsa_priv_key {
let priv_key_path = path.join(file);
priv_keys.mldsa_priv_key = Crypto::mldsa_priv_key_from_file(&priv_key_path)?;
gen_config.priv_keys = Some(priv_keys);
}
}
gen_config.not_before = from_date;
gen_config.not_after = to_date;
Ok(Some(gen_config))
} else {
Ok(None)
}
}
// Returns the vendor public key descriptor and owner public key hashes from the image.
pub fn image_pk_desc_hash(manifest: &ImageManifest) -> (String, String) {
let crypto = Crypto::default();
let vendor_pk_desc_hash = from_hw_format(
&crypto
.sha384_digest(manifest.preamble.vendor_pub_key_info.as_bytes())
.unwrap(),
)
.encode_hex();
let owner_pk_hash = from_hw_format(
&crypto
.sha384_digest(manifest.preamble.owner_pub_keys.as_bytes())
.unwrap(),
)
.encode_hex();
(vendor_pk_desc_hash, owner_pk_hash)
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/gen/src/lib.rs | image/gen/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains data strucutres for the Caliptra Image Generator.
--*/
mod generator;
pub use generator::ImageGenerator;
use anyhow::Context;
use caliptra_image_types::*;
use serde_derive::Deserialize;
use std::path::Path;
/// Image Generator Executable
pub trait ImageGeneratorExecutable {
/// Executable Version Number
fn version(&self) -> u32;
/// Executable Revision
fn rev(&self) -> &ImageRevision;
/// Executable Load Address
fn load_addr(&self) -> u32;
/// Executable Entry Point
fn entry_point(&self) -> u32;
/// Executable Content
fn content(&self) -> &Vec<u8>;
/// Executable Size
fn size(&self) -> u32;
}
pub trait ImageGeneratorHasher {
type Output: Copy;
fn update(&mut self, data: &[u8]);
fn finish(self) -> Self::Output;
}
/// Image Generator Crypto Trait
pub trait ImageGeneratorCrypto {
type Sha256Hasher: ImageGeneratorHasher<Output = [u32; SHA256_DIGEST_WORD_SIZE]>;
fn sha256_start(&self) -> Self::Sha256Hasher;
/// Calculate SHA-256 digest
fn sha256_digest(&self, data: &[u8]) -> anyhow::Result<[u32; SHA256_DIGEST_WORD_SIZE]> {
let mut hasher = self.sha256_start();
hasher.update(data);
Ok(hasher.finish())
}
/// Calculate SHA2-384 digest
fn sha384_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest384>;
/// Calculate SHA2-512 digest
fn sha512_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest512>;
/// Calculate ECDSA Signature
fn ecdsa384_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageEccPrivKey,
pub_key: &ImageEccPubKey,
) -> anyhow::Result<ImageEccSignature>;
/// Calculate LMS Signature
fn lms_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageLmsPrivKey,
) -> anyhow::Result<ImageLmsSignature>;
/// Calculate MLDSA Signature
fn mldsa_sign(
&self,
msg: &[u8],
priv_key: &ImageMldsaPrivKey,
pub_key: &ImageMldsaPubKey,
) -> anyhow::Result<ImageMldsaSignature>;
/// Read ECC-384 Public Key from PEM file
fn ecc_pub_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPubKey>;
/// Read ECC-384 Private Key from PEM file
fn ecc_priv_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPrivKey>;
/// Read MLDSA Public Key from file. Library format is same as hardware format.
fn mldsa_pub_key_from_file(path: &Path) -> anyhow::Result<ImageMldsaPubKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read public key file {}", path.display()))?;
Ok(ImageMldsaPubKey(
u8_to_u32_le(&key_bytes).try_into().unwrap(),
))
}
/// Read MLDSA Private Key from file. Library format is same as hardware format.
fn mldsa_priv_key_from_file(path: &Path) -> anyhow::Result<ImageMldsaPrivKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read private key file {}", path.display()))?;
Ok(ImageMldsaPrivKey(
u8_to_u32_le(&key_bytes).try_into().unwrap(),
))
}
}
/// Convert the slice to hardware format
pub fn to_hw_format<const NUM_WORDS: usize>(value: &[u8]) -> [u32; NUM_WORDS] {
let mut result = [0u32; NUM_WORDS];
for i in 0..result.len() {
result[i] = u32::from_be_bytes(value[i * 4..][..4].try_into().unwrap())
}
result
}
/// Convert the hardware format to byte array
pub fn from_hw_format(value: &[u32; ECC384_SCALAR_WORD_SIZE]) -> [u8; ECC384_SCALAR_BYTE_SIZE] {
let mut result = [0u8; ECC384_SCALAR_BYTE_SIZE];
for i in 0..value.len() {
*<&mut [u8; 4]>::try_from(&mut result[i * 4..][..4]).unwrap() = value[i].to_be_bytes();
}
result
}
pub fn u8_to_u32_le(input: &[u8]) -> Vec<u32> {
input
.chunks(4)
.map(|chunk| {
let mut array = [0u8; 4];
array.copy_from_slice(chunk);
u32::from_le_bytes(array)
})
.collect()
}
/// Image Generator Vendor Configuration
#[derive(Default, Clone, Deserialize)]
pub struct ImageGeneratorVendorConfig {
pub ecc_key_count: u32,
pub lms_key_count: u32,
pub mldsa_key_count: u32,
pub pub_keys: ImageVendorPubKeys,
pub ecc_key_idx: u32,
pub pqc_key_idx: u32,
pub priv_keys: Option<ImageVendorPrivKeys>,
pub not_before: [u8; 15],
pub not_after: [u8; 15],
pub pl0_pauser: Option<u32>,
}
/// Image Generator Owner Configuration
#[derive(Default, Clone, Deserialize)]
pub struct ImageGeneratorOwnerConfig {
pub pub_keys: OwnerPubKeyConfig,
pub priv_keys: Option<ImageOwnerPrivKeys>,
pub not_before: [u8; 15],
pub not_after: [u8; 15],
}
/// Image Generator Configuration
#[derive(Default)]
pub struct ImageGeneratorConfig<T>
where
T: ImageGeneratorExecutable,
{
pub pqc_key_type: FwVerificationPqcKeyType,
pub vendor_config: ImageGeneratorVendorConfig,
pub owner_config: Option<ImageGeneratorOwnerConfig>,
pub fmc: T,
pub runtime: T,
pub fw_svn: u32,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/gen/src/generator.rs | image/gen/src/generator.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
generator.rs
Abstract:
Caliptra Image generator
--*/
use anyhow::bail;
use caliptra_image_types::*;
use memoffset::offset_of;
use zerocopy::IntoBytes;
use crate::*;
/// Image generator
pub struct ImageGenerator<Crypto: ImageGeneratorCrypto> {
crypto: Crypto,
}
impl<Crypto: ImageGeneratorCrypto> ImageGenerator<Crypto> {
const DEFAULT_FLAGS: u32 = 0;
const PL0_PAUSER_FLAG: u32 = (1 << 0);
/// Create an instance `ImageGenerator`
pub fn new(crypto: Crypto) -> Self {
Self { crypto }
}
/// Generate image
///
/// # Arguments
///
/// * `config` - Image generator configuration
///
/// # Returns
///
/// * `ImageBundle` - Caliptra Image Bundle
pub fn generate<E>(&self, config: &ImageGeneratorConfig<E>) -> anyhow::Result<ImageBundle>
where
E: ImageGeneratorExecutable,
{
let image_size =
IMAGE_MANIFEST_BYTE_SIZE as u32 + config.fmc.size() + config.runtime.size();
if image_size > IMAGE_BYTE_SIZE as u32 {
bail!(
"Image larger than {IMAGE_BYTE_SIZE} bytes; image size:{} bytes",
image_size
);
}
// Create FMC TOC & Content
let id = ImageTocEntryId::Fmc;
let offset = IMAGE_MANIFEST_BYTE_SIZE as u32;
let (fmc_toc, fmc) = self.gen_image(config, id, offset)?;
// Create Runtime TOC & Content
let id = ImageTocEntryId::Runtime;
let offset = offset + fmc_toc.size;
let (runtime_toc, runtime) = self.gen_image(config, id, offset)?;
// Check if fmc and runtime image load address ranges don't overlap.
if fmc_toc.overlaps(&runtime_toc) {
bail!(
"FMC:[{:#x?}:{:#x?}] and Runtime:[{:#x?}:{:#x?}] load address ranges overlap",
fmc_toc.load_addr,
fmc_toc.load_addr + fmc_toc.size - 1,
runtime_toc.load_addr,
runtime_toc.load_addr + runtime_toc.size - 1
);
}
let ecc_key_idx = config.vendor_config.ecc_key_idx;
let pqc_key_idx = config.vendor_config.pqc_key_idx;
// Create Header
let toc_digest = self.toc_digest(&fmc_toc, &runtime_toc)?;
let header = self.gen_header(config, ecc_key_idx, pqc_key_idx, toc_digest)?;
// Create Preamble
let vendor_header_digest_384 = self.vendor_header_digest_384(&header)?;
let mut vendor_header_signdata_holder = ImageSignData {
digest_384: &vendor_header_digest_384,
mldsa_msg: None,
};
let owner_header_digest_384 = self.owner_header_digest_384(&header)?;
let mut owner_header_signdata_holder = ImageSignData {
digest_384: &owner_header_digest_384,
mldsa_msg: None,
};
// Update vendor_header_signdata_holder and owner_header_signdata_holder with data if MLDSA validation is required.
if config.pqc_key_type == FwVerificationPqcKeyType::MLDSA {
vendor_header_signdata_holder.mldsa_msg = Some(self.vendor_header_bytes(&header));
owner_header_signdata_holder.mldsa_msg = Some(header.as_bytes());
}
let preamble = self.gen_preamble(
config,
ecc_key_idx,
pqc_key_idx,
&vendor_header_signdata_holder,
&owner_header_signdata_holder,
)?;
// Create Manifest
let manifest = ImageManifest {
marker: MANIFEST_MARKER,
size: core::mem::size_of::<ImageManifest>() as u32,
pqc_key_type: config.pqc_key_type.into(),
reserved: [0u8; 3],
preamble,
header,
fmc: fmc_toc,
runtime: runtime_toc,
};
// Create Image Bundle
let image = ImageBundle {
manifest,
fmc,
runtime,
};
Ok(image)
}
/// Create preamble
pub fn gen_preamble<E>(
&self,
config: &ImageGeneratorConfig<E>,
ecc_vendor_key_idx: u32,
pqc_vendor_key_idx: u32,
vendor_signdata_holder: &ImageSignData,
owner_signdata_holder: &ImageSignData,
) -> anyhow::Result<ImagePreamble>
where
E: ImageGeneratorExecutable,
{
let mut vendor_sigs = ImageSignatures::default();
let mut owner_sigs = ImageSignatures::default();
// Add Vendor Header Signatures.
if let Some(priv_keys) = config.vendor_config.priv_keys {
let sig = self.crypto.ecdsa384_sign(
vendor_signdata_holder.digest_384,
&priv_keys.ecc_priv_keys[ecc_vendor_key_idx as usize],
&config.vendor_config.pub_keys.ecc_pub_keys[ecc_vendor_key_idx as usize],
)?;
vendor_sigs.ecc_sig = sig;
if config.pqc_key_type == FwVerificationPqcKeyType::LMS {
let lms_sig = self.crypto.lms_sign(
vendor_signdata_holder.digest_384,
&priv_keys.lms_priv_keys[pqc_vendor_key_idx as usize],
)?;
let sig = lms_sig.as_bytes();
vendor_sigs.pqc_sig.0[..sig.len()].copy_from_slice(sig);
} else {
let mldsa_sig = self.crypto.mldsa_sign(
vendor_signdata_holder.mldsa_msg.unwrap(),
&priv_keys.mldsa_priv_keys[pqc_vendor_key_idx as usize],
&config.vendor_config.pub_keys.mldsa_pub_keys[pqc_vendor_key_idx as usize],
)?;
let sig = mldsa_sig.as_bytes();
vendor_sigs.pqc_sig.0[..sig.len()].copy_from_slice(sig);
};
}
// Add Owner Header Signatures.
if let Some(owner_config) = &config.owner_config {
if let Some(priv_keys) = &owner_config.priv_keys {
let sig = self.crypto.ecdsa384_sign(
owner_signdata_holder.digest_384,
&priv_keys.ecc_priv_key,
&owner_config.pub_keys.ecc_pub_key,
)?;
owner_sigs.ecc_sig = sig;
if config.pqc_key_type == FwVerificationPqcKeyType::LMS {
let lms_sig = self
.crypto
.lms_sign(owner_signdata_holder.digest_384, &priv_keys.lms_priv_key)?;
let sig = lms_sig.as_bytes();
owner_sigs.pqc_sig.0[..sig.len()].copy_from_slice(sig);
} else {
let mldsa_sig = self.crypto.mldsa_sign(
owner_signdata_holder.mldsa_msg.unwrap(),
&priv_keys.mldsa_priv_key,
&config.owner_config.as_ref().unwrap().pub_keys.mldsa_pub_key,
)?;
let sig = mldsa_sig.as_bytes();
owner_sigs.pqc_sig.0[..sig.len()].copy_from_slice(sig);
};
}
}
let mut vendor_pub_key_info = ImageVendorPubKeyInfo {
ecc_key_descriptor: ImageEccKeyDescriptor {
version: KEY_DESCRIPTOR_VERSION,
reserved: 0,
key_hash_count: config.vendor_config.ecc_key_count as u8,
key_hash: ImageEccKeyHashes::default(),
},
pqc_key_descriptor: ImagePqcKeyDescriptor {
version: KEY_DESCRIPTOR_VERSION,
key_type: FwVerificationPqcKeyType::default() as u8,
key_hash_count: 0,
key_hash: ImagePqcKeyHashes::default(),
},
};
// Hash the ECC vendor public keys.
for i in 0..config.vendor_config.ecc_key_count {
let ecc_pub_key = config.vendor_config.pub_keys.ecc_pub_keys[i as usize];
let ecc_pub_key_digest = self.crypto.sha384_digest(ecc_pub_key.as_bytes())?;
vendor_pub_key_info.ecc_key_descriptor.key_hash[i as usize] = ecc_pub_key_digest;
}
// Hash the LMS or MLDSA vendor public keys.
if config.pqc_key_type == FwVerificationPqcKeyType::LMS {
for i in 0..config.vendor_config.lms_key_count {
vendor_pub_key_info.pqc_key_descriptor.key_hash[i as usize] =
self.crypto.sha384_digest(
config.vendor_config.pub_keys.lms_pub_keys[i as usize].as_bytes(),
)?;
}
vendor_pub_key_info.pqc_key_descriptor.key_type = FwVerificationPqcKeyType::LMS.into();
vendor_pub_key_info.pqc_key_descriptor.key_hash_count =
config.vendor_config.lms_key_count as u8;
} else {
for i in 0..config.vendor_config.mldsa_key_count {
vendor_pub_key_info.pqc_key_descriptor.key_hash[i as usize] =
self.crypto.sha384_digest(
config.vendor_config.pub_keys.mldsa_pub_keys[i as usize].as_bytes(),
)?;
}
vendor_pub_key_info.pqc_key_descriptor.key_type =
FwVerificationPqcKeyType::MLDSA.into();
vendor_pub_key_info.pqc_key_descriptor.key_hash_count =
config.vendor_config.mldsa_key_count as u8;
}
let mut preamble = ImagePreamble {
vendor_pub_key_info,
vendor_ecc_pub_key_idx: ecc_vendor_key_idx,
vendor_ecc_active_pub_key: config.vendor_config.pub_keys.ecc_pub_keys
[ecc_vendor_key_idx as usize],
vendor_pqc_pub_key_idx: pqc_vendor_key_idx,
vendor_sigs,
owner_sigs,
..Default::default()
};
// Store the PQC (LMS or MLDSA) vendor public key in the Preamble.
let pqc_pub_key = match config.pqc_key_type {
FwVerificationPqcKeyType::LMS => {
config.vendor_config.pub_keys.lms_pub_keys[pqc_vendor_key_idx as usize].as_bytes()
}
FwVerificationPqcKeyType::MLDSA => config.vendor_config.pub_keys.mldsa_pub_keys
[pqc_vendor_key_idx as usize]
.0
.as_bytes(),
};
preamble.vendor_pqc_active_pub_key.0[..pqc_pub_key.len()].copy_from_slice(pqc_pub_key);
if let Some(owner_config) = &config.owner_config {
// Store the ECC owner public key in the Preamble.
preamble.owner_pub_keys.ecc_pub_key = owner_config.pub_keys.ecc_pub_key;
// Store the PQC (LMS or MLDSA) owner public key in the Preamble.
let pqc_pub_key = match config.pqc_key_type {
FwVerificationPqcKeyType::LMS => owner_config.pub_keys.lms_pub_key.as_bytes(),
FwVerificationPqcKeyType::MLDSA => owner_config.pub_keys.mldsa_pub_key.0.as_bytes(),
};
preamble.owner_pub_keys.pqc_pub_key.0[..pqc_pub_key.len()].copy_from_slice(pqc_pub_key);
}
Ok(preamble)
}
/// Generate header
fn gen_header<E>(
&self,
config: &ImageGeneratorConfig<E>,
ecc_key_idx: u32,
lms_key_idx: u32,
digest: ImageDigest384,
) -> anyhow::Result<ImageHeader>
where
E: ImageGeneratorExecutable,
{
let mut header = ImageHeader {
vendor_ecc_pub_key_idx: ecc_key_idx,
vendor_pqc_pub_key_idx: lms_key_idx,
flags: Self::DEFAULT_FLAGS,
toc_len: MAX_TOC_ENTRY_COUNT,
toc_digest: digest,
svn: config.fw_svn,
..Default::default()
};
header.vendor_data.vendor_not_before = config.vendor_config.not_before;
header.vendor_data.vendor_not_after = config.vendor_config.not_after;
if let Some(pauser) = config.vendor_config.pl0_pauser {
header.flags |= Self::PL0_PAUSER_FLAG;
header.pl0_pauser = pauser;
}
if let Some(owner_config) = &config.owner_config {
header.owner_data.owner_not_before = owner_config.not_before;
header.owner_data.owner_not_after = owner_config.not_after;
}
Ok(header)
}
/// Calculate header digest for vendor.
/// Vendor digest is calculated up to the `owner_data` field.
pub fn vendor_header_digest_384(&self, header: &ImageHeader) -> anyhow::Result<ImageDigest384> {
let offset = offset_of!(ImageHeader, owner_data);
self.crypto
.sha384_digest(header.as_bytes().get(..offset).unwrap())
}
/// Calculate header digest for owner.
pub fn owner_header_digest_384(&self, header: &ImageHeader) -> anyhow::Result<ImageDigest384> {
self.crypto.sha384_digest(header.as_bytes())
}
pub fn vendor_header_bytes<'a>(&self, header: &'a ImageHeader) -> &'a [u8] {
let offset = offset_of!(ImageHeader, owner_data);
header.as_bytes().get(..offset).unwrap()
}
/// Calculate owner public key descriptor digest.
pub fn owner_pubkey_digest(&self, preamble: &ImagePreamble) -> anyhow::Result<ImageDigest384> {
self.crypto
.sha384_digest(preamble.owner_pub_keys.as_bytes())
}
/// Calculate vendor public key descriptor digest.
pub fn vendor_pubkey_info_digest(
&self,
preamble: &ImagePreamble,
) -> anyhow::Result<ImageDigest384> {
self.crypto
.sha384_digest(preamble.vendor_pub_key_info.as_bytes())
}
/// Generate image
fn gen_image<E>(
&self,
config: &ImageGeneratorConfig<E>,
id: ImageTocEntryId,
offset: u32,
) -> anyhow::Result<(ImageTocEntry, Vec<u8>)>
where
E: ImageGeneratorExecutable,
{
let image = match id {
ImageTocEntryId::Fmc => &config.fmc,
ImageTocEntryId::Runtime => &config.runtime,
};
let toc_type = ImageTocEntryType::Executable;
let digest = self.crypto.sha384_digest(image.content())?;
let entry = ImageTocEntry {
id: id.into(),
toc_type: toc_type.into(),
revision: *image.rev(),
version: image.version(),
reserved: [0; 2],
load_addr: image.load_addr(),
entry_point: image.entry_point(),
offset,
size: image.content().len() as u32,
digest,
};
Ok((entry, image.content().clone()))
}
/// Calculate TOC digest
pub fn toc_digest(
&self,
fmc_toc: &ImageTocEntry,
rt_toc: &ImageTocEntry,
) -> anyhow::Result<ImageDigest384> {
let mut toc_content: Vec<u8> = Vec::new();
toc_content.extend_from_slice(fmc_toc.as_bytes());
toc_content.extend_from_slice(rt_toc.as_bytes());
self.crypto.sha384_digest(&toc_content)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/types/src/lib.rs | image/types/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains data structures for the firmware image bundle.
--*/
#![cfg_attr(not(feature = "std"), no_std)]
use caliptra_error::{CaliptraError, CaliptraResult};
use caliptra_lms_types::{
LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsPrivateKey, LmsPublicKey, LmsSignature,
};
use core::mem::size_of;
use core::ops::Range;
use memoffset::{offset_of, span_of};
#[cfg(feature = "std")]
use serde_derive::Deserialize;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
use zeroize::Zeroize;
pub const MANIFEST_MARKER: u32 = 0x324E4D43;
pub const KEY_DESCRIPTOR_VERSION: u16 = 1;
pub const VENDOR_ECC_MAX_KEY_COUNT: u32 = 4;
pub const VENDOR_LMS_MAX_KEY_COUNT: u32 = 32;
pub const VENDOR_MLDSA_MAX_KEY_COUNT: u32 = 4;
pub const VENDOR_PQC_MAX_KEY_COUNT: u32 = VENDOR_LMS_MAX_KEY_COUNT;
pub const MAX_TOC_ENTRY_COUNT: u32 = 2;
pub const IMAGE_REVISION_BYTE_SIZE: usize = 20;
pub const ECC384_SCALAR_WORD_SIZE: usize = 12;
pub const ECC384_SCALAR_BYTE_SIZE: usize = 48;
pub const SHA192_DIGEST_BYTE_SIZE: usize = 24;
pub const SHA192_DIGEST_WORD_SIZE: usize = 6;
pub const SHA256_DIGEST_WORD_SIZE: usize = 8;
pub const SHA384_DIGEST_WORD_SIZE: usize = 12;
pub const SHA384_DIGEST_BYTE_SIZE: usize = 48;
pub const SHA512_DIGEST_WORD_SIZE: usize = 16;
pub const SHA512_DIGEST_BYTE_SIZE: usize = 64;
pub const IMAGE_LMS_OTS_P_PARAM: usize = 51;
pub const IMAGE_LMS_KEY_HEIGHT: usize = 15;
pub const IMAGE_BYTE_SIZE: usize = 256 * 1024;
// LMS-SHA192-H15
pub const IMAGE_LMS_TREE_TYPE: LmsAlgorithmType = LmsAlgorithmType::LmsSha256N24H15;
// LMOTS-SHA192-W4
pub const IMAGE_LMS_OTS_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::LmotsSha256N24W4;
pub const IMAGE_MANIFEST_BYTE_SIZE: usize = core::mem::size_of::<ImageManifest>();
pub const LMS_PUB_KEY_BYTE_SIZE: usize = 48;
pub const MLDSA87_PUB_KEY_BYTE_SIZE: usize = 2592;
pub const MLDSA87_PUB_KEY_WORD_SIZE: usize = 648;
pub const MLDSA87_PRIV_KEY_BYTE_SIZE: usize = 4896;
pub const MLDSA87_PRIV_KEY_WORD_SIZE: usize = 1224;
pub const MLDSA87_SIGNATURE_BYTE_SIZE: usize = 4628;
pub const MLDSA87_SIGNATURE_WORD_SIZE: usize = 1157;
pub const MLDSA87_MSG_BYTE_SIZE: usize = 64;
pub const PQC_PUB_KEY_BYTE_SIZE: usize = MLDSA87_PUB_KEY_BYTE_SIZE;
pub const PQC_SIGNATURE_BYTE_SIZE: usize = MLDSA87_SIGNATURE_BYTE_SIZE;
pub type ImageScalar = [u32; ECC384_SCALAR_WORD_SIZE];
pub type ImageDigest384 = [u32; SHA384_DIGEST_WORD_SIZE];
pub type ImageDigest512 = [u32; SHA512_DIGEST_WORD_SIZE];
pub type ImageRevision = [u8; IMAGE_REVISION_BYTE_SIZE];
pub type ImageEccPrivKey = ImageScalar;
#[repr(C)]
#[derive(
IntoBytes,
FromBytes,
Immutable,
KnownLayout,
Default,
Debug,
Copy,
Clone,
Eq,
PartialEq,
Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageEccPubKey {
/// X Coordinate
pub x: ImageScalar,
/// Y Coordinate
pub y: ImageScalar,
}
pub type ImageLmsPublicKey = LmsPublicKey<SHA192_DIGEST_WORD_SIZE>;
pub type ImageLmsPrivKey = LmsPrivateKey<SHA192_DIGEST_WORD_SIZE>;
#[repr(C)]
#[derive(
Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageMldsaPubKey(pub [u32; MLDSA87_PUB_KEY_WORD_SIZE]);
impl Default for ImageMldsaPubKey {
fn default() -> Self {
ImageMldsaPubKey([0; MLDSA87_PUB_KEY_WORD_SIZE])
}
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for ImageMldsaPubKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ArrayVisitor;
impl<'de> serde::de::Visitor<'de> for ArrayVisitor {
type Value = ImageMldsaPubKey;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(&format!(
"an array of {} u32 elements",
MLDSA87_PUB_KEY_WORD_SIZE
))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut arr = [0u32; MLDSA87_PUB_KEY_WORD_SIZE];
for (i, item) in arr.iter_mut().enumerate().take(MLDSA87_PUB_KEY_WORD_SIZE) {
*item = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ImageMldsaPubKey(arr))
}
}
deserializer.deserialize_seq(ArrayVisitor)
}
}
#[repr(C)]
#[derive(
Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageMldsaPrivKey(pub [u32; MLDSA87_PRIV_KEY_WORD_SIZE]);
impl Default for ImageMldsaPrivKey {
fn default() -> Self {
ImageMldsaPrivKey([0; MLDSA87_PRIV_KEY_WORD_SIZE])
}
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for ImageMldsaPrivKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ArrayVisitor;
impl<'de> serde::de::Visitor<'de> for ArrayVisitor {
type Value = ImageMldsaPrivKey;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(&format!(
"an array of {} u32 elements",
MLDSA87_PRIV_KEY_WORD_SIZE
))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut arr = [0u32; MLDSA87_PRIV_KEY_WORD_SIZE];
for (i, item) in arr.iter_mut().enumerate().take(MLDSA87_PRIV_KEY_WORD_SIZE) {
*item = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ImageMldsaPrivKey(arr))
}
}
deserializer.deserialize_seq(ArrayVisitor)
}
}
#[repr(C)]
#[derive(
Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImagePqcPubKey(pub [u8; PQC_PUB_KEY_BYTE_SIZE]);
impl Default for ImagePqcPubKey {
fn default() -> Self {
ImagePqcPubKey([0; PQC_PUB_KEY_BYTE_SIZE])
}
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for ImagePqcPubKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ArrayVisitor;
impl<'de> serde::de::Visitor<'de> for ArrayVisitor {
type Value = ImagePqcPubKey;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(&format!("an array of {} bytes", PQC_PUB_KEY_BYTE_SIZE))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut arr = [0u8; PQC_PUB_KEY_BYTE_SIZE];
for (i, item) in arr.iter_mut().enumerate().take(PQC_PUB_KEY_BYTE_SIZE) {
*item = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ImagePqcPubKey(arr))
}
}
deserializer.deserialize_seq(ArrayVisitor)
}
}
#[repr(C)]
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
FromBytes,
Immutable,
IntoBytes,
KnownLayout,
PartialEq,
Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageEccSignature {
/// Random point
pub r: ImageScalar,
/// Proof
pub s: ImageScalar,
}
pub type ImageLmsSignature =
LmsSignature<SHA192_DIGEST_WORD_SIZE, IMAGE_LMS_OTS_P_PARAM, IMAGE_LMS_KEY_HEIGHT>;
pub type ImageLmOTSSignature = LmotsSignature<SHA192_DIGEST_WORD_SIZE, IMAGE_LMS_OTS_P_PARAM>;
#[repr(C)]
#[derive(
Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageMldsaSignature(pub [u32; MLDSA87_SIGNATURE_WORD_SIZE]);
impl Default for ImageMldsaSignature {
fn default() -> Self {
ImageMldsaSignature([0; MLDSA87_SIGNATURE_WORD_SIZE])
}
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for ImageMldsaSignature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ArrayVisitor;
impl<'de> serde::de::Visitor<'de> for ArrayVisitor {
type Value = ImageMldsaSignature;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(&format!(
"an array of {} u32 elements",
MLDSA87_SIGNATURE_WORD_SIZE
))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut arr = [0u32; MLDSA87_SIGNATURE_WORD_SIZE];
for (i, item) in arr.iter_mut().enumerate().take(MLDSA87_SIGNATURE_WORD_SIZE) {
*item = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ImageMldsaSignature(arr))
}
}
deserializer.deserialize_seq(ArrayVisitor)
}
}
#[repr(C)]
#[derive(
Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Zeroize,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImagePqcSignature(pub [u8; PQC_SIGNATURE_BYTE_SIZE]);
impl Default for ImagePqcSignature {
fn default() -> Self {
ImagePqcSignature([0; PQC_SIGNATURE_BYTE_SIZE])
}
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for ImagePqcSignature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ArrayVisitor;
impl<'de> serde::de::Visitor<'de> for ArrayVisitor {
type Value = ImagePqcSignature;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(&format!("an array of {} bytes", PQC_SIGNATURE_BYTE_SIZE))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut arr = [0u8; PQC_SIGNATURE_BYTE_SIZE];
for (i, item) in arr.iter_mut().enumerate().take(PQC_SIGNATURE_BYTE_SIZE) {
*item = seq
.next_element()?
.ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
}
Ok(ImagePqcSignature(arr))
}
}
deserializer.deserialize_seq(ArrayVisitor)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub enum FwVerificationPqcKeyType {
MLDSA = 1,
LMS = 3,
}
impl From<FwVerificationPqcKeyType> for u8 {
fn from(val: FwVerificationPqcKeyType) -> Self {
val as u8
}
}
impl Default for FwVerificationPqcKeyType {
fn default() -> Self {
Self::MLDSA
}
}
impl FwVerificationPqcKeyType {
pub fn from_u8(value: u8) -> Option<FwVerificationPqcKeyType> {
match value {
1 => Some(FwVerificationPqcKeyType::MLDSA),
3 => Some(FwVerificationPqcKeyType::LMS),
_ => None,
}
}
}
#[derive(Debug)]
pub struct ImageSignData<'a> {
pub digest_384: &'a ImageDigest384,
pub mldsa_msg: Option<&'a [u8]>,
}
/// Caliptra Image Bundle
#[cfg(feature = "std")]
#[derive(Debug, Default)]
pub struct ImageBundle {
/// Manifest
pub manifest: ImageManifest,
/// FMC
pub fmc: Vec<u8>,
/// Runtime
pub runtime: Vec<u8>,
}
#[cfg(feature = "std")]
impl ImageBundle {
pub fn to_bytes(&self) -> std::io::Result<Vec<u8>> {
use std::io::ErrorKind;
let mut result = vec![];
result.extend_from_slice(self.manifest.as_bytes());
if self.manifest.fmc.offset as usize != result.len() {
return Err(std::io::Error::new(
ErrorKind::Other,
"actual fmc offset does not match manifest",
));
}
if self.manifest.fmc.size as usize != self.fmc.len() {
return Err(std::io::Error::new(
ErrorKind::Other,
"actual fmc size does not match manifest",
));
}
result.extend_from_slice(&self.fmc);
if self.manifest.runtime.offset as usize != result.len() {
return Err(std::io::Error::new(
ErrorKind::Other,
"actual runtime offset does not match manifest",
));
}
if self.manifest.runtime.size as usize != self.runtime.len() {
return Err(std::io::Error::new(
ErrorKind::Other,
"actual runtime size does not match manifest",
));
}
result.extend_from_slice(&self.runtime);
Ok(result)
}
}
/// Calipatra Image Manifest
///
/// NOTE: only the header, fmc, and runtime portions of this struct are covered by signature.
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Clone, Copy, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageManifest {
/// Marker
pub marker: u32,
/// Size of `Manifest` structure
pub size: u32,
/// PQC key type for image verification (LMS or MLDSA keys)
pub pqc_key_type: u8,
pub reserved: [u8; 3],
/// Preamble
pub preamble: ImagePreamble,
/// Header
pub header: ImageHeader,
/// First Mutable Code TOC Entry
pub fmc: ImageTocEntry,
/// Runtime TOC Entry
pub runtime: ImageTocEntry,
}
impl Default for ImageManifest {
fn default() -> Self {
Self {
marker: Default::default(),
size: size_of::<ImageManifest>() as u32,
pqc_key_type: 0,
reserved: [0u8; 3],
preamble: ImagePreamble::default(),
header: ImageHeader::default(),
fmc: ImageTocEntry::default(),
runtime: ImageTocEntry::default(),
}
}
}
impl ImageManifest {
/// Returns the `Range<u32>` containing the vendor public key descriptors
pub fn vendor_pub_key_descriptors_range() -> Range<u32> {
let offset = offset_of!(ImageManifest, preamble) as u32;
let span = span_of!(ImagePreamble, vendor_pub_key_info);
span.start as u32 + offset..span.end as u32 + offset
}
/// Returns the `Range<u32>` containing the owner public key
pub fn owner_pub_key_range() -> Range<u32> {
let offset = offset_of!(ImageManifest, preamble) as u32;
let span = span_of!(ImagePreamble, owner_pub_keys);
span.start as u32 + offset..span.end as u32 + offset
}
/// Returns `Range<u32>` containing the header
pub fn header_range() -> Range<u32> {
let span = span_of!(ImageManifest, header);
span.start as u32..span.end as u32
}
/// Returns `Range<u32>` containing the table of contents
pub fn toc_range() -> Range<u32> {
let span = span_of!(ImageManifest, fmc..=runtime);
span.start as u32..span.end as u32
}
}
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageVendorPubKeys {
pub ecc_pub_keys: [ImageEccPubKey; VENDOR_ECC_MAX_KEY_COUNT as usize],
#[zeroize(skip)]
pub lms_pub_keys: [ImageLmsPublicKey; VENDOR_LMS_MAX_KEY_COUNT as usize],
pub mldsa_pub_keys: [ImageMldsaPubKey; VENDOR_MLDSA_MAX_KEY_COUNT as usize],
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageVendorPubKeyInfo {
pub ecc_key_descriptor: ImageEccKeyDescriptor,
pub pqc_key_descriptor: ImagePqcKeyDescriptor,
}
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageVendorPrivKeys {
pub ecc_priv_keys: [ImageEccPrivKey; VENDOR_ECC_MAX_KEY_COUNT as usize],
#[zeroize(skip)]
pub lms_priv_keys: [ImageLmsPrivKey; VENDOR_LMS_MAX_KEY_COUNT as usize],
pub mldsa_priv_keys: [ImageMldsaPrivKey; VENDOR_MLDSA_MAX_KEY_COUNT as usize],
}
#[repr(C)]
#[derive(IntoBytes, FromBytes, Default, Debug, Clone, Copy, Zeroize)]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct OwnerPubKeyConfig {
pub ecc_pub_key: ImageEccPubKey,
#[zeroize(skip)]
pub lms_pub_key: ImageLmsPublicKey,
pub mldsa_pub_key: ImageMldsaPubKey,
}
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageOwnerPubKeys {
pub ecc_pub_key: ImageEccPubKey,
pub pqc_pub_key: ImagePqcPubKey,
}
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Clone, Copy, Zeroize)]
#[cfg_attr(feature = "std", derive(Deserialize))]
pub struct ImageOwnerPrivKeys {
pub ecc_priv_key: ImageEccPrivKey,
#[zeroize(skip)]
pub lms_priv_key: ImageLmsPrivKey,
pub mldsa_priv_key: ImageMldsaPrivKey,
}
#[repr(C)]
#[derive(Clone, Copy, IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageSignatures {
pub ecc_sig: ImageEccSignature,
pub pqc_sig: ImagePqcSignature,
}
/// Caliptra Image ECC Key Descriptor
#[repr(C)]
#[derive(Clone, Copy, Default, Debug, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageEccKeyDescriptor {
pub version: u16,
pub reserved: u8,
pub key_hash_count: u8,
pub key_hash: ImageEccKeyHashes,
}
/// Caliptra Image LMS/MLDSA Key Descriptor
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImagePqcKeyDescriptor {
pub version: u16,
pub key_type: u8,
pub key_hash_count: u8,
pub key_hash: ImagePqcKeyHashes,
}
pub type ImageEccKeyHashes = [ImageDigest384; VENDOR_ECC_MAX_KEY_COUNT as usize];
pub type ImagePqcKeyHashes = [ImageDigest384; VENDOR_PQC_MAX_KEY_COUNT as usize];
/// Caliptra Image Bundle Preamble
#[repr(C)]
#[derive(Clone, Copy, IntoBytes, Immutable, KnownLayout, FromBytes, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImagePreamble {
/// Vendor Public Key Descriptor + Key Hashes
pub vendor_pub_key_info: ImageVendorPubKeyInfo,
/// Vendor ECC Public Key Index
pub vendor_ecc_pub_key_idx: u32,
/// Vendor Active Public Key
pub vendor_ecc_active_pub_key: ImageEccPubKey,
/// Vendor PQC Public Key Index
pub vendor_pqc_pub_key_idx: u32,
/// Vendor Active PQC (LMS or MLDSA) Public Key
pub vendor_pqc_active_pub_key: ImagePqcPubKey,
/// Vendor Signatures
pub vendor_sigs: ImageSignatures,
/// Owner Public Keys
pub owner_pub_keys: ImageOwnerPubKeys,
/// Owner Signatures
pub owner_sigs: ImageSignatures,
pub _rsvd: [u32; 2],
}
#[repr(C)]
#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct VendorSignedData {
/// Vendor Start Date [ASN1 Time Format] For FMC alias certificate.
pub vendor_not_before: [u8; 15],
/// Vendor End Date [ASN1 Time Format] For FMC alias certificate.
pub vendor_not_after: [u8; 15],
pub reserved: [u8; 10],
}
#[repr(C)]
#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct OwnerSignedData {
/// Owner Start Date [ASN1 Time Format] For FMC alias certificate: Takes Preference over vendor start date
pub owner_not_before: [u8; 15],
/// Owner End Date [ASN1 Time Format] For FMC alias certificate: Takes Preference over vendor end date
pub owner_not_after: [u8; 15],
pub reserved: [u8; 10],
}
/// Caliptra Image header
#[repr(C)]
#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageHeader {
/// Revision
pub revision: [u32; 2],
/// Vendor ECC Public Key Index
pub vendor_ecc_pub_key_idx: u32,
/// Vendor PQC Public Key Index
pub vendor_pqc_pub_key_idx: u32,
/// Flags
/// Bit 0: Interpret the pl0_pauser field. If not set, all PAUSERs are PL1.
pub flags: u32,
/// TOC Entry Count
pub toc_len: u32,
/// The PAUSER with PL0 privileges. The SoC integration must choose
/// only one PAUSER to be PL0.
pub pl0_pauser: u32,
/// TOC Digest
pub toc_digest: ImageDigest384,
pub svn: u32,
/// Vendor Data
pub vendor_data: VendorSignedData,
/// The Signed owner data
pub owner_data: OwnerSignedData,
}
/// Caliptra table contents entry id
pub enum ImageTocEntryType {
/// First mutable code
Executable = 1,
}
impl From<ImageTocEntryType> for u32 {
/// Converts to this type from the input type.
fn from(value: ImageTocEntryType) -> Self {
value as u32
}
}
/// Caliptra table contents entry id
pub enum ImageTocEntryId {
/// First mutable code
Fmc = 1,
/// Runtime
Runtime = 2,
}
impl From<ImageTocEntryId> for u32 {
/// Converts to this type from the input type.
fn from(value: ImageTocEntryId) -> Self {
value as u32
}
}
/// Caliptra Table of contents entry
#[repr(C)]
#[derive(IntoBytes, Clone, Copy, FromBytes, Immutable, KnownLayout, Default, Debug, Zeroize)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ImageTocEntry {
/// ID
pub id: u32,
/// Type
pub toc_type: u32,
/// Commit revision
pub revision: ImageRevision,
// Firmware release number
pub version: u32,
/// Reserved field
pub reserved: [u32; 2],
/// Entry Point
pub load_addr: u32,
/// Entry Point
pub entry_point: u32,
/// Offset
pub offset: u32,
/// Size
pub size: u32,
/// Digest
pub digest: ImageDigest384,
}
impl ImageTocEntry {
pub fn image_range(&self) -> CaliptraResult<Range<u32>> {
let err = CaliptraError::IMAGE_VERIFIER_ERR_TOC_ENTRY_RANGE_ARITHMETIC_OVERFLOW;
let end = self.offset.checked_add(self.size).ok_or(err)?;
Ok(self.offset..end)
}
pub fn image_size(&self) -> u32 {
self.size
}
pub fn overlaps(&self, other: &ImageTocEntry) -> bool {
self.load_addr < (other.load_addr + other.image_size())
&& (self.load_addr + self.image_size()) > other.load_addr
}
}
/// Information about the ROM image.
#[repr(C)]
#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Default, Debug)]
pub struct RomInfo {
// sha256 digest with big-endian words, where each 4-byte segment of the
// digested data has the bytes reversed.
pub sha256_digest: [u32; 8],
pub revision: ImageRevision,
pub flags: u32,
pub version: u16,
pub rsvd: u16, // maintain DWORD alignment
}
#[cfg(all(test, target_family = "unix"))]
mod tests {
use super::*;
#[test]
fn test_manifest_size() {
assert_eq!(std::mem::size_of::<ImageManifest>() % 4, 0);
}
#[test]
fn test_image_overlap() {
let mut image1 = ImageTocEntry::default();
let mut image2 = ImageTocEntry::default();
// Case 1
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 450;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 2
image1.load_addr = 450;
image1.size = 100;
image2.load_addr = 400;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 3
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 499;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 4
image1.load_addr = 499;
image1.size = 100;
image2.load_addr = 400;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 5
image1.load_addr = 499;
image1.size = 1;
image2.load_addr = 400;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 6
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 499;
image2.size = 1;
assert!(image1.overlaps(&image2));
// Case 7
image1.load_addr = 400;
image1.size = 1;
image2.load_addr = 400;
image2.size = 100;
assert!(image1.overlaps(&image2));
// Case 8
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 400;
image2.size = 1;
assert!(image1.overlaps(&image2));
// Case 9
image1.load_addr = 399;
image1.size = 1;
image2.load_addr = 400;
image2.size = 100;
assert!(!image1.overlaps(&image2));
// Case 10
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 399;
image2.size = 1;
assert!(!image1.overlaps(&image2));
// Case 11
image1.load_addr = 500;
image1.size = 100;
image2.load_addr = 400;
image2.size = 100;
assert!(!image1.overlaps(&image2));
// Case 12
image1.load_addr = 400;
image1.size = 100;
image2.load_addr = 500;
image2.size = 100;
assert!(!image1.overlaps(&image2));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/fake-keys/src/lib.rs | image/fake-keys/src/lib.rs | // Licensed under the Apache-2.0 license
use caliptra_image_gen::{ImageGeneratorOwnerConfig, ImageGeneratorVendorConfig};
use caliptra_image_types::{
ImageEccPrivKey, ImageEccPubKey, ImageLmsPrivKey, ImageLmsPublicKey, ImageMldsaPrivKey,
ImageMldsaPubKey, ImageOwnerPrivKeys, ImageVendorPrivKeys, ImageVendorPubKeys,
OwnerPubKeyConfig, IMAGE_LMS_OTS_TYPE, IMAGE_LMS_TREE_TYPE, VENDOR_ECC_MAX_KEY_COUNT,
VENDOR_LMS_MAX_KEY_COUNT, VENDOR_MLDSA_MAX_KEY_COUNT,
};
use caliptra_lms_types::bytes_to_words_6;
#[cfg(test)]
use std::fs;
#[cfg(test)]
use std::io::Write; // bring trait into scope
#[cfg(test)]
use zerocopy::IntoBytes;
/// Generated with
///
/// ```no_run
/// use caliptra_image_crypto::OsslCrypto;
/// use std::path::PathBuf;
/// use caliptra_image_gen::ImageGeneratorCrypto;
///
/// fn print_public_key(name: &str, path: &str) {
/// let key = OsslCrypto::ecc_pub_key_from_pem(&PathBuf::from(path)).unwrap();
/// println!("pub const {name}_PUBLIC: ImageEccPubKey = {key:#010x?};");
/// }
/// fn print_private_key(name: &str, path: &str) {
/// let key = OsslCrypto::ecc_priv_key_from_pem(&PathBuf::from(path)).unwrap();
/// println!("pub const {name}_PRIVATE: ImageEccPrivKey = {key:#010x?};");
/// }
///
/// print_public_key("VENDOR_KEY_0", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-pub-key-0.pem");
/// print_private_key("VENDOR_KEY_0", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-priv-key-0.pem");
/// print_public_key("VENDOR_KEY_1", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-pub-key-1.pem");
/// print_private_key("VENDOR_KEY_1", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-priv-key-1.pem");
/// print_public_key("VENDOR_KEY_2", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-pub-key-2.pem");
/// print_private_key("VENDOR_KEY_2", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-priv-key-2.pem");
/// print_public_key("VENDOR_KEY_3", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-pub-key-3.pem");
/// print_private_key("VENDOR_KEY_3", "../../target/riscv32imc-unknown-none-elf/firmware/vnd-priv-key-3.pem");
/// print_public_key("OWNER_KEY", "../../target/riscv32imc-unknown-none-elf/firmware/own-pub-key.pem");
/// print_private_key("OWNER_KEY", "../../target/riscv32imc-unknown-none-elf/firmware/own-priv-key.pem");
/// ```
pub const VENDOR_ECC_KEY_0_PUBLIC: ImageEccPubKey = ImageEccPubKey {
x: [
0xc69fe67f, 0x97ea3e42, 0x21a7a603, 0x6c2e070d, 0x1657327b, 0xc3f1e7c1, 0x8dccb9e4,
0xffda5c3f, 0x4db0a1c0, 0x567e0973, 0x17bf4484, 0x39696a07,
],
y: [
0xc126b913, 0x5fc82572, 0x8f1cd403, 0x19109430, 0x994fe3e8, 0x74a8b026, 0xbe14794d,
0x27789964, 0x7735fde8, 0x328afd84, 0xcd4d4aa8, 0x72d40b42,
],
};
pub const VENDOR_ECC_KEY_0_PRIVATE: ImageEccPrivKey = [
0x29f939ea, 0x41746499, 0xd550c6fa, 0x6368b0d7, 0x61e09b4c, 0x75b21922, 0x86f96240, 0x00ea1d99,
0xace94ba6, 0x7ae89b0e, 0x3f210cf1, 0x9a45b6b5,
];
pub const VENDOR_ECC_KEY_1_PUBLIC: ImageEccPubKey = ImageEccPubKey {
x: [
0xa6309750, 0xf0a05ddb, 0x956a7f86, 0x2812ec4f, 0xec454e95, 0x3b53dbfb, 0x9eb54140,
0x15ea7507, 0x084af93c, 0xb7fa33fe, 0x51811ad5, 0xe754232e,
],
y: [
0xef5a5987, 0x7a0ce0be, 0x2621d2a9, 0x8bf3c5df, 0xaf7b3d6d, 0x97f24183, 0xa4a42038,
0x58c39b86, 0x272ef548, 0xe572b937, 0x1ecf1994, 0x1b8d4ea7,
],
};
pub const VENDOR_ECC_KEY_1_PRIVATE: ImageEccPrivKey = [
0xf2ee427b, 0x4412f46f, 0x8fb020a5, 0xc23b0154, 0xb3fcb201, 0xf93c2ee2, 0x923fd577, 0xf85320bb,
0x289eb276, 0x2b6b21d3, 0x5cdb3925, 0xa57d5043,
];
pub const VENDOR_ECC_KEY_2_PUBLIC: ImageEccPubKey = ImageEccPubKey {
x: [
0xa0d25693, 0xc4251e48, 0x185615b0, 0xa6c27f6d, 0xe62c39f5, 0xa9a32f75, 0x9553226a,
0x4d1926c1, 0x7928910f, 0xb7adc1b6, 0x89996733, 0x10134881,
],
y: [
0xbbdf72d7, 0x07c08100, 0xd54fcdad, 0xb1567bb0, 0x0522762b, 0x76b8dc4a, 0x846c175a,
0x3fbd0501, 0x9bdc8118, 0x4be5f33c, 0xbb21b41d, 0x93a8c523,
],
};
pub const VENDOR_ECC_KEY_2_PRIVATE: ImageEccPrivKey = [
0xaf72a74c, 0xfbbacc3c, 0x7ad2f9d9, 0xc969d1c9, 0x19c2d803, 0x0a53749a, 0xee730267, 0x7c11a52d,
0xee63e4c8, 0x0b5c0293, 0x28d35c27, 0x5f959aee,
];
pub const VENDOR_ECC_KEY_3_PUBLIC: ImageEccPubKey = ImageEccPubKey {
x: [
0x002a82b6, 0x8e03e9a0, 0xfd3b4c14, 0xca2cb3e8, 0x14350a71, 0x0e43956d, 0x21694fb4,
0xf34485e8, 0xf0e33583, 0xf7ea142d, 0x50e16f8b, 0x0225bb95,
],
y: [
0x5802641c, 0x7c45a4a2, 0x408e03a6, 0xa4100a92, 0x50fcc468, 0xd238cd0d, 0x449cc3e5,
0x1abc25e7, 0x0b05c426, 0x843dcd6f, 0x944ef6ff, 0xfa53ec5b,
],
};
pub const VENDOR_ECC_KEY_3_PRIVATE: ImageEccPrivKey = [
0xafbdfc7d, 0x36b54629, 0xd12c4cb5, 0x33926c30, 0x20611617, 0x86b50b23, 0x6046ff93, 0x17ea0144,
0xbc900c70, 0xb8cb36ac, 0x268b8079, 0xe3aeaaaf,
];
pub const VENDOR_LMS_KEY_0_PRIVATE: ImageLmsPrivKey = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x49, 0x08, 0xa1, 0x7b, 0xca, 0xdb, 0x18, 0x29, 0x1e, 0x28, 0x90, 0x58, 0xd5, 0xa8, 0xe3,
0xe8,
],
seed: bytes_to_words_6([
0x4d, 0xce, 0x1e, 0x1e, 0x77, 0x52, 0x53, 0xec, 0x07, 0xbc, 0x07, 0x90, 0xcb, 0x59, 0xb2,
0x73, 0x45, 0x86, 0xb0, 0x32, 0x86, 0xc7, 0x69, 0x74,
]),
};
pub const VENDOR_LMS_KEY_0_PUBLIC: ImageLmsPublicKey = ImageLmsPublicKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x49, 0x08, 0xa1, 0x7b, 0xca, 0xdb, 0x18, 0x29, 0x1e, 0x28, 0x90, 0x58, 0xd5, 0xa8, 0xe3,
0xe8,
],
digest: bytes_to_words_6([
0x64, 0xad, 0x3e, 0xb8, 0xbe, 0x68, 0x64, 0xf1, 0x7c, 0xcd, 0xa3, 0x8b, 0xde, 0x35, 0xed,
0xaa, 0x6c, 0x0d, 0xa5, 0x27, 0x64, 0x54, 0x07, 0xc6,
]),
};
pub const VENDOR_LMS_KEY_1_PRIVATE: ImageLmsPrivKey = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x7c, 0xb5, 0x36, 0x9d, 0x64, 0xe4, 0x28, 0x1d, 0x04, 0x6e, 0x97, 0x7c, 0x70, 0xd4, 0xd0,
0xa3,
],
seed: bytes_to_words_6([
0x57, 0x68, 0x5b, 0xb6, 0xe9, 0x46, 0x2b, 0x6b, 0xd3, 0x60, 0x21, 0xeb, 0xf0, 0x43, 0xb7,
0x56, 0x0c, 0x58, 0x1e, 0xbf, 0x7b, 0x50, 0xc5, 0x14,
]),
};
pub const VENDOR_LMS_KEY_1_PUBLIC: ImageLmsPublicKey = ImageLmsPublicKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x7c, 0xb5, 0x36, 0x9d, 0x64, 0xe4, 0x28, 0x1d, 0x04, 0x6e, 0x97, 0x7c, 0x70, 0xd4, 0xd0,
0xa3,
],
digest: bytes_to_words_6([
0x8e, 0xa4, 0x70, 0x1d, 0xad, 0xf7, 0xd7, 0x00, 0x05, 0x64, 0xb7, 0xd6, 0x1d, 0x1c, 0x95,
0x87, 0x9d, 0xd6, 0x47, 0x5c, 0x9c, 0x3a, 0xae, 0x0b,
]),
};
pub const VENDOR_LMS_KEY_2_PRIVATE: ImageLmsPrivKey = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x2b, 0xbb, 0x4b, 0x72, 0xc5, 0xb4, 0x1e, 0x05, 0xd2, 0xfa, 0xbe, 0x76, 0xf4, 0x17, 0x04,
0xbd,
],
seed: bytes_to_words_6([
0x73, 0xce, 0x8c, 0x94, 0xf7, 0xc9, 0xb0, 0x1c, 0xb8, 0x3a, 0x44, 0x27, 0xa9, 0x47, 0xb2,
0xa9, 0x44, 0x44, 0x46, 0xbd, 0xe2, 0x86, 0xe5, 0xe6,
]),
};
pub const VENDOR_LMS_KEY_2_PUBLIC: ImageLmsPublicKey = ImageLmsPublicKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x2b, 0xbb, 0x4b, 0x72, 0xc5, 0xb4, 0x1e, 0x05, 0xd2, 0xfa, 0xbe, 0x76, 0xf4, 0x17, 0x04,
0xbd,
],
digest: bytes_to_words_6([
0xdc, 0xb5, 0x3f, 0x96, 0x24, 0xd4, 0xc7, 0xb3, 0xc9, 0xae, 0x4d, 0x4c, 0x0e, 0x41, 0xe0,
0x8e, 0x3b, 0x15, 0x93, 0x96, 0x0f, 0xe6, 0xa2, 0x77,
]),
};
pub const VENDOR_LMS_KEY_3_PRIVATE: ImageLmsPrivKey = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x42, 0xcb, 0xa2, 0xe5, 0x57, 0x5b, 0x52, 0x35, 0x7e, 0xa7, 0xae, 0xad, 0xef, 0x54, 0x07,
0x4c,
],
seed: bytes_to_words_6([
0xba, 0x49, 0x06, 0x67, 0x17, 0x3f, 0xfe, 0x67, 0x15, 0x6e, 0xf2, 0x61, 0xac, 0xb4, 0xbc,
0x90, 0xcb, 0x4f, 0xa1, 0xbc, 0x26, 0xbb, 0xa2, 0x34,
]),
};
pub const VENDOR_LMS_KEY_3_PUBLIC: ImageLmsPublicKey = ImageLmsPublicKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x42, 0xcb, 0xa2, 0xe5, 0x57, 0x5b, 0x52, 0x35, 0x7e, 0xa7, 0xae, 0xad, 0xef, 0x54, 0x07,
0x4c,
],
digest: bytes_to_words_6([
0x5a, 0xa6, 0x0e, 0x27, 0x69, 0x25, 0x15, 0x99, 0x3a, 0xe8, 0xe2, 0x1f, 0x27, 0xcc, 0xdd,
0xed, 0x8f, 0xfc, 0xd3, 0xd2, 0x8e, 0xfb, 0xde, 0xc2,
]),
};
pub const VENDOR_MLDSA_KEY_0_PUBLIC: ImageMldsaPubKey = ImageMldsaPubKey([
0x3bf1c072, 0x227e937d, 0x8d98b669, 0x3adcaa6d, 0x11cd8ae7, 0x0dfc0c94, 0xe0d9cb25, 0x88aaa221,
0x74f8598a, 0x9ad20af2, 0xbd7f341c, 0xecfad6fe, 0x14574bc8, 0xdff12d65, 0x6ed928af, 0xca148658,
0x00d907d7, 0xd5e2a111, 0x542be345, 0xc5a3bed5, 0x248c7509, 0x5950a127, 0xa75cd598, 0x711f7458,
0x623f5b03, 0xebb289ac, 0x50258717, 0x569139f8, 0x2fb636db, 0xc03626c7, 0xdc0ba827, 0x28ac43fe,
0xc7cc34a9, 0x1be23bd8, 0x67b35b94, 0x9a3c5012, 0xacb1da1c, 0x3129e2bc, 0xa7bc6f3b, 0x3f752c2d,
0x728869d1, 0x56cac42d, 0x59b630cb, 0x6f6918fb, 0x25e50e09, 0x4fbdee27, 0x8deaa9b6, 0x9dc0b272,
0x9854f170, 0xc590f836, 0x7f3b01c0, 0x8d46fa2d, 0xf8869033, 0x097c8f2c, 0x65e0c23c, 0xb6f3f1bb,
0x2ac85f49, 0xd7d2d44f, 0x1ae7db5c, 0x677068dc, 0xa2fc63fd, 0x9382bf3b, 0xd3cb0bba, 0x4e19a123,
0xcff6ec9f, 0xd696984b, 0x8125506e, 0x5fd27133, 0x49a01ef6, 0x2ef9e501, 0xd6e2f030, 0x2d0cf054,
0xccc9bc29, 0xf6b9be29, 0xaf859ed5, 0x336ec1f6, 0x687fcad2, 0x57a70781, 0x588977d0, 0xfd83a550,
0xa7c6aa66, 0x361fb68d, 0xd50d5d89, 0xfb9fc776, 0x8d892a9e, 0x861fe766, 0x427fd1f6, 0x07dc3010,
0xd9bc9778, 0x57df22bc, 0xca6081dc, 0xeb9dad1a, 0xaa39628e, 0x1f2cb727, 0x76b567f0, 0x9bb2a7bb,
0xe2865cd3, 0x333601dc, 0x5f35c09b, 0xaabecdbd, 0xf238e9b9, 0xbe0da083, 0xafb15256, 0xdb33eba7,
0xa86a423e, 0x41f59d6f, 0x397321bc, 0x5ebffdab, 0x26351565, 0xdc7620d6, 0xb9abe454, 0x36c76ab2,
0x2b25f61b, 0x39a1998a, 0x3fc53427, 0xd527966e, 0xf585e75b, 0x339bfe05, 0x6f8cb822, 0xc23aee28,
0xc0a1043b, 0x0146a6f5, 0x032395c3, 0xa625ef28, 0xa9cbc554, 0x14a8ff8e, 0x61cd6fc2, 0x747cbd0b,
0x52c8f987, 0x8cd6b4b6, 0x6897d158, 0xc265975b, 0xfec17952, 0x7cf78109, 0x46e26d60, 0x168b84c8,
0x6201e4b4, 0x41f57eb2, 0xbcdd1a94, 0x52725376, 0xc0e53597, 0xe3eb1a93, 0xc2e35cbd, 0x85d45e80,
0x8b5419ef, 0xb7d15e5b, 0x5cf71ddc, 0x4bf700ce, 0x61dfdacf, 0x186bba2d, 0xab71f36b, 0xb41f53b7,
0xe83e927e, 0xab2a9a00, 0x704e9e75, 0xc66bd030, 0x20738340, 0x5615861d, 0xadc4cd44, 0x324e5392,
0xac343354, 0xeb4e7cc6, 0xd2a1ea13, 0x53557a65, 0x3606578a, 0x4af02cf4, 0xd3ddb64a, 0x27df5341,
0xa84c34b1, 0x13607996, 0x83c25c74, 0x147a2c10, 0x1260cc97, 0x14960735, 0x27291317, 0x19400a13,
0x27be4859, 0x00149426, 0xde3c1b6b, 0x619624f4, 0xfa6bcef5, 0xb654c371, 0xcb303e21, 0xfb7fa8f6,
0x0c753606, 0x8080aef8, 0x9b385007, 0xf1191614, 0x406184b1, 0x22e5bd3f, 0x7ab7dbc2, 0xd5af114d,
0x153e9ea1, 0x47b35bb9, 0x348a99ef, 0xea3302d3, 0x595e11be, 0x59a3d733, 0x8d6cf484, 0x6dcae9ce,
0xab7c39d6, 0xfb7f1c78, 0x1cd91930, 0xc276b24c, 0x6955b7be, 0x3d641b04, 0x434bc395, 0x83fc8b30,
0xc22c0066, 0xc2e2193e, 0x1cace644, 0xdca35c99, 0xebdb0ed7, 0x85db8fc4, 0x6eb974ce, 0x81735ed7,
0x44cf273e, 0x5419381d, 0x3a61d616, 0xbcce09e2, 0x8e8890a9, 0x3d75955f, 0x93faa93f, 0x933b892b,
0x8060345c, 0xb7d89c50, 0xa2808fee, 0x2f23404e, 0xfb0a18e3, 0x253b0400, 0x3336cf2f, 0x0ac1327e,
0x77299f70, 0xc034129f, 0xe57f328c, 0x333fca8c, 0x6c9ca3a2, 0x0fc30af0, 0xfa548984, 0x01ec4a90,
0xdb4e4c58, 0x1da8b01e, 0xf57b1f70, 0x6dd64ba3, 0xac88a3d3, 0x7858bc64, 0xafcaeb08, 0xc88a8e47,
0x4455d1c3, 0x22e63fb8, 0x44e768d5, 0xdbb95b9b, 0xa7cc7808, 0x7a058eca, 0x9a6702b8, 0x44b9da55,
0xe48940c7, 0x9bab364c, 0x9a48f848, 0x15dcf05b, 0x0a8f40b6, 0x6bf3661c, 0xb464ba62, 0x056fe333,
0xdf963785, 0x4c17b038, 0x514ad3ec, 0x9e794bd0, 0x3eb1f90c, 0x3292a34f, 0x88556541, 0x3abf6aa1,
0x20d9f756, 0xd0ecc544, 0x8d20a40a, 0x6d6a9b82, 0xaa6d2233, 0x95ce9fa2, 0x9c5a7dc4, 0xedca9aaf,
0x79fa256f, 0xdb817805, 0xb85b0cc6, 0xd412a46d, 0x8201c076, 0xbde2cd6a, 0x8704e31f, 0xedd8558d,
0xe6ee4fec, 0x1035c7bc, 0x72850ef6, 0xb1cb7bf5, 0x85a6802e, 0x68be53b0, 0xbd0cea80, 0xb09aff89,
0xe873c704, 0xd98895f6, 0x33e210c2, 0x6cbb35cc, 0xadc06de8, 0xffeda945, 0x2fcc0e84, 0x2fed6abe,
0x5d98f27c, 0x0db0cf12, 0x04b4ff2b, 0x33647644, 0x53aceac2, 0xdef8b0af, 0xd4c89116, 0x27307322,
0xbebbfe1e, 0x9a467d66, 0xe2b75788, 0x4e0fe56b, 0xbfe49617, 0x01f13994, 0xdfb2899b, 0xe1aa63a1,
0x8465dbea, 0xa5216dec, 0x585345f0, 0xfb14d5c3, 0xdba39959, 0x71f9394a, 0xa5d893be, 0x1f56753c,
0x2319c9c2, 0xfcbf16e1, 0x382c35fb, 0x7b5ad07a, 0x23ac9924, 0x26474750, 0xed760ad1, 0xa3da8298,
0x781e625e, 0x5dc9f693, 0xbd149e1c, 0xaca7c294, 0x8b65a984, 0x343260d4, 0xfb9863a0, 0x5408bba1,
0xa6ed4193, 0x5bea5b04, 0x7f9a7b1c, 0x72a86678, 0x60a5ee78, 0x5e71e572, 0xd895a20f, 0x8c8916b0,
0x0c273e24, 0x44ae8992, 0xd7286a17, 0x953ef103, 0x8ae31e25, 0xb7ff072b, 0x23c5a37d, 0xa77020e0,
0x622d7ff6, 0xd2c87173, 0xb7ba6186, 0x82d5354b, 0x1af05350, 0x23c8c800, 0x6e8ed4e3, 0x42ec1534,
0x8d4e25fa, 0x6b0faef2, 0xd3ee1336, 0x5e13d760, 0x5d87d4af, 0x38c4e49d, 0x688cd9a6, 0xdb4d753d,
0x5b509a96, 0x95cdffc6, 0x62355d78, 0x0b606082, 0xdcc60446, 0xf3b9e827, 0x586a147b, 0xb8cc0bcf,
0x4110678d, 0x58563e14, 0x24a318ba, 0x5486ab33, 0x4424d7b9, 0xde054151, 0x78322f7c, 0xbc49c078,
0xae9b1e93, 0xd254acd8, 0xc882de5f, 0x1be122a2, 0x94ced021, 0xd45ca951, 0x80d5939c, 0xc70eb2ae,
0x8804f726, 0x6feb1d91, 0xbcebf8bb, 0x2e09f612, 0xd0f1a86e, 0x8ee5a443, 0xd23e5b06, 0x660737d9,
0xdcd6b1c7, 0xd44f8df9, 0xbd580610, 0x18057561, 0x017541aa, 0x25fbec74, 0x5fc1e4c8, 0x738dce10,
0x6be83283, 0x2cdc5009, 0x8ae65569, 0xe38ec0f1, 0xc716d17c, 0xc24e0eab, 0x3d7bf44e, 0x659375da,
0x359d053d, 0xc664a669, 0xb3c82263, 0xc22a45fb, 0x2b15b61a, 0x72745fd2, 0x6829c8cc, 0x25276088,
0x7f7d4e36, 0xa17f6578, 0x9b6c1f02, 0x2732a902, 0x6b933100, 0x6b0d0718, 0x7a7bdf6a, 0xe2928822,
0x4cd4d37e, 0x2df6b059, 0x1df00d50, 0xe4237a30, 0xc70d2053, 0x3c07bf71, 0x47ad0170, 0x89e75e51,
0xa0f2ccc7, 0x6d2a4577, 0x410127f0, 0x4a06a95b, 0x64fb6b47, 0x672f9e55, 0x88a1e783, 0xdc66e03d,
0x476eae52, 0xcd0f00e2, 0x38cfff9f, 0x7535f8fc, 0xfeb51b50, 0xfca0c2bd, 0xc0daa43a, 0xe8ff9b4b,
0x66d5a656, 0x4c057a3e, 0xf5694943, 0x2b591d07, 0x943ebc67, 0x8df40ab0, 0xed55eaf6, 0x3574043c,
0xb12731b0, 0x48f111dd, 0x5c7fc292, 0x60272e40, 0x36ae656e, 0x31565487, 0x42780b20, 0xb5c6ae14,
0xcb871218, 0x2ab18540, 0x0ad717be, 0x1b235925, 0x891565d1, 0x7a7e568e, 0xc4bcd9e9, 0x315fc19f,
0x631095b5, 0x0fe516ab, 0x5c8a2af7, 0xe4a65938, 0x19538292, 0x3eb022ba, 0xb109d691, 0xd17181d2,
0x6298534e, 0x7d65b1f8, 0x0105950d, 0x3afaa11b, 0xf4cffc24, 0x576a7f81, 0xa2a610d2, 0xda277250,
0x7d39c765, 0x6ffd0f54, 0x31d741f1, 0x6a01f2e4, 0xc87a25bd, 0x444dbb8c, 0xc755dcb3, 0xb464b65a,
0x6623868d, 0x6837121c, 0x1f7cea35, 0x39e09a97, 0xdc64ea90, 0xae0e34ff, 0x72005629, 0xf33200c5,
0xa5a363c7, 0xa4089544, 0x4422eb76, 0x7a9e74f8, 0x033333be, 0x3fd130cd, 0x7d7fdb51, 0xb1d4f8fd,
0xa28b31a6, 0x1ab323ca, 0x306cea10, 0xf81f12d4, 0xc9470fe4, 0xa6ae2cf6, 0x7f5b611b, 0x815b5519,
0x7e88be8a, 0xae571035, 0x2224bd05, 0xb6902517, 0xbdf1520d, 0xbe974998, 0x869ab318, 0x3ae8b9a6,
0x938bebf4, 0x9a212229, 0xbd0d0eb4, 0xadad0026, 0x18b596e3, 0xd33391ce, 0x50731933, 0xf8fa3b15,
0xc544244a, 0x0877967e, 0xed854cc6, 0x5d5ec51e, 0x6494cecb, 0x3ec689fa, 0x0b87b8d5, 0x3f907672,
0x0c686fb2, 0xfa710f84, 0x85538eb9, 0xa9563669, 0x532d2505, 0xcce7f426, 0x3055aad7, 0x0c9c7ec1,
0x8a62e8e3, 0xdceffb9f, 0xa1fce07a, 0x992c0330, 0xa1b7fa5f, 0x600cdb00, 0xfbe4e69e, 0x4848468a,
0xc2498cf5, 0x7e548837, 0x28a9681b, 0xedce2c51, 0x83b8468a, 0x9c31b4f3, 0xfae38be0, 0xae66d8fb,
0x09bee0a0, 0x2b973e2c, 0x5806f734, 0xfde914e6, 0x967c039c, 0x8a920022, 0x60d05768, 0xb51fdc4c,
0xb4bc6cac, 0x16b26a97, 0xe889b1bf, 0x0fd3e0bd, 0x2c35965d, 0xbd1d8b6e, 0x278d0150, 0x0bf0a368,
0x23a24ee3, 0xd92b265a, 0x4b7f0a24, 0x9e0c06bf, 0xf3f3c409, 0x93a567a2, 0x41238fa5, 0x61d70de6,
0x48e8188e, 0x01a6434f, 0x94b3da75, 0xe2053eb5, 0x76ce7225, 0x15eb7872, 0x80cb24d5, 0xc5023d04,
0xee4de6bd, 0xab94ae4d, 0xb9682249, 0x74cd04c4, 0x28822443, 0xe9e3bf6d, 0xa1a74c9e, 0xa1d021de,
0x28858526, 0x0937aaac, 0x16c52197, 0xb452ddd5, 0xd39171b8, 0x18430130, 0x2fe1c686, 0x37234135,
0x0cfe2a0a, 0x6418372b, 0x4d2b039d, 0x9278ed03, 0x199fec8c, 0xeaa8f92e, 0x0860eb83, 0x0d3fd36b,
0xcd45025a, 0xc5fa5baf, 0x4fe308cb, 0x6defba30, 0x9426d46f, 0x128678c6, 0x0407e5b1, 0xd4cb5578,
]);
pub const VENDOR_MLDSA_KEY_0_PRIVATE: ImageMldsaPrivKey = ImageMldsaPrivKey([
0x3bf1c072, 0x227e937d, 0x8d98b669, 0x3adcaa6d, 0x11cd8ae7, 0x0dfc0c94, 0xe0d9cb25, 0x88aaa221,
0x07ae2191, 0xba7ed841, 0x699ee913, 0xec76ba8e, 0xa30b2fdb, 0x49dfc799, 0x8a0bb473, 0x39695109,
0x5994dd06, 0x230f0177, 0x00755028, 0x87f24693, 0xa9b6cda4, 0xb0f353c5, 0x21d414be, 0xc9a2d187,
0x29d0ca04, 0x5a5ea5e6, 0x81934449, 0x0e781b8e, 0x9a784f5f, 0x0337dc9b, 0x4b54a30d, 0x60167dca,
0x41914001, 0xc8598908, 0x6a024461, 0xd325b714, 0x96039022, 0x6524a268, 0x9885c282, 0x16244122,
0x2522922c, 0x220a14a1, 0x94180817, 0x8d94c830, 0x444db90b, 0x98237006, 0x61888b40, 0x448818e0,
0x871c0126, 0x21029c8c, 0xe124a894, 0x448a6500, 0x09b88346, 0x638e328b, 0x08a20128, 0x41012160,
0x2228a710, 0x829c2db1, 0x91150c4d, 0x8b2d3240, 0x984a2028, 0x41952184, 0x1048a714, 0xb88a8d40,
0x2914d384, 0x898da618, 0xa29c4148, 0x0e44036c, 0x6340b648, 0x90ca91c8, 0x70a45c05, 0xa1053602,
0x12618092, 0x84028b65, 0x1a440602, 0x46d26c89, 0x04229900, 0x5a5018c2, 0x851250a8, 0x10450a0d,
0xe2421424, 0x912045c0, 0x09a31085, 0xc860c324, 0x82db7134, 0x4144d350, 0xc8510089, 0xc84b4e02,
0x6d39232c, 0x9c093241, 0x17014542, 0x4180e126, 0xe04e0124, 0x44c38434, 0x64972146, 0xa341a311,
0x08439088, 0x31b29c86, 0x220140d9, 0xa6d20c02, 0x30b42050, 0x91424920, 0x22c24942, 0x1236a025,
0x246cc29b, 0x42cc0a25, 0x6098a124, 0x64604124, 0x48998138, 0x92425a92, 0x538e20e1, 0x150a4406,
0x4c984000, 0x9b0d9614, 0xb40a6016, 0x46401880, 0x594a40da, 0x10904e32, 0x80a4a288, 0x5a283019,
0x42434514, 0x25c25b2e, 0xc2811120, 0x96112230, 0x48c30b89, 0xda80c603, 0xa2d04520, 0x90b0996d,
0xca6c2311, 0x26814534, 0x2920d48c, 0xe3203641, 0x29108622, 0x49901031, 0xda69b44c, 0x14030e06,
0x6a264801, 0x22841842, 0x42411216, 0x2c991b4e, 0x0924a601, 0x04540085, 0x2192204a, 0xd24114ca,
0xc9122992, 0x0518500d, 0x5c0ca0db, 0x82517144, 0x32168428, 0x4b411602, 0x844880a0, 0x4cb90984,
0x8a10a8e0, 0x830a5188, 0x89c6c08c, 0x1b712284, 0xc6c96642, 0x85c92065, 0xdb822603, 0x14122116,
0x2d431840, 0xe34dc910, 0x80426a16, 0x9216d884, 0x1b85925a, 0x34e20231, 0x46081912, 0x190dc08b,
0xc91821b3, 0x88b0610c, 0x1b3124a1, 0xa31a0090, 0x50c8c921, 0x2149940b, 0x98e228c8, 0x25868264,
0xc00db922, 0x08a36a22, 0x4a466402, 0x44408040, 0x80208880, 0x85980b2d, 0x0208010a, 0xa29969a7,
0x70b80a48, 0x1080829a, 0x34587189, 0x7002ca91, 0x59212664, 0x35116da2, 0x29812090, 0x1b90c608,
0x30c260c0, 0x69b30920, 0x5361b920, 0x365b0996, 0x0e206062, 0xc3858400, 0x040a51b8, 0x69969184,
0x180c82d2, 0x125b0994, 0x45208c30, 0x4284c81c, 0xa3006016, 0x09c08061, 0xe342208b, 0xa89a0a22,
0x2647206c, 0x8a4e160b, 0x930b3122, 0x2c30ca01, 0x0168940c, 0x464b2032, 0x65245082, 0x89651881,
0xb6441222, 0x6818a230, 0x1a84c520, 0xb2a44642, 0x71a91845, 0x8a4634e0, 0x441c2510, 0x4610004c,
0x5810a48b, 0x36610e08, 0x31225064, 0x41850904, 0x84c42e02, 0x0d169364, 0xa26e2263, 0x190a6d90,
0x0c90d92c, 0x048cb0d3, 0xa70205c1, 0x81b8416c, 0xc1294093, 0x911c64b2, 0x64c2c370, 0x000d9711,
0x384c84c8, 0x82489c49, 0x0240264a, 0x39182837, 0x2998d989, 0x50710661, 0x08484090, 0x6e48e06a,
0x2170a010, 0x991c5023, 0x32385049, 0x4152420c, 0x48c01136, 0x49b44424, 0x10702852, 0x95145238,
0x6130a220, 0x2465080b, 0x425a7180, 0x6584494a, 0xd40e1711, 0x32834c88, 0x8916e18c, 0x210206e1,
0x18224619, 0x2516dc11, 0xc1061048, 0x49014520, 0x45c60a2e, 0x1a4a0202, 0xc7224646, 0x84b49149,
0xe2718452, 0x48dc7042, 0x2948200e, 0x1c421298, 0x091b6cc5, 0x41c09c4e, 0x6248485b, 0xc2826514,
0x32240909, 0xd4520441, 0x47130114, 0x4018516d, 0x59404713, 0x98438210, 0x6cc5134c, 0xa47016cc,
0x92d42c86, 0x70c48269, 0x1010b293, 0x141b8488, 0x6230e04d, 0x018596e0, 0x95006149, 0x51b6a044,
0xd4021440, 0x06046c08, 0x4d404868, 0xa29136d9, 0x160a6592, 0x1096ca2c, 0xc1890121, 0x24906db8,
0x85164b0c, 0x90061502, 0x969b6034, 0x20244441, 0xd38128d8, 0x22210044, 0x51c61351, 0x1291b024,
0x48cb1046, 0x2880e202, 0x632c38d2, 0x32dc5124, 0x8210c10e, 0x0900b844, 0x480a44b3, 0x2c842431,
0x1c8dc208, 0x08934606, 0x3038648d, 0x10083201, 0xb44091b3, 0x4e24038c, 0x444d0319, 0xa2147134,
0x2d224168, 0xd489811b, 0x12812a36, 0x8d36a345, 0x0021231c, 0xb7017107, 0x4d189380, 0x912da90c,
0x184810b2, 0x4a402028, 0xe4119481, 0x06594512, 0x0a42e445, 0x82401480, 0x968a68b6, 0x9096e044,
0x0148b0a3, 0x12108519, 0x9019118e, 0x4924c892, 0x14c12808, 0x40810481, 0x42852661, 0x28094044,
0x8d911886, 0xd4243920, 0x064b8840, 0x20b89330, 0xe4810923, 0x884b6088, 0x85b31245, 0xd8803208,
0x02a409a6, 0x1099194a, 0xc26118c3, 0x180181c8, 0x62202382, 0x1831309c, 0x38983084, 0x8092e189,
0x98093040, 0xc2946582, 0x25246088, 0x03658210, 0x18109113, 0x05845c24, 0xe344485c, 0x251c8e06,
0x49a0800a, 0x120038e4, 0x82046022, 0x45450288, 0x93713082, 0x381b44c0, 0x48885c08, 0xcc65288a,
0x228b9138, 0x25492040, 0x2169c209, 0x25042c35, 0x0d94e082, 0x4c85a8c0, 0xb0dc50c2, 0x20490165,
0xc1754097, 0x4cb9c57c, 0x8fecd875, 0xbe34d4cf, 0xf09e92f7, 0x7ffebecc, 0x545e8bbb, 0x1b035ec2,
0x91f8eed9, 0x9e0c496e, 0x3382b03b, 0x38df460a, 0x00cb9667, 0x31ec616b, 0x0868f004, 0x82c9cfbf,
0xbbc2b573, 0x3c54b59a, 0xeabd6a02, 0xd271a634, 0x758a62c9, 0xe2fb7648, 0x1b43b3a1, 0x7af7fb2c,
0x69ff0cfd, 0x1ca282dd, 0x0e59b26d, 0x930a5f8a, 0xb2c10f04, 0xd9d7ae28, 0x28532821, 0x6f5709cf,
0xb6d34eaf, 0x6de68258, 0xbfa19d62, 0x41f50ab3, 0xcac0db15, 0xca46cd8c, 0xa9818bf3, 0x865cfee6,
0x4a24ac09, 0x48ce2d1c, 0x1941d6e9, 0x67b048c9, 0x56a87107, 0x25b18a90, 0x8959a498, 0xec7f0851,
0x81702e9f, 0xe36fea7f, 0x9946d40b, 0xb16e1bd3, 0x21cb9139, 0x8e885879, 0x2ce4c5cc, 0x9073af79,
0xa418e616, 0x66aaca74, 0x3661e548, 0xeb2e303d, 0xeb6e0ddf, 0x1d0702fc, 0x6023b8c3, 0x418f2bbd,
0xa2679a52, 0xb8e88f2c, 0xbd7bb924, 0xe667fd5b, 0xa9fddff5, 0x30685201, 0x14fa19a5, 0x836edabc,
0x6f7be4be, 0x89245eb5, 0x0eeb496c, 0x04746521, 0x2a131110, 0x6bd2b5ce, 0xe846a2db, 0x3c734b93,
0xda746ec3, 0x8c909cc7, 0x0ec68262, 0xaaf20c15, 0x990b9ff0, 0xceb08250, 0xdfaa9ab7, 0xfa4b1d44,
0x8644be4d, 0x04b8212d, 0x334015d8, 0x49204de1, 0x8a33f8e1, 0x435f3305, 0xff3364d9, 0x2260d1f1,
0x80c14442, 0x9fcc108d, 0x980449bf, 0xc9e080b3, 0xae374910, 0xefc56377, 0x5bb618b7, 0x12e6870f,
0xb6965482, 0x541a599c, 0x3f657979, 0xfdb2808a, 0x66746fc0, 0x2e2cf9fb, 0xb7cf7757, 0x7057bc3a,
0x6c82dcee, 0xba52bdcc, 0x1db92d1d, 0x65f4e40c, 0x1ad71972, 0x268434a5, 0xfa79f85e, 0x0fb13456,
0x13f5ee45, 0x3a2a1fb9, 0xcd0182a4, 0x0d31593e, 0x49e65a3c, 0x9129ec3b, 0x5351d291, 0x942588b2,
0xd6e3f133, 0x26d57549, 0x479933e0, 0xfa33f237, 0xe3af8c37, 0x2e19caf7, 0xd5f4c742, 0xf91378e3,
0x3c1b55cd, 0xe33fa5fc, 0x8cfcebfe, 0x070406db, 0xbaedaa23, 0x6ee82efd, 0x76eafb0b, 0x6d956fb7,
0xd8257c59, 0x2274cb46, 0xdbe30a33, 0x1273a4be, 0xc64691c3, 0x7093441d, 0xaa295884, 0xe903b69a,
0x61bbde38, 0x6efae70f, 0x417357be, 0x023a9713, 0x2769e7cc, 0x42c06311, 0xe5ee6a09, 0x49bc9e7b,
0x3c6cc3c0, 0xe91506c6, 0xd8f79cbc, 0x82bb9314, 0xd43b6e01, 0x41488d61, 0x2bd4568e, 0x4f7f096b,
0x7b9b53c0, 0x6daee623, 0xf9e79cfc, 0xf2397828, 0x95ad34c2, 0x991c4ff7, 0x864d497a, 0x5dd5ec06,
0x1e81a61b, 0xb9c8aba7, 0x196985ca, 0xd59f178b, 0x8ae30ac1, 0xa8c2edb1, 0x15cf9834, 0x8bae73b4,
0xa32f1523, 0x8e02c59d, 0xba286f23, 0x9d9d1d91, 0x233e48c0, 0xd76a7da6, 0x51ca4928, 0xaf9b6cd8,
0xf94a2acf, 0x05d27748, 0xa57e8e57, 0x97fd45b0, 0x77c07e53, 0x73b3fa21, 0x9b15952d, 0x1a481281,
0x78fd24b3, 0x609e10bf, 0x472e0702, 0xf1268d76, 0xab2b537b, 0x0b571f79, 0x4177a259, 0x53b9a435,
0x0d095b80, 0x883cacb8, 0x4393945a, 0x283acfa7, 0x82bbee47, 0xd92cd5f6, 0x373f5e66, 0xa263d414,
0x50e6b8da, 0x935b152f, 0x7d43f9b9, 0xfe577769, 0x59058881, 0xe928bbba, 0x42f7d3ba, 0x321d1483,
0x1259dc2e, 0x4000dc92, 0x04b38bcd, 0xe486267a, 0x7310f32f, 0x082d0740, 0x7a53a6c0, 0x5c79caf1,
0x59670f69, 0x59d3898d, 0x45a84297, 0x75dacbd4, 0xcf33dc37, 0xd79171b7, 0xf0c76023, 0x4cf15861,
0xbe20739d, 0xac634f00, 0x68dadc95, 0x20d2507b, 0x9e69a8dc, 0x3c20ab5f, 0xde02dde4, 0x7afc2518,
0x3d399b10, 0x9838575c, 0xa6c05535, 0x8c2f1e04, 0xf197fe9d, 0xc9b29c0a, 0x6b648471, 0xc669e65a,
0x2208fbce, 0x0af17cf1, 0xd9d60d6c, 0xda88254e, 0x9353efc1, 0x8f260b8c, 0x60e8f401, 0x9809ea9c,
0x457535e0, 0x60968444, 0x3e199909, 0xa829e600, 0x12b938b6, 0x2dd084a2, 0xd639cc83, 0x4bcc8073,
0xbba73a55, 0xccda9aba, 0x14c853ca, 0xe4d7f7ff, 0xeeb4cd1e, 0xfb503fa8, 0xb0978ecf, 0x80d8e8b7,
0x44eb2b60, 0xaca02e64, 0x42da9e72, 0x59c1ec2f, 0x34a61c2a, 0xcebe8370, 0x9bd2126c, 0x6c76d14d,
0xb005bc1e, 0x8260d912, 0xefed7505, 0x07f16283, 0xef894477, 0xb18117c3, 0x9ad87412, 0x2da31a02,
0x917c79a7, 0xb9246c75, 0x25f6fbe9, 0xf3ca6939, 0xf4fc57c6, 0xac2535c7, 0x05928766, 0x3b667b5f,
0xea48a51a, 0xeccf147e, 0x137ef1ed, 0xfe5b07fe, 0x01c279a5, 0x30c73088, 0xcb1fefdf, 0x6f35b390,
0x70d88e8b, 0x0b99c416, 0xb0e131f6, 0xd591b237, 0x77b7a795, 0x4dafee9d, 0x11012bbd, 0x3cfd259a,
0xcedded8b, 0x94e79394, 0x405b507e, 0x4a66452e, 0x82543cf3, 0x4df6365c, 0xeeda8b7b, 0xe69ee1f6,
0x3bfb2852, 0xdbfe7981, 0xaba2d1c0, 0x99d9df45, 0x3ef07132, 0x435e0a22, 0x9cb3190b, 0x961caa7a,
0x1a9be88d, 0xd77bb523, 0x4bc934ee, 0xb4757271, 0xbc72a291, 0x3ebd9ded, 0xfd552c70, 0xdbf7eaed,
0xab67c8a0, 0xc227684b, 0xc83ebc03, 0xcd13ad38, 0x0d26f47f, 0x0d6e7f79, 0x7f20ae2a, 0xffde136c,
0x991cb88b, 0x69f6ec95, 0x77c10d33, 0xedf81fbc, 0xf14ad225, 0xb0651e1d, 0x6074fb1c, 0x30bc8482,
0xf2802d16, 0x39fd3e6d, 0x244a9b90, 0xd6f2137e, 0x1de9e88e, 0x40eb2b6c, 0xc2d0111b, 0xd9d5a97d,
0xe1cda86c, 0x8fe1883b, 0xea521273, 0xcb5966be, 0xae26fb93, 0xe901a5fd, 0xb10dfe6c, 0xa1290d7f,
0x1a52b5fb, 0x495480e4, 0x781faed1, 0xd040ded4, 0x68dee954, 0xe4158200, 0xcd31ce8e, 0x7bf765ff,
0x6cb0fae4, 0x638ff2d6, 0x2169a63b, 0xe56f52bb, 0x3796c700, 0x1a682c66, 0x34a80c82, 0x235cc15d,
0xad6f86d9, 0xf2a734a5, 0x1a681d01, 0x51b4a735, 0x6741e655, 0x153d7758, 0xb700de79, 0x282f14c0,
0x8d5c51b6, 0x4d3b604e, 0xbde89550, 0xadb5520f, 0x4c1b5bc1, 0x624e85b8, 0x2b9a5e5b, 0x9bc40a85,
0xdcf5031b, 0xa2cbfdeb, 0xac64b20c, 0x7e89170c, 0xb3e5b4b4, 0xb32f5c35, 0xd5acecdf, 0x9e16bbf4,
0x83e36319, 0x8d77bfc2, 0x5cb10d04, 0x100e5ffa, 0x402caecd, 0x30ba71f0, 0xcfdacbe9, 0xf661c000,
0xe9ecd13b, 0x19f49bb2, 0x09afc8af, 0x93a4b985, 0xa2044bcb, 0x85511c92, 0xe8497757, 0xd057345e,
0x279ee93e, 0x3c96a823, 0x768d22da, 0x7e8e05b7, 0x96f44e6e, 0xa24a8dd7, 0x230eadbb, 0x28a00470,
0x5faafb31, 0x8694022f, 0x8d5847f5, 0x50551cb2, 0x29004d37, 0xa2f4547e, 0xa685e030, 0xdbb27f1d,
0xa6482e58, 0x81f681ac, 0x190e7ffd, 0x2014ecb7, 0x61a54355, 0xe79ca4f0, 0x9f3fee73, 0x8acde8fd,
0x2df96b10, 0x8ad37865, 0x2a202508, 0xb3b1bb14, 0x1dae1e43, 0x45de0c22, 0x3e8c3d9c, 0xc128dca5,
0x983f75d2, 0x09296c58, 0x77988fdb, 0xb291fc98, 0xc5d665b8, 0x685d4df8, 0x96b4269c, 0x81ecb8a5,
0x1d0646f1, 0xc42f91b0, 0x8b7ec2c2, 0xd726ba54, 0xbd1170d0, 0x7d2825a3, 0x2532873b, 0x9d02282f,
0xbc25f19c, 0x4c1adb81, 0x4e27dcc0, 0xd026654b, 0xab2e3e96, 0x489971be, 0xef909b8c, 0xcbfa3724,
0x6779864e, 0x7bd78514, 0x8c5d0df2, 0xf3ef7181, 0x3c0cd466, 0x66956841, 0xa7b0308a, 0x33649d42,
0x5123ea2c, 0xd81c98e5, 0xf3d3e024, 0x7158aaaa, 0xe3cc3fce, 0x33fae274, 0xe15e89d0, 0xfed57449,
0xa884d288, 0x13611e0b, 0x5e2444c0, 0xa40be1c3, 0x8808ce35, 0x037d646b, 0x100648bd, 0xbd63fd0f,
0xd4e708b2, 0x583d781e, 0xce3fa6c7, 0xe7a68695, 0xb8df174f, 0xd5be3b7e, 0x6ae718b0, 0x2de25f8a,
0xa83b19e8, 0x7fa7d864, 0x57255584, 0xd2220f9d, 0x473a7c87, 0xa8a7af11, 0x0cdb1a56, 0xc806f569,
0x1f0c2118, 0xe39dee5a, 0x93f7cb14, 0x40fa636e, 0x500214c5, 0x15624b79, 0xf68f86fe, 0x5d69235a,
0x22c7674a, 0x1448e2cb, 0x01c73578, 0xdcbd0771, 0x0977f936, 0xfd5f860d, 0xe49c8fe6, 0xcd6e7d00,
0x193e1dd4, 0xac1c10bd, 0xbba719e3, 0x01fdd9af, 0xa0abf212, 0xc942d7c7, 0x32aef3bf, 0xc048f45d,
0x864ff9a4, 0x4e8a0e8f, 0x2eb382d7, 0x41c2858b, 0xd78b9b55, 0xdba3abd5, 0x358bad24, 0x55aaeefa,
0x7e50d1df, 0xc6d4c66f, 0x452ffb00, 0x6f7af9ea, 0x72f67cf0, 0x967a3946, 0x11b4ab90, 0x6bbf3dec,
0x38339a57, 0x7afd0d85, 0x89428198, 0x4f8bc922, 0x5f1a1471, 0xa67beb22, 0xe102d41f, 0x81aee5e4,
0x23d4719d, 0xace6e75f, 0xf407033a, 0xf817d268, 0xda420827, 0x3f29b858, 0x311402d0, 0x94f7b8dd,
0xfd8b2267, 0x4ef8f644, 0x1bc05724, 0xed462688, 0xebb474d4, 0x07e88d66, 0x2b4a3ee2, 0xd58e0279,
0xdcb6aab1, 0xb5661ec2, 0x407f94d7, 0x430783ca, 0xd564d1bd, 0xac3f0965, 0x36e5488e, 0x475f7a33,
0x3aefe0cd, 0x57afb2a0, 0x1ecf443c, 0x4d31ba13, 0x29000e9b, 0xeedfb9b5, 0xfd7bdbe7, 0x60c5bb97,
0x8d2ed2fd, 0x3a04678b, 0x0c9b1a2b, 0xcc540eec, 0x9e58df0c, 0x57f43d18, 0x261e136d, 0x46775baa,
0xa6e123e1, 0x899095a1, 0x2765ca71, 0x0cf3694a, 0x2d821529, 0x1358f175, 0x7e7f289c, 0xb614e0db,
0x96ac4c1e, 0xa82a7cea, 0x576e78f6, 0x152bbb07, 0x810e79d6, 0xf96a6c12, 0x90e82cab, 0xf4961f1c,
0x0b99f08d, 0x46ba799f, 0xf7d50110, 0xc18b58db, 0x63494735, 0xfb35b8de, 0x947c07d8, 0x418749f6,
0x6a15e173, 0xbf5dc5cc, 0x20864bfa, 0xb8f9ca32, 0xc2dc05e0, 0xdbd9eb40, 0x65d0b74e, 0x344f20eb,
0x7bab3276, 0xc105b7cc, 0xcb1ea258, 0x834d1717, 0x66fb0c09, 0x78b1f894, 0x1d1234f9, 0xcda3cae1,
0x48b38beb, 0xae348864, 0xafd30378, 0x3a4b2ca3, 0x2ae5a63d, 0x40f1095b, 0xf7528dbb, 0x31b01f20,
0x8621d0c2, 0x9df798ce, 0x93a8de11, 0x584c6fbb, 0xd4a7812c, 0x95c99890, 0x33180393, 0x3b28de78,
0x8c369335, 0x9815bbef, 0x77093d98, 0xb8fb7946, 0xa4ca5da9, 0xc9080d78, 0x3cc3f993, 0x9cadcda0,
0x75ccc369, 0xb48281d3, 0x5490b681, 0x29f947bd, 0x01f57351, 0xc54d6622, 0xa9773409, 0x9579163b,
0x426b0de1, 0xae5e8029, 0xe573a762, 0x5f9e08ab, 0x7e0d06a3, 0x614117e1, 0xa75e27bd, 0x771ff267,
0x88e6b441, 0x5d7be9e5, 0xc785b56b, 0xded2d500, 0x58dc3881, 0xf501cc53, 0xf79e5441, 0xbdb0fe37,
0xa672c9c5, 0xc5ece816, 0xfbc55164, 0x1360945a, 0xb343ccae, 0x128d4bbc, 0x4c760143, 0x84373bfe,
0x648076e3, 0xbccc521b, 0xedc11e3f, 0x961748f8, 0xf96614bf, 0x0384cb51, 0x9a9ca4a8, 0x4f281b2e,
0xba82dfc7, 0xe753133e, 0x0f00f0f2, 0x8aebef9b, 0x10f0cf58, 0x99e392e9, 0xf70bc777, 0x9523da7e,
0xc18ed55e, 0x3e95e6e3, 0x1370a79e, 0x2af7ae22, 0xb7a85109, 0xe4cbbc51, 0xa3681d0d, 0xa0bda53d,
0xbac91f90, 0x8daece52, 0xa61a9f8c, 0x4552f41e, 0x81040714, 0x4d266261, 0x91cd8e5d, 0x6220a0d3,
0xa30312e0, 0x589bf9e8, 0x8627be3c, 0x84eb84f8, 0x69fb5beb, 0xf6781793, 0xf133929e, 0xb7f93753,
0x3f743c56, 0x67996475, 0x8d4ed18c, 0x28a729a4, 0xbeee2a11, 0x04b88bcd, 0x54b61986, 0x264139fa,
0xccd89203, 0xc477df55, 0xa1e4a76d, 0x2c14352a, 0x8ecf34a8, 0x9bd29c78, 0xa5ffb86a, 0xbb83cc39,
0xa6b5d008, 0x2c0ac5e2, 0xa8d355e7, 0x24ff3db2, 0x42d33742, 0x8a11286b, 0x2d40a103, 0x35fe851e,
0xc98e16e8, 0x076e01c6, 0x6d87805c, 0x8b7673cc, 0xf0cdcf8d, 0xe9ea973f, 0x61a97367, 0xdf8d670f,
0xfe691655, 0xd485aeb3, 0x2b6a1e7c, 0xf94d6b23, 0x4ed1fb37, 0x648b0973, 0x3bc0c161, 0x2d37f880,
0x332ffefa, 0x5605f2f4, 0xdd7ed6fa, 0x56ac9a78, 0x8c611ce4, 0x2cc64256, 0x6292fa4a, 0x610566bd,
0x26cc20ee, 0x8d5ed38b, 0xfb4f9e69, 0xa18dad9d, 0xeb615b9f, 0x634919fb, 0x4b213ef9, 0x6c38b6a4,
0xac217c77, 0x94bfda3b, 0xba46ddd1, 0xecdadacb, 0xbba1ab2d, 0x3f12b8e7, 0xca3712ec, 0x880b867e,
0x86d7e99f, 0x21dea5bf, 0x0f26ddc5, 0x6f799fa7, 0xda7777d1, 0x362fa4ee, 0xaea96d43, 0x32ac40a4,
0x453d80fc, 0x7fbafbce, 0x718f3a51, 0x0faec872, 0x934c047f, 0x2c2586af, 0x9c3597f5, 0xeb4469ce,
]);
pub const VENDOR_MLDSA_KEY_1_PUBLIC: ImageMldsaPubKey = ImageMldsaPubKey([
0x6c3432f4, 0xc90e6d09, 0x25d9f804, 0x6b231215, 0xcb1cfde3, 0x3aeda9bd, 0xfe2d8664, 0xd52ebd31,
0x5329f634, 0x1fa5874f, 0x4655b295, 0x7b9f51ce, 0xa8edad3f, 0x32532178, 0xf40c42cc, 0x3e80296d,
0xdae6d5f4, 0xfd405743, 0x1608f99b, 0xb887c651, 0xa3a23745, 0xdd629581, 0xba41c876, 0xb6d25bbc,
0xa9e23863, 0x324ee4b4, 0x79277b40, 0xfc2d1cae, 0xaf55ad96, 0xa6f2d137, 0x263d1f6f, 0xada2e8e4,
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/serde/src/lib.rs | image/serde/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
Caliptra Image Bundle serialization & deserialization routines.
--*/
use caliptra_image_types::*;
use std::io::Write;
use zerocopy::IntoBytes;
/// Image Bundle Writer
pub struct ImageBundleWriter<W: Write> {
writer: W,
}
impl<W: Write> ImageBundleWriter<W> {
/// Create an instance of `ImageBundleWriter`
pub fn new(writer: W) -> Self {
Self { writer }
}
/// Write Image Bundle
pub fn write(&mut self, image: &ImageBundle) -> anyhow::Result<()> {
self.writer.write_all(image.manifest.as_bytes())?;
self.writer.write_all(&image.fmc)?;
self.writer.write_all(&image.runtime)?;
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/elf/src/lib.rs | image/elf/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains ELF Executable loading and parsing related functionality.
--*/
use anyhow::{bail, Context};
use caliptra_image_gen::ImageGeneratorExecutable;
use caliptra_image_types::ImageRevision;
use elf::abi::PT_LOAD;
use elf::endian::AnyEndian;
use elf::ElfBytes;
use std::path::PathBuf;
/// ELF Executable
#[derive(Default)]
pub struct ElfExecutable {
version: u32,
rev: ImageRevision,
load_addr: u32,
entry_point: u32,
content: Vec<u8>,
}
fn load_into_image(
image: &mut Vec<u8>,
image_base_addr: u32,
section_addr: u32,
section_data: &[u8],
) -> anyhow::Result<()> {
if section_addr < image_base_addr {
bail!("Section address 0x{section_addr:08x} is below image base address 0x{image_base_addr:08x}");
}
let section_offset = usize::try_from(section_addr - image_base_addr).unwrap();
image.resize(
usize::max(image.len(), section_offset + section_data.len()),
u8::default(),
);
image[section_offset..][..section_data.len()].copy_from_slice(section_data);
Ok(())
}
impl ElfExecutable {
pub fn open(path: &PathBuf, version: u32, rev: ImageRevision) -> anyhow::Result<Self> {
let file_data = std::fs::read(path).with_context(|| "Failed to read file")?;
ElfExecutable::new(&file_data, version, rev)
}
/// Create new instance of `ElfExecutable`.
pub fn new(elf_bytes: &[u8], version: u32, rev: ImageRevision) -> anyhow::Result<Self> {
let mut content = vec![];
let elf_file = ElfBytes::<AnyEndian>::minimal_parse(elf_bytes)
.with_context(|| "Failed to parse elf file")?;
let Some(segments) = elf_file.segments() else {
bail!("ELF file has no segments");
};
let Some(load_addr) = segments
.iter()
.filter(|s| s.p_type == PT_LOAD)
.map(|s| s.p_paddr as u32)
.min()
else {
bail!("ELF file has no LOAD segments");
};
for segment in segments {
if segment.p_type != PT_LOAD {
continue;
}
let segment_data = elf_file.segment_data(&segment)?;
if segment_data.is_empty() {
continue;
}
load_into_image(
&mut content,
load_addr,
segment.p_paddr as u32,
segment_data,
)?;
}
let entry_point = elf_file.ehdr.e_entry as u32;
Ok(Self {
version,
rev,
load_addr,
entry_point,
content,
})
}
}
impl ImageGeneratorExecutable for ElfExecutable {
/// Executable Version Number
fn version(&self) -> u32 {
self.version
}
/// Executable Revision
fn rev(&self) -> &ImageRevision {
&self.rev
}
/// Executable load address
fn load_addr(&self) -> u32 {
self.load_addr
}
/// Executable entry point
fn entry_point(&self) -> u32 {
self.entry_point
}
/// Executable content
fn content(&self) -> &Vec<u8> {
&self.content
}
/// Executable size
fn size(&self) -> u32 {
self.content.len() as u32
}
}
#[cfg(test)]
mod test {
use crate::load_into_image;
#[test]
fn test_load_into_image() {
let mut image = Vec::new();
load_into_image(&mut image, 0x4000_0000, 0x4000_0006, b"hello world").unwrap();
load_into_image(&mut image, 0x4000_0000, 0x4000_0000, b"abcdef").unwrap();
load_into_image(&mut image, 0x4000_0000, 0x4000_0011, b"hi").unwrap();
assert_eq!(&image, b"abcdefhello worldhi");
}
#[test]
fn test_load_into_image_bad_address() {
let mut image = Vec::new();
assert_eq!(
load_into_image(&mut image, 0x4000_0000, 0x3fff_ffff, b"h")
.unwrap_err()
.to_string(),
"Section address 0x3fffffff is below image base address 0x40000000"
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/crypto/src/rustcrypto.rs | image/crypto/src/rustcrypto.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains crypto utilities needed to generate images.
--*/
use core::{ops::Deref, str::from_utf8};
use std::path::Path;
use anyhow::{anyhow, bail, Context};
use caliptra_image_gen::{
from_hw_format, to_hw_format, ImageGeneratorCrypto, ImageGeneratorHasher,
};
use caliptra_image_types::*;
use fips204::ml_dsa_87::{PrivateKey, PublicKey, SIG_LEN};
use fips204::traits::{SerDes, Signer, Verifier};
use zerocopy::IntoBytes;
use {
ecdsa::{elliptic_curve::sec1::ToEncodedPoint, signature::hazmat::PrehashSigner},
p384::pkcs8::DecodePublicKey,
rand::{rngs::OsRng, RngCore},
sec1::DecodeEcPrivateKey,
sha2::{Digest, Sha256, Sha384, Sha512},
};
use crate::{sign_with_lms_key, Sha256Hasher, SUPPORTED_LMS_Q_VALUE};
#[derive(Default)]
pub struct RustCrypto {}
pub struct RustCryptoSha256Hasher(Sha256);
impl ImageGeneratorHasher for RustCryptoSha256Hasher {
type Output = [u32; SHA256_DIGEST_WORD_SIZE];
fn update(&mut self, data: &[u8]) {
self.0.update(data)
}
fn finish(self) -> Self::Output {
to_hw_format(&self.0.finalize())
}
}
impl ImageGeneratorCrypto for RustCrypto {
type Sha256Hasher = RustCryptoSha256Hasher;
fn sha256_start(&self) -> Self::Sha256Hasher {
RustCryptoSha256Hasher(Sha256::default())
}
fn sha384_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest384> {
let mut engine = Sha384::new();
engine.update(data);
Ok(to_hw_format(&engine.finalize()))
}
fn ecdsa384_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageEccPrivKey,
_pub_key: &ImageEccPubKey,
) -> anyhow::Result<ImageEccSignature> {
let priv_key: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(priv_key);
let digest: [u8; SHA384_DIGEST_BYTE_SIZE] = from_hw_format(digest);
let sig: p384::ecdsa::Signature =
p384::ecdsa::SigningKey::from_slice(&priv_key)?.sign_prehash(&digest)?;
let r = &sig.r().deref().to_bytes();
let s = &sig.s().deref().to_bytes();
let image_sig = ImageEccSignature {
r: to_hw_format(&r),
s: to_hw_format(&s),
};
Ok(image_sig)
}
fn lms_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageLmsPrivKey,
) -> anyhow::Result<ImageLmsSignature> {
let message: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(digest);
let mut nonce = [0u8; SHA192_DIGEST_BYTE_SIZE];
OsRng.fill_bytes(&mut nonce);
sign_with_lms_key::<RustCryptoHasher>(priv_key, &message, &nonce, SUPPORTED_LMS_Q_VALUE)
}
// [TODO][CAP2]: Update to use RustCrypto API when available.
fn mldsa_sign(
&self,
msg: &[u8],
priv_key: &ImageMldsaPrivKey,
pub_key: &ImageMldsaPubKey,
) -> anyhow::Result<ImageMldsaSignature> {
// Private key is received in hw format which is also the library format.
// Unlike ECC, no reversal of the DWORD endianess needed.
let priv_key_bytes: [u8; MLDSA87_PRIV_KEY_BYTE_SIZE] = priv_key
.0
.as_bytes()
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid private key size"))?;
let priv_key = { PrivateKey::try_from_bytes(priv_key_bytes).unwrap() };
let signature = priv_key.try_sign_with_seed(&[0u8; 32], msg, &[]).unwrap();
let signature_extended = {
let mut sig = [0u8; SIG_LEN + 1];
sig[..SIG_LEN].copy_from_slice(&signature);
sig
};
let pub_key = {
let pub_key_bytes: [u8; MLDSA87_PUB_KEY_BYTE_SIZE] = pub_key
.0
.as_bytes()
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid public key size"))?;
PublicKey::try_from_bytes(pub_key_bytes).unwrap()
};
if !pub_key.verify(msg, &signature, &[]) {
bail!("MLDSA public key verification failed");
}
// Return the signature in hw format (which is also the library format)
// Unlike ECC, no reversal of the DWORD endianess needed.
let mut sig: ImageMldsaSignature = ImageMldsaSignature::default();
for (i, chunk) in signature_extended.chunks(4).enumerate() {
sig.0[i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
Ok(sig)
}
fn ecc_pub_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPubKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read public key PEM file {}", path.display()))?;
let pub_key =
p384::PublicKey::from_public_key_pem(from_utf8(&key_bytes)?)?.to_encoded_point(false);
let x = pub_key.x().ok_or(anyhow!("Error parsing x coordinate"))?;
let y = pub_key.y().ok_or(anyhow!("Error parsing y coordinate"))?;
let image_key = ImageEccPubKey {
x: to_hw_format(&x),
y: to_hw_format(&y),
};
Ok(image_key)
}
fn ecc_priv_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPrivKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read private key PEM file {}", path.display()))?;
let priv_key = p384::ecdsa::SigningKey::from_sec1_pem(from_utf8(&key_bytes)?)?.to_bytes();
Ok(to_hw_format(&priv_key))
}
fn sha512_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest512> {
let mut engine = Sha512::new();
engine.update(data);
Ok(to_hw_format(&engine.finalize()))
}
}
pub struct RustCryptoHasher(Sha256);
impl Sha256Hasher for RustCryptoHasher {
fn new() -> Self {
Self(Sha256::new())
}
fn update(&mut self, bytes: &[u8]) {
self.0.update(bytes)
}
fn finish(self) -> [u8; 32] {
self.0.finalize().into()
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/crypto/src/lib.rs | image/crypto/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains crypto utilities needed to generate images.
--*/
use std::path::PathBuf;
use anyhow::{anyhow, Context};
use caliptra_image_types::*;
use caliptra_lms_types::{LmotsAlgorithmType, LmsAlgorithmType};
#[cfg(feature = "openssl")]
mod openssl;
#[cfg(feature = "rustcrypto")]
mod rustcrypto;
#[cfg(feature = "openssl")]
pub use crate::openssl::*;
#[cfg(feature = "rustcrypto")]
pub use crate::rustcrypto::*;
use zerocopy::{FromBytes, IntoBytes};
const LMS_TREE_GEN_SUPPORTED_FULL_HEIGHT: u8 = 10u8;
const SUPPORTED_LMS_Q_VALUE: u32 = 5u32;
// LMS-SHA192-H5
const IMAGE_LMS_TREE_TYPE_HT_5: LmsAlgorithmType = LmsAlgorithmType::LmsSha256N24H5;
// LMOTS-SHA192-W8
const IMAGE_LMS_OTS_TYPE_8: LmotsAlgorithmType = LmotsAlgorithmType::LmotsSha256N24W8;
const D_PBLC: u16 = 0x8080;
const D_MESG: u16 = 0x8181;
const D_LEAF: u16 = 0x8282;
const D_INTR: u16 = 0x8383;
pub trait Sha256Hasher: Sized {
/// Create a new Sha256Hasher
fn new() -> Self;
/// Adds a chunk to the running hash.
///
/// # Arguments
///
/// * `bytes` - Value to add to hash.
fn update(&mut self, bytes: &[u8]);
/// Finish a running hash operation and return the result.
///
/// Once this function has been called, the object can no longer be used and
/// a new one must be created to hash more data.
fn finish(self) -> [u8; 32];
}
/// Read LMS SHA192 public Key from PEM file
pub fn lms_pub_key_from_pem(path: &PathBuf) -> anyhow::Result<ImageLmsPublicKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read public key PEM file {}", path.display()))?;
ImageLmsPublicKey::read_from_bytes(&key_bytes[..])
.map_err(|_| anyhow!("Error parsing LMS public key"))
}
/// Read LMS SHA192 private Key from PEM file
pub fn lms_priv_key_from_pem(path: &PathBuf) -> anyhow::Result<ImageLmsPrivKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read private key PEM file {}", path.display()))?;
ImageLmsPrivKey::read_from_bytes(&key_bytes[..])
.map_err(|_| anyhow!("Error parsing LMS priv key"))
}
fn generate_lmots_pubkey_helper<T: Sha256Hasher>(
id: &[u8],
q: u32,
p: usize,
w: u8,
seed: &[u8],
k: &mut [u8],
) {
let mut x = vec![0u8; p * SHA192_DIGEST_BYTE_SIZE];
gen_x::<T>(id, q, p, seed, &mut x);
gen_k::<T>(id, q, p, w, &x, k);
}
fn coefficient(s: &[u8], i: usize, w: usize) -> anyhow::Result<u8> {
let bitmask: u16 = (1 << (w)) - 1;
let index = i * w / 8;
if index >= s.len() {
return Err(anyhow!("Error invalid coeff index"));
}
let b = s[index];
// extra logic to avoid the divide by 0
// which a good compiler would notice only happens when w is 0 and that portion of the
// expression could be skipped
let mut shift = 8;
if w != 0 {
shift = 8 - (w * (i % (8 / w)) + w);
}
// Rust errors if we try to shift off all of the bits off from a value
// some implementations 0 fill, others do some other filling.
// we make this be 0
let mut rs = 0;
if shift < 8 {
rs = b >> shift;
}
let small_bitmask = bitmask as u8;
Ok(small_bitmask & rs)
}
fn stack_top_mut(st: &mut [u8], st_index: usize) -> &mut [u8] {
&mut st[st_index * SHA192_DIGEST_BYTE_SIZE..][..SHA192_DIGEST_BYTE_SIZE]
}
fn stack_top(st: &[u8], st_index: usize) -> &[u8] {
&st[st_index * SHA192_DIGEST_BYTE_SIZE..][..SHA192_DIGEST_BYTE_SIZE]
}
// https://www.rfc-editor.org/rfc/rfc8554.html#appendix-A
fn gen_x<T: Sha256Hasher>(id: &[u8], q: u32, p: usize, seed: &[u8], x: &mut [u8]) {
for i in 0..p {
let offset = i * SHA192_DIGEST_BYTE_SIZE;
let x_i = &mut x[offset..][..SHA192_DIGEST_BYTE_SIZE];
let idx: [u8; 1] = [0xff];
let i_str: [u8; 2] = (i as u16).to_be_bytes();
let q_str: [u8; 4] = q.to_be_bytes();
let mut hasher = T::new();
hasher.update(id);
hasher.update(&q_str);
hasher.update(&i_str);
hasher.update(&idx);
hasher.update(seed);
x_i.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
}
}
fn gen_k<T: Sha256Hasher>(id: &[u8], q: u32, p: usize, w: u8, x: &[u8], k: &mut [u8]) {
let mut y = vec![0u8; p * SHA192_DIGEST_BYTE_SIZE];
for i in 0..p {
let offset = i * SHA192_DIGEST_BYTE_SIZE;
let tmp = &mut y[offset..][..SHA192_DIGEST_BYTE_SIZE];
let x_i = &x[offset..][..SHA192_DIGEST_BYTE_SIZE];
tmp.clone_from_slice(x_i);
let i_str: [u8; 2] = (i as u16).to_be_bytes();
let width: u16 = (1 << w) - 1;
let chain_len: u8 = width as u8;
for j in 0..chain_len {
let j_str: [u8; 1] = [j];
let mut hasher = T::new();
hasher.update(id);
hasher.update(&q.to_be_bytes());
hasher.update(&i_str);
hasher.update(&j_str);
hasher.update(tmp);
tmp.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
}
}
let mut hasher = T::new();
hasher.update(id);
hasher.update(&q.to_be_bytes());
hasher.update(&D_PBLC.to_be_bytes());
hasher.update(&y[..]);
k.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
}
// https://datatracker.ietf.org/doc/html/rfc8554#appendix-C
fn generate_lms_pubkey_helper<T: Sha256Hasher>(
id: &[u8],
ots_alg: LmotsAlgorithmType,
tree_height: u8,
seed: &[u8],
q: Option<u32>,
pub_key: &mut Option<ImageLmsPublicKey>,
sig: &mut Option<ImageLmsSignature>,
) {
let mut target_node: u32 = match pub_key {
Some(_) => 1,
None => (((1 << tree_height) as u32) + q.unwrap()) ^ 1,
};
let mut k = [0u8; SHA192_DIGEST_BYTE_SIZE];
let zero_k = [0u8; SHA192_DIGEST_BYTE_SIZE];
let mut level: usize = 0;
let mut pub_key_stack = vec![0u8; SHA192_DIGEST_BYTE_SIZE * (tree_height as usize)];
let mut stack_idx: usize = 0;
let max_idx: u32 = 1 << tree_height;
let (p, w) = match ots_alg {
IMAGE_LMS_OTS_TYPE_8 => (26usize, 8u8),
_ => (51usize, 4u8),
};
for i in 0..max_idx {
// TODO: We only support a fixed Q in larger trees
if tree_height <= LMS_TREE_GEN_SUPPORTED_FULL_HEIGHT || i == SUPPORTED_LMS_Q_VALUE {
generate_lmots_pubkey_helper::<T>(id, i, p, w, seed, &mut k[..]);
} else {
k[..].copy_from_slice(&zero_k[..]);
}
let mut r: u32 = i + (1 << tree_height);
let mut r_str: [u8; 4] = r.to_be_bytes();
let mut hasher = T::new();
hasher.update(id);
hasher.update(&r_str);
hasher.update(&D_LEAF.to_be_bytes());
hasher.update(&k[..]);
k.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
let mut j: u32 = i;
let mut cur_node: u32 = (1 << tree_height) + i;
while j % 2 == 1 {
r >>= 1;
j >>= 1;
// pop left_side (i.e T[r]) from stack
stack_idx -= 1;
// Before mixing left and right nodes, check if left node is needed to be
// filled in the signature path.
if cur_node == target_node + 1 {
if let Some(sig_val) = sig.as_mut() {
sig_val.tree_path[level]
.as_mut_bytes()
.copy_from_slice(stack_top(&pub_key_stack, stack_idx));
level += 1;
}
target_node = (target_node >> 1) ^ 1;
}
// Before mixing left and right nodes, check if right node is needed to be
// filled in the signature path.
if cur_node == target_node {
if let Some(sig_val) = sig.as_mut() {
sig_val.tree_path[level]
.as_mut_bytes()
.copy_from_slice(&k[..]);
level += 1;
}
target_node = (target_node >> 1) ^ 1;
}
r_str = r.to_be_bytes();
cur_node >>= 1;
// temp = H(I || u32str(r) || u16str(D_INTR) || left_side || temp)
hasher = T::new();
hasher.update(id);
hasher.update(&r_str);
hasher.update(&D_INTR.to_be_bytes());
hasher.update(stack_top(&pub_key_stack, stack_idx));
hasher.update(&k[..]);
k.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
}
// push K onto the data stack
stack_top_mut(&mut pub_key_stack, stack_idx).clone_from_slice(&k[..]);
stack_idx += 1;
}
// Pop top from stack (should be 1) when requested for public key.
if let Some(pub_key_val) = pub_key {
stack_idx -= 1;
pub_key_val
.digest
.as_mut_bytes()
.clone_from_slice(stack_top(&pub_key_stack, stack_idx));
}
}
// https://datatracker.ietf.org/doc/html/rfc8554#section-4.5
fn generate_ots_signature_helper<T: Sha256Hasher>(
message: &[u8],
ots_alg: LmotsAlgorithmType,
id: &[u8],
seed: &[u8],
rand: &[u8],
q: u32,
) -> ImageLmOTSSignature {
let (alg_p, width, ls) = match ots_alg {
LmotsAlgorithmType::LmotsSha256N24W8 => (26usize, 8usize, 0u8),
_ => (51usize, 4usize, 4u8),
};
let mut sig = ImageLmOTSSignature {
ots_type: ots_alg,
..Default::default()
};
sig.nonce.as_mut_bytes().clone_from_slice(rand);
let mut q_arr = [0u8; SHA192_DIGEST_BYTE_SIZE];
let mut hasher = T::new();
hasher.update(id);
hasher.update(&q.to_be_bytes());
hasher.update(&D_MESG.to_be_bytes());
hasher.update(rand);
hasher.update(message);
q_arr.clone_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
let mut checksum: u16 = 0;
let data_coeff: usize = (SHA192_DIGEST_BYTE_SIZE * 8) / width;
let alg_chksum_max: u16 = (1 << width) - 1;
for i in 0..data_coeff {
checksum += alg_chksum_max - (coefficient(&q_arr, i, width).unwrap() as u16);
}
checksum <<= ls;
let checksum_str: [u8; 2] = checksum.to_be_bytes();
let mut x = vec![0u8; alg_p * SHA192_DIGEST_BYTE_SIZE];
gen_x::<T>(id, q, alg_p, seed, &mut x);
for i in 0..alg_p {
let a: u8 = if i < data_coeff {
coefficient(&q_arr, i, width).unwrap()
} else {
coefficient(&checksum_str, i - data_coeff, width).unwrap()
};
let offset: usize = i * SHA192_DIGEST_BYTE_SIZE;
let tmp: &mut [u8] = &mut x[offset..][..SHA192_DIGEST_BYTE_SIZE];
let i_str: [u8; 2] = (i as u16).to_be_bytes();
for j in 0..a {
let j_str: [u8; 1] = [j];
hasher = T::new();
hasher.update(id);
hasher.update(&q.to_be_bytes());
hasher.update(&i_str);
hasher.update(&j_str);
hasher.update(tmp);
tmp.copy_from_slice(&hasher.finish()[..SHA192_DIGEST_BYTE_SIZE]);
}
let sig_val = &mut sig.y[i];
sig_val.as_mut_bytes().clone_from_slice(tmp);
}
sig
}
#[allow(unused)]
fn generate_lms_pubkey<T: Sha256Hasher>(
priv_key: &ImageLmsPrivKey,
) -> anyhow::Result<ImageLmsPublicKey> {
match priv_key.tree_type {
IMAGE_LMS_TREE_TYPE => {}
IMAGE_LMS_TREE_TYPE_HT_5 => {}
_ => return Err(anyhow!("Error looking up lms tree type")),
};
match priv_key.otstype {
IMAGE_LMS_OTS_TYPE => {}
IMAGE_LMS_OTS_TYPE_8 => {}
_ => return Err(anyhow!("Error looking up lms ots type")),
};
let height = match priv_key.tree_type {
IMAGE_LMS_TREE_TYPE => 15,
IMAGE_LMS_TREE_TYPE_HT_5 => 5,
_ => return Err(anyhow!("Error parsing lms parameters")),
};
let mut pub_key = Some(ImageLmsPublicKey::default());
if let Some(x) = pub_key.as_mut() {
x.otstype = priv_key.otstype;
x.id = priv_key.id;
x.tree_type = priv_key.tree_type;
}
generate_lms_pubkey_helper::<T>(
&priv_key.id,
priv_key.otstype,
height,
priv_key.seed.as_bytes(),
None,
&mut pub_key,
&mut None,
);
Ok(pub_key.unwrap())
}
fn sign_with_lms_key<T: Sha256Hasher>(
priv_key: &ImageLmsPrivKey,
message: &[u8],
nonce: &[u8],
q: u32,
) -> anyhow::Result<ImageLmsSignature> {
match priv_key.tree_type {
IMAGE_LMS_TREE_TYPE => {}
IMAGE_LMS_TREE_TYPE_HT_5 => {}
_ => return Err(anyhow!("Error looking up lms tree type")),
};
match priv_key.otstype {
IMAGE_LMS_OTS_TYPE => {}
IMAGE_LMS_OTS_TYPE_8 => {}
_ => return Err(anyhow!("Error looking up lms ots type")),
};
let height = match priv_key.tree_type {
IMAGE_LMS_TREE_TYPE => 15,
IMAGE_LMS_TREE_TYPE_HT_5 => 5,
_ => return Err(anyhow!("Error parsing lms parameters")),
};
if q >= (1 << height) {
return Err(anyhow!("Invalid q"));
}
let ots_sig = generate_ots_signature_helper::<T>(
message,
priv_key.otstype,
&priv_key.id,
priv_key.seed.as_bytes(),
nonce,
q,
);
let mut sig = Some(ImageLmsSignature::default());
if let Some(x) = sig.as_mut() {
x.q = q.into();
x.ots = ots_sig;
x.tree_type = priv_key.tree_type;
}
generate_lms_pubkey_helper::<T>(
&priv_key.id,
priv_key.otstype,
height,
priv_key.seed.as_bytes(),
Some(q),
&mut None,
&mut sig,
);
Ok(sig.unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "openssl")]
use ::openssl::rand::rand_bytes;
use caliptra_lms_types::bytes_to_words_6;
#[cfg(feature = "rustcrypto")]
use rand::{rngs::OsRng, RngCore};
use zerocopy::{LittleEndian, U32};
#[test]
#[ignore]
fn test_print_lms_private_pub_key() {
let mut priv_key: ImageLmsPrivKey = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
..Default::default()
};
for i in 0..4 {
#[cfg(feature = "openssl")]
rand_bytes(&mut priv_key.id).unwrap();
#[cfg(feature = "openssl")]
rand_bytes(priv_key.seed.as_mut_bytes()).unwrap();
#[cfg(feature = "rustcrypto")]
OsRng.fill_bytes(&mut priv_key.id);
#[cfg(feature = "rustcrypto")]
OsRng.fill_bytes(priv_key.seed.as_mut_bytes());
#[cfg(feature = "openssl")]
let pub_key = generate_lms_pubkey::<OpensslHasher>(&priv_key).unwrap();
#[cfg(feature = "rustcrypto")]
let pub_key = generate_lms_pubkey::<RustCryptoHasher>(&priv_key).unwrap();
println!("pub const VENDOR_LMS_KEY{i}_PRIVATE: ImageLmsPrivKey = {priv_key:#04x?};");
println!("pub const VENDOR_LMS_KEY{i}_PUBLIC: ImageLmsPublicKey = {pub_key:#04x?};");
}
for i in 0..1 {
#[cfg(feature = "openssl")]
rand_bytes(&mut priv_key.id).unwrap();
#[cfg(feature = "openssl")]
rand_bytes(priv_key.seed.as_mut_bytes()).unwrap();
#[cfg(feature = "rustcrypto")]
OsRng.fill_bytes(&mut priv_key.id);
#[cfg(feature = "rustcrypto")]
OsRng.fill_bytes(priv_key.seed.as_mut_bytes());
#[cfg(feature = "openssl")]
let pub_key = generate_lms_pubkey::<OpensslHasher>(&priv_key).unwrap();
#[cfg(feature = "rustcrypto")]
let pub_key = generate_lms_pubkey::<RustCryptoHasher>(&priv_key).unwrap();
println!("pub const OWNER_LMS_KEY{i}_PRIVATE: ImageLmsPrivKey = {priv_key:#04x?};");
println!("pub const OWNER_LMS_KEY{i}_PUBLIC: ImageLmsPublicKey = {pub_key:#04x?};");
}
}
#[test]
fn test_lms() {
let priv_key = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE_HT_5,
otstype: IMAGE_LMS_OTS_TYPE_8,
id: [
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
0x2e, 0x2f,
],
seed: bytes_to_words_6([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
]),
};
let expected_pub_key = ImageLmsPublicKey {
tree_type: IMAGE_LMS_TREE_TYPE_HT_5,
otstype: IMAGE_LMS_OTS_TYPE_8,
id: priv_key.id,
digest: bytes_to_words_6([
0x2c, 0x57, 0x14, 0x50, 0xae, 0xd9, 0x9c, 0xfb, 0x4f, 0x4a, 0xc2, 0x85, 0xda, 0x14,
0x88, 0x27, 0x96, 0x61, 0x83, 0x14, 0x50, 0x8b, 0x12, 0xd2,
]),
};
#[cfg(feature = "openssl")]
let pub_key = generate_lms_pubkey::<OpensslHasher>(&priv_key).unwrap();
#[cfg(feature = "rustcrypto")]
let pub_key = generate_lms_pubkey::<RustCryptoHasher>(&priv_key).unwrap();
assert_eq!(expected_pub_key, pub_key);
}
#[test]
fn test_lms_sig() {
let priv_key = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE_HT_5,
otstype: IMAGE_LMS_OTS_TYPE_8,
id: [
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
0x2e, 0x2f,
],
seed: bytes_to_words_6([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
]),
};
let expected_ots_sig: [[U32<LittleEndian>; 6]; 51] = [
bytes_to_words_6([
0xe1, 0x3b, 0x9f, 0x08, 0x75, 0xf0, 0x93, 0x61, 0xdc, 0x77, 0xfc, 0xc4, 0x48, 0x1e,
0xa4, 0x63, 0xc0, 0x73, 0x71, 0x62, 0x49, 0x71, 0x91, 0x93,
]),
bytes_to_words_6([
0x61, 0x4b, 0x83, 0x5b, 0x46, 0x94, 0xc0, 0x59, 0xf1, 0x2d, 0x3a, 0xed, 0xd3, 0x4f,
0x3d, 0xb9, 0x3f, 0x35, 0x80, 0xfb, 0x88, 0x74, 0x3b, 0x8b,
]),
bytes_to_words_6([
0x3d, 0x06, 0x48, 0xc0, 0x53, 0x7b, 0x7a, 0x50, 0xe4, 0x33, 0xd7, 0xea, 0x9d, 0x66,
0x72, 0xff, 0xfc, 0x5f, 0x42, 0x77, 0x0f, 0xea, 0xb4, 0xf9,
]),
bytes_to_words_6([
0x8e, 0xb3, 0xf3, 0xb2, 0x3f, 0xd2, 0x06, 0x1e, 0x4d, 0x0b, 0x38, 0xf8, 0x32, 0x86,
0x0a, 0xe7, 0x66, 0x73, 0xad, 0x1a, 0x1a, 0x52, 0xa9, 0x00,
]),
bytes_to_words_6([
0x5d, 0xcf, 0x1b, 0xfb, 0x56, 0xfe, 0x16, 0xff, 0x72, 0x36, 0x27, 0x61, 0x2f, 0x9a,
0x48, 0xf7, 0x90, 0xf3, 0xc4, 0x7a, 0x67, 0xf8, 0x70, 0xb8,
]),
bytes_to_words_6([
0x1e, 0x91, 0x9d, 0x99, 0x91, 0x9c, 0x8d, 0xb4, 0x81, 0x68, 0x83, 0x8c, 0xec, 0xe0,
0xab, 0xfb, 0x68, 0x3d, 0xa4, 0x8b, 0x92, 0x09, 0x86, 0x8b,
]),
bytes_to_words_6([
0xe8, 0xec, 0x10, 0xc6, 0x3d, 0x8b, 0xf8, 0x0d, 0x36, 0x49, 0x8d, 0xfc, 0x20, 0x5d,
0xc4, 0x5d, 0x0d, 0xd8, 0x70, 0x57, 0x2d, 0x6d, 0x8f, 0x1d,
]),
bytes_to_words_6([
0x90, 0x17, 0x7c, 0xf5, 0x13, 0x7b, 0x8b, 0xbf, 0x7b, 0xcb, 0x67, 0xa4, 0x6f, 0x86,
0xf2, 0x6c, 0xfa, 0x5a, 0x44, 0xcb, 0xca, 0xa4, 0xe1, 0x8d,
]),
bytes_to_words_6([
0xa0, 0x99, 0xa9, 0x8b, 0x0b, 0x3f, 0x96, 0xd5, 0xac, 0x8a, 0xc3, 0x75, 0xd8, 0xda,
0x2a, 0x7c, 0x24, 0x80, 0x04, 0xba, 0x11, 0xd7, 0xac, 0x77,
]),
bytes_to_words_6([
0x5b, 0x92, 0x18, 0x35, 0x9c, 0xdd, 0xab, 0x4c, 0xf8, 0xcc, 0xc6, 0xd5, 0x4c, 0xb7,
0xe1, 0xb3, 0x5a, 0x36, 0xdd, 0xc9, 0x26, 0x5c, 0x08, 0x70,
]),
bytes_to_words_6([
0x63, 0xd2, 0xfc, 0x67, 0x42, 0xa7, 0x17, 0x78, 0x76, 0x47, 0x6a, 0x32, 0x4b, 0x03,
0x29, 0x5b, 0xfe, 0xd9, 0x9f, 0x2e, 0xaf, 0x1f, 0x38, 0x97,
]),
bytes_to_words_6([
0x05, 0x83, 0xc1, 0xb2, 0xb6, 0x16, 0xaa, 0xd0, 0xf3, 0x1c, 0xd7, 0xa4, 0xb1, 0xbb,
0x0a, 0x51, 0xe4, 0x77, 0xe9, 0x4a, 0x01, 0xbb, 0xb4, 0xd6,
]),
bytes_to_words_6([
0xf8, 0x86, 0x6e, 0x25, 0x28, 0xa1, 0x59, 0xdf, 0x3d, 0x6c, 0xe2, 0x44, 0xd2, 0xb6,
0x51, 0x8d, 0x1f, 0x02, 0x12, 0x28, 0x5a, 0x3c, 0x2d, 0x4a,
]),
bytes_to_words_6([
0x92, 0x70, 0x54, 0xa1, 0xe1, 0x62, 0x0b, 0x5b, 0x02, 0xaa, 0xb0, 0xc8, 0xc1, 0x0e,
0xd4, 0x8a, 0xe5, 0x18, 0xea, 0x73, 0xcb, 0xa8, 0x1f, 0xcf,
]),
bytes_to_words_6([
0xff, 0x88, 0xbf, 0xf4, 0x61, 0xda, 0xc5, 0x1e, 0x7a, 0xb4, 0xca, 0x75, 0xf4, 0x7a,
0x62, 0x59, 0xd2, 0x48, 0x20, 0xb9, 0x99, 0x57, 0x92, 0xd1,
]),
bytes_to_words_6([
0x39, 0xf6, 0x1a, 0xe2, 0xa8, 0x18, 0x6a, 0xe4, 0xe3, 0xc9, 0xbf, 0xe0, 0xaf, 0x2c,
0xc7, 0x17, 0xf4, 0x24, 0xf4, 0x1a, 0xa6, 0x7f, 0x03, 0xfa,
]),
bytes_to_words_6([
0xed, 0xb0, 0x66, 0x51, 0x15, 0xf2, 0x06, 0x7a, 0x46, 0x84, 0x3a, 0x4c, 0xbb, 0xd2,
0x97, 0xd5, 0xe8, 0x3b, 0xc1, 0xaa, 0xfc, 0x18, 0xd1, 0xd0,
]),
bytes_to_words_6([
0x3b, 0x3d, 0x89, 0x4e, 0x85, 0x95, 0xa6, 0x52, 0x60, 0x73, 0xf0, 0x2a, 0xb0, 0xf0,
0x8b, 0x99, 0xfd, 0x9e, 0xb2, 0x08, 0xb5, 0x9f, 0xf6, 0x31,
]),
bytes_to_words_6([
0x7e, 0x55, 0x45, 0xe6, 0xf9, 0xad, 0x5f, 0x9c, 0x18, 0x3a, 0xbd, 0x04, 0x3d, 0x5a,
0xcd, 0x6e, 0xb2, 0xdd, 0x4d, 0xa3, 0xf0, 0x2d, 0xbc, 0x31,
]),
bytes_to_words_6([
0x67, 0xb4, 0x68, 0x72, 0x0a, 0x4b, 0x8b, 0x92, 0xdd, 0xfe, 0x79, 0x60, 0x99, 0x8b,
0xb7, 0xa0, 0xec, 0xf2, 0xa2, 0x6a, 0x37, 0x59, 0x82, 0x99,
]),
bytes_to_words_6([
0x41, 0x3f, 0x7b, 0x2a, 0xec, 0xd3, 0x9a, 0x30, 0xce, 0xc5, 0x27, 0xb4, 0xd9, 0x71,
0x0c, 0x44, 0x73, 0x63, 0x90, 0x22, 0x45, 0x1f, 0x50, 0xd0,
]),
bytes_to_words_6([
0x1c, 0x04, 0x57, 0x12, 0x5d, 0xa0, 0xfa, 0x44, 0x29, 0xc0, 0x7d, 0xad, 0x85, 0x9c,
0x84, 0x6c, 0xbb, 0xd9, 0x3a, 0xb5, 0xb9, 0x1b, 0x01, 0xbc,
]),
bytes_to_words_6([
0x77, 0x0b, 0x08, 0x9c, 0xfe, 0xde, 0x6f, 0x65, 0x1e, 0x86, 0xdd, 0x7c, 0x15, 0x98,
0x9c, 0x8b, 0x53, 0x21, 0xde, 0xa9, 0xca, 0x60, 0x8c, 0x71,
]),
bytes_to_words_6([
0xfd, 0x86, 0x23, 0x23, 0x07, 0x2b, 0x82, 0x7c, 0xee, 0x7a, 0x7e, 0x28, 0xe4, 0xe2,
0xb9, 0x99, 0x64, 0x72, 0x33, 0xc3, 0x45, 0x69, 0x44, 0xbb,
]),
bytes_to_words_6([
0x7a, 0xef, 0x91, 0x87, 0xc9, 0x6b, 0x3f, 0x5b, 0x79, 0xfb, 0x98, 0xbc, 0x76, 0xc3,
0x57, 0x4d, 0xd0, 0x6f, 0x0e, 0x95, 0x68, 0x5e, 0x5b, 0x3a,
]),
bytes_to_words_6([
0xef, 0x3a, 0x54, 0xc4, 0x15, 0x5f, 0xe3, 0xad, 0x81, 0x77, 0x49, 0x62, 0x9c, 0x30,
0xad, 0xbe, 0x89, 0x7c, 0x4f, 0x44, 0x54, 0xc8, 0x6c, 0x49,
]),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
];
let message: [u8; 28] = [
0x54, 0x65, 0x73, 0x74, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x20, 0x66,
0x6f, 0x72, 0x20, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x2d, 0x31, 0x39, 0x32, 0x0a,
];
let nonce = [
0x0b, 0x50, 0x40, 0xa1, 0x8c, 0x1b, 0x5c, 0xab, 0xcb, 0xc8, 0x5b, 0x04, 0x74, 0x02,
0xec, 0x62, 0x94, 0xa3, 0x0d, 0xd8, 0xda, 0x8f, 0xc3, 0xda,
];
let expected_tree_path = [
bytes_to_words_6([
0xe9, 0xca, 0x10, 0xea, 0xa8, 0x11, 0xb2, 0x2a, 0xe0, 0x7f, 0xb1, 0x95, 0xe3, 0x59,
0x0a, 0x33, 0x4e, 0xa6, 0x42, 0x09, 0x94, 0x2f, 0xba, 0xe3,
]),
bytes_to_words_6([
0x38, 0xd1, 0x9f, 0x15, 0x21, 0x82, 0xc8, 0x07, 0xd3, 0xc4, 0x0b, 0x18, 0x9d, 0x3f,
0xcb, 0xea, 0x94, 0x2f, 0x44, 0x68, 0x24, 0x39, 0xb1, 0x91,
]),
bytes_to_words_6([
0x33, 0x2d, 0x33, 0xae, 0x0b, 0x76, 0x1a, 0x2a, 0x8f, 0x98, 0x4b, 0x56, 0xb2, 0xac,
0x2f, 0xd4, 0xab, 0x08, 0x22, 0x3a, 0x69, 0xed, 0x1f, 0x77,
]),
bytes_to_words_6([
0x19, 0xc7, 0xaa, 0x7e, 0x9e, 0xee, 0x96, 0x50, 0x4b, 0x0e, 0x60, 0xc6, 0xbb, 0x5c,
0x94, 0x2d, 0x69, 0x5f, 0x04, 0x93, 0xeb, 0x25, 0xf8, 0x0a,
]),
bytes_to_words_6([
0x58, 0x71, 0xcf, 0xfd, 0x13, 0x1d, 0x0e, 0x04, 0xff, 0xe5, 0x06, 0x5b, 0xc7, 0x87,
0x5e, 0x82, 0xd3, 0x4b, 0x40, 0xb6, 0x9d, 0xd9, 0xf3, 0xc1,
]),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
];
#[cfg(feature = "openssl")]
let sig = sign_with_lms_key::<OpensslHasher>(&priv_key, &message, &nonce, 5).unwrap();
#[cfg(feature = "rustcrypto")]
let sig = sign_with_lms_key::<RustCryptoHasher>(&priv_key, &message, &nonce, 5).unwrap();
assert_eq!(
sig,
ImageLmsSignature {
q: 5.into(),
ots: ImageLmOTSSignature {
ots_type: IMAGE_LMS_OTS_TYPE_8,
nonce: bytes_to_words_6(nonce),
y: expected_ots_sig,
},
tree_type: IMAGE_LMS_TREE_TYPE_HT_5,
tree_path: expected_tree_path,
}
);
}
#[test]
fn test_lms_sig_h15() {
let priv_key = ImageLmsPrivKey {
tree_type: IMAGE_LMS_TREE_TYPE,
otstype: IMAGE_LMS_OTS_TYPE,
id: [
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
0x2e, 0x2f,
],
seed: bytes_to_words_6([
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
]),
};
let expected_ots_sig: [[U32<LittleEndian>; 6]; 51] = [
bytes_to_words_6([
0xd0, 0xf3, 0x73, 0xcf, 0x2b, 0x22, 0xe3, 0x6a, 0x23, 0x7d, 0x5c, 0x9d, 0xe8, 0x70,
0xed, 0x6b, 0x54, 0x6e, 0x6a, 0x43, 0x82, 0x1d, 0xa4, 0x73,
]),
bytes_to_words_6([
0xb5, 0x72, 0x8c, 0xd9, 0xc3, 0x49, 0x1c, 0xc1, 0xc1, 0x0e, 0x61, 0x1f, 0xef, 0xbb,
0xba, 0x1e, 0x77, 0xa1, 0x63, 0x25, 0x83, 0xc1, 0xdd, 0x6a,
]),
bytes_to_words_6([
0xc6, 0xa8, 0x28, 0xd1, 0x3b, 0x24, 0x3f, 0x96, 0xbe, 0xea, 0x03, 0x74, 0xe9, 0xa9,
0x46, 0xe5, 0x59, 0xaf, 0x37, 0xd2, 0x4b, 0xc7, 0x6e, 0xb2,
]),
bytes_to_words_6([
0x46, 0x84, 0x4f, 0xe6, 0x91, 0xc4, 0x8d, 0xd1, 0xb7, 0x22, 0xcc, 0xb1, 0x3b, 0xa2,
0x32, 0x17, 0xe0, 0x4f, 0xdb, 0x0d, 0x8c, 0x45, 0x8a, 0xe5,
]),
bytes_to_words_6([
0x71, 0x31, 0x75, 0x09, 0xa3, 0x7a, 0xba, 0x7a, 0xb3, 0x04, 0x59, 0x49, 0x91, 0x29,
0x80, 0xab, 0x07, 0xb0, 0x46, 0xaa, 0xc6, 0xbc, 0x5f, 0x65,
]),
bytes_to_words_6([
0x37, 0x83, 0xe3, 0x24, 0xd7, 0x41, 0x21, 0xb5, 0x92, 0xc7, 0x5d, 0xd0, 0x92, 0x78,
0x29, 0x5c, 0x66, 0xef, 0x07, 0x85, 0x12, 0xe2, 0x9d, 0x3f,
]),
bytes_to_words_6([
0x32, 0x33, 0x9e, 0xc5, 0x34, 0x88, 0xde, 0xba, 0x3e, 0x75, 0x68, 0x05, 0xec, 0xe5,
0x6e, 0x08, 0x0d, 0x56, 0x25, 0x57, 0x48, 0x69, 0x9e, 0xe1,
]),
bytes_to_words_6([
0xd8, 0xf7, 0x57, 0x76, 0x65, 0xf6, 0x16, 0x14, 0xd9, 0x5f, 0x1c, 0xdb, 0xab, 0x71,
0x2e, 0x62, 0xea, 0xdc, 0x47, 0x4e, 0xac, 0x5b, 0xd8, 0xe2,
]),
bytes_to_words_6([
0xc4, 0xc1, 0xb2, 0x6a, 0x00, 0x67, 0x5f, 0x21, 0x4c, 0xa4, 0xdf, 0x06, 0x83, 0x8b,
0x0d, 0x79, 0xca, 0x0f, 0xfb, 0x43, 0xa7, 0x5b, 0x0a, 0x6e,
]),
bytes_to_words_6([
0xe4, 0xae, 0xb8, 0xdb, 0x73, 0x9c, 0xac, 0x2f, 0xdd, 0xd5, 0x36, 0xee, 0xf1, 0x77,
0x57, 0x7e, 0xde, 0x86, 0x5e, 0x0d, 0xcd, 0xf3, 0xbb, 0x51,
]),
bytes_to_words_6([
0xa0, 0x1c, 0x04, 0x28, 0x84, 0xb0, 0x17, 0xb5, 0x37, 0xdc, 0xac, 0xdf, 0x44, 0x6b,
0xeb, 0xbc, 0x60, 0x30, 0xcb, 0xd3, 0x83, 0xc9, 0xf3, 0xa1,
]),
bytes_to_words_6([
0x31, 0xc6, 0x4a, 0x5b, 0xc0, 0x68, 0xf3, 0xf3, 0x2b, 0x81, 0x56, 0x85, 0x65, 0x2d,
0xcf, 0xb0, 0x18, 0x56, 0x8e, 0x92, 0x17, 0x03, 0xac, 0x5e,
]),
bytes_to_words_6([
0xf8, 0x86, 0x6e, 0x25, 0x28, 0xa1, 0x59, 0xdf, 0x3d, 0x6c, 0xe2, 0x44, 0xd2, 0xb6,
0x51, 0x8d, 0x1f, 0x02, 0x12, 0x28, 0x5a, 0x3c, 0x2d, 0x4a,
]),
bytes_to_words_6([
0x15, 0x35, 0x1d, 0x1e, 0x3e, 0x56, 0x9d, 0x25, 0x51, 0xab, 0x26, 0x02, 0xcb, 0xf9,
0xcb, 0x39, 0x42, 0x2b, 0xd9, 0xdb, 0x84, 0x3c, 0xae, 0x0a,
]),
bytes_to_words_6([
0xfc, 0x8c, 0x81, 0x07, 0x6e, 0xef, 0x85, 0xdc, 0xa2, 0xea, 0xf8, 0x06, 0xee, 0xf6,
0xb8, 0x10, 0xad, 0x0d, 0x29, 0xf6, 0xa7, 0x7d, 0x07, 0x15,
]),
bytes_to_words_6([
0x0d, 0xcb, 0xa2, 0x9a, 0x92, 0x8b, 0x7d, 0x6a, 0x6b, 0x27, 0x62, 0x65, 0x6d, 0x62,
0xfa, 0x99, 0x42, 0x95, 0xed, 0x73, 0xbb, 0x0d, 0x67, 0x23,
]),
bytes_to_words_6([
0x1e, 0x51, 0xce, 0x24, 0x80, 0xa2, 0x2b, 0xd1, 0x9c, 0xbf, 0x4d, 0x35, 0x31, 0xd3,
0xf2, 0xf7, 0x91, 0x33, 0xa6, 0x82, 0x0a, 0x7b, 0xd3, 0xc9,
]),
bytes_to_words_6([
0x6d, 0x48, 0x83, 0xd6, 0x1f, 0x1e, 0xef, 0xcc, 0xfc, 0x3a, 0xf6, 0xd0, 0xd9, 0xf1,
0x0e, 0x7c, 0xa6, 0x68, 0x05, 0x45, 0x7c, 0x24, 0xdb, 0x05,
]),
bytes_to_words_6([
0x49, 0x47, 0x18, 0x63, 0x1d, 0xa0, 0xe3, 0x88, 0x5a, 0x31, 0xb3, 0xd7, 0xfd, 0xa4,
0xa7, 0x56, 0x78, 0xda, 0xbc, 0x18, 0x12, 0xf1, 0xb6, 0x88,
]),
bytes_to_words_6([
0x94, 0x1f, 0x2c, 0x9c, 0x79, 0x7f, 0xd2, 0x5c, 0xb9, 0x79, 0xdc, 0x0c, 0x26, 0xd3,
0x3a, 0xfd, 0x02, 0xbe, 0x2d, 0x51, 0x98, 0x99, 0x0e, 0x21,
]),
bytes_to_words_6([
0x32, 0x3d, 0x49, 0xb7, 0xda, 0xb8, 0x5b, 0xf4, 0x13, 0xda, 0x18, 0x81, 0x09, 0xf7,
0x18, 0xd5, 0xc7, 0xb8, 0x6b, 0x98, 0x99, 0xe3, 0x13, 0x14,
]),
bytes_to_words_6([
0xcb, 0x62, 0xdb, 0xcc, 0x7e, 0xf8, 0xf9, 0xfe, 0xa3, 0xc7, 0xe0, 0x26, 0x00, 0x50,
0x33, 0xda, 0xc8, 0x44, 0xba, 0x68, 0xa7, 0x82, 0xbf, 0xeb,
]),
bytes_to_words_6([
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/image/crypto/src/openssl.rs | image/crypto/src/openssl.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains crypto utilities needed to generate images.
--*/
use std::path::Path;
use anyhow::{bail, Context};
use caliptra_image_gen::{
from_hw_format, to_hw_format, u8_to_u32_le, ImageGeneratorCrypto, ImageGeneratorHasher,
};
use caliptra_image_types::*;
use zerocopy::IntoBytes;
use openssl::{
bn::{BigNum, BigNumContext},
ec::{EcGroup, EcKey, EcPoint},
ecdsa::EcdsaSig,
nid::Nid,
pkey::Private,
pkey_ctx::PkeyCtx,
pkey_ml_dsa::{PKeyMlDsaBuilder, Variant},
rand::rand_bytes,
sha::{Sha256, Sha384, Sha512},
signature::Signature,
};
use crate::{sign_with_lms_key, Sha256Hasher, SUPPORTED_LMS_Q_VALUE};
#[derive(Default)]
pub struct OsslCrypto {}
pub struct OsslSha256Hasher(Sha256);
impl ImageGeneratorHasher for OsslSha256Hasher {
type Output = [u32; SHA256_DIGEST_WORD_SIZE];
fn update(&mut self, data: &[u8]) {
self.0.update(data)
}
fn finish(self) -> Self::Output {
to_hw_format(&self.0.finish())
}
}
impl ImageGeneratorCrypto for OsslCrypto {
type Sha256Hasher = OsslSha256Hasher;
fn sha256_start(&self) -> Self::Sha256Hasher {
OsslSha256Hasher(Sha256::default())
}
fn sha384_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest384> {
let mut engine = Sha384::new();
engine.update(data);
Ok(to_hw_format(&engine.finish()))
}
fn sha512_digest(&self, data: &[u8]) -> anyhow::Result<ImageDigest512> {
let mut engine = Sha512::new();
engine.update(data);
Ok(to_hw_format(&engine.finish()))
}
fn ecdsa384_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageEccPrivKey,
pub_key: &ImageEccPubKey,
) -> anyhow::Result<ImageEccSignature> {
let priv_key: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(priv_key);
let pub_key_x: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(&pub_key.x);
let pub_key_y: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(&pub_key.y);
let digest: [u8; SHA384_DIGEST_BYTE_SIZE] = from_hw_format(digest);
let group = EcGroup::from_curve_name(Nid::SECP384R1)?;
let mut ctx = BigNumContext::new()?;
let priv_key = BigNum::from_slice(&priv_key)?;
let pub_key_x = BigNum::from_slice(&pub_key_x)?;
let pub_key_y = BigNum::from_slice(&pub_key_y)?;
let mut pub_key = EcPoint::new(&group)?;
pub_key.set_affine_coordinates_gfp(&group, &pub_key_x, &pub_key_y, &mut ctx)?;
let ec_key = EcKey::from_private_components(&group, &priv_key, &pub_key)?;
let sig = EcdsaSig::sign(&digest, &ec_key)?;
let r = sig.r().to_vec_padded(ECC384_SCALAR_BYTE_SIZE as i32)?;
let s = sig.s().to_vec_padded(ECC384_SCALAR_BYTE_SIZE as i32)?;
let image_sig = ImageEccSignature {
r: to_hw_format(&r),
s: to_hw_format(&s),
};
Ok(image_sig)
}
fn lms_sign(
&self,
digest: &ImageDigest384,
priv_key: &ImageLmsPrivKey,
) -> anyhow::Result<ImageLmsSignature> {
let message: [u8; ECC384_SCALAR_BYTE_SIZE] = from_hw_format(digest);
let mut nonce = [0u8; SHA192_DIGEST_BYTE_SIZE];
rand_bytes(&mut nonce)?;
sign_with_lms_key::<OpensslHasher>(priv_key, &message, &nonce, SUPPORTED_LMS_Q_VALUE)
}
fn mldsa_sign(
&self,
msg: &[u8],
priv_key: &ImageMldsaPrivKey,
pub_key: &ImageMldsaPubKey,
) -> anyhow::Result<ImageMldsaSignature> {
// Private key is received in hw format which is also the OSSL library format.
// Unlike ECC, no reversal of the DWORD endianess needed.
let private_key = {
let pub_key = pub_key.0.as_bytes();
let priv_key = priv_key.0.as_bytes();
let builder =
PKeyMlDsaBuilder::<Private>::new(Variant::MlDsa87, pub_key, Some(priv_key))?;
builder.build()?
};
let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?;
let mut ctx = PkeyCtx::new(&private_key)?;
ctx.sign_message_init(&mut algo)?;
const SIG_LEN: usize = 4627;
let mut signature = [0u8; SIG_LEN + 1];
ctx.sign(msg, Some(&mut signature))?;
ctx.verify_message_init(&mut algo)?;
match ctx.verify(msg, &signature[..SIG_LEN]) {
Ok(true) => (),
_ => bail!("MLDSA signature verification failed"),
}
// Return the signature in hw format (which is also the library format)
// Unlike ECC, no reversal of the DWORD endianess needed.
let mut sig = ImageMldsaSignature::default();
for (i, chunk) in signature.chunks(4).enumerate() {
sig.0[i] = u32::from_le_bytes(chunk.try_into().unwrap());
}
Ok(sig)
}
fn ecc_pub_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPubKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read public key PEM file {}", path.display()))?;
let key = EcKey::public_key_from_pem(&key_bytes)?;
let group = EcGroup::from_curve_name(Nid::SECP384R1)?;
let mut ctx = BigNumContext::new()?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
key.public_key()
.affine_coordinates_gfp(&group, &mut x, &mut y, &mut ctx)?;
let x = x.to_vec_padded(ECC384_SCALAR_BYTE_SIZE as i32)?;
let y = y.to_vec_padded(ECC384_SCALAR_BYTE_SIZE as i32)?;
let image_key = ImageEccPubKey {
x: to_hw_format(&x),
y: to_hw_format(&y),
};
Ok(image_key)
}
fn ecc_priv_key_from_pem(path: &Path) -> anyhow::Result<ImageEccPrivKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read private key PEM file {}", path.display()))?;
let key = EcKey::private_key_from_pem(&key_bytes)?;
let priv_key = key
.private_key()
.to_vec_padded(ECC384_SCALAR_BYTE_SIZE as i32)?;
Ok(to_hw_format(&priv_key))
}
/// Read MLDSA Public Key from file. Library format is same as hardware format.
fn mldsa_pub_key_from_file(path: &Path) -> anyhow::Result<ImageMldsaPubKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read public key file {}", path.display()))?;
Ok(ImageMldsaPubKey(
u8_to_u32_le(&key_bytes).try_into().unwrap(),
))
}
/// Read MLDSA Private Key from file. Library format is same as hardware format.
fn mldsa_priv_key_from_file(path: &Path) -> anyhow::Result<ImageMldsaPrivKey> {
let key_bytes = std::fs::read(path)
.with_context(|| format!("Failed to read private key file {}", path.display()))?;
Ok(ImageMldsaPrivKey(
u8_to_u32_le(&key_bytes).try_into().unwrap(),
))
}
}
pub struct OpensslHasher(Sha256);
impl Sha256Hasher for OpensslHasher {
fn new() -> Self {
Self(Sha256::new())
}
fn update(&mut self, bytes: &[u8]) {
self.0.update(bytes)
}
fn finish(self) -> [u8; 32] {
self.0.finish()
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/lms-types/src/lib.rs | lms-types/src/lib.rs | // Licensed under the Apache-2.0 license
// TODO not(fuzzing), attribute not found
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
#[cfg(not(feature = "no-cfi"))]
use caliptra_cfi_derive::Launder;
use core::mem::size_of;
#[cfg(feature = "std")]
use core::mem::size_of_val;
#[cfg(feature = "std")]
use serde::de::{self, Deserialize, Deserializer, Expected, MapAccess, Visitor};
use zerocopy::{
BigEndian, FromBytes, Immutable, IntoBytes, KnownLayout, LittleEndian, Unaligned, U32,
};
use zeroize::Zeroize;
pub type LmsIdentifier = [u8; 16];
macro_rules! static_assert {
($expression:expr) => {
const _: () = assert!($expression);
};
}
#[repr(transparent)]
#[derive(
IntoBytes,
FromBytes,
Copy,
Clone,
Debug,
KnownLayout,
Immutable,
Unaligned,
Default,
PartialEq,
Eq,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct LmsAlgorithmType(pub U32<BigEndian>);
impl LmsAlgorithmType {
#![allow(non_upper_case_globals)]
pub const fn new(val: u32) -> Self {
Self(U32::from_bytes(val.to_be_bytes()))
}
pub const LmsReserved: Self = Self::new(0);
pub const LmsSha256N32H5: Self = Self::new(5);
pub const LmsSha256N32H10: Self = Self::new(6);
pub const LmsSha256N32H15: Self = Self::new(7);
pub const LmsSha256N32H20: Self = Self::new(8);
pub const LmsSha256N32H25: Self = Self::new(9);
pub const LmsSha256N24H5: Self = Self::new(10);
pub const LmsSha256N24H10: Self = Self::new(11);
pub const LmsSha256N24H15: Self = Self::new(12);
pub const LmsSha256N24H20: Self = Self::new(13);
pub const LmsSha256N24H25: Self = Self::new(14);
}
// Manually implement serde::Deserialize. This has to be done manually because
// the zerocopy type `U32` does not support it and implementations of a trait
// have to be done in the crate the object is defined in. This is true for all
// of the other manual implementations in this file as well.
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for LmsAlgorithmType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(LmsAlgorithmType::new(u32::deserialize(deserializer)?))
}
}
#[repr(transparent)]
#[derive(
IntoBytes,
FromBytes,
Debug,
Immutable,
KnownLayout,
Unaligned,
Default,
PartialEq,
Eq,
Clone,
Copy,
)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct LmotsAlgorithmType(pub U32<BigEndian>);
impl LmotsAlgorithmType {
#![allow(non_upper_case_globals)]
pub const fn new(val: u32) -> Self {
Self(U32::from_bytes(val.to_be_bytes()))
}
pub const LmotsReserved: Self = Self::new(0);
pub const LmotsSha256N32W1: Self = Self::new(1);
pub const LmotsSha256N32W2: Self = Self::new(2);
pub const LmotsSha256N32W4: Self = Self::new(3);
pub const LmotsSha256N32W8: Self = Self::new(4);
pub const LmotsSha256N24W1: Self = Self::new(5);
pub const LmotsSha256N24W2: Self = Self::new(6);
pub const LmotsSha256N24W4: Self = Self::new(7);
pub const LmotsSha256N24W8: Self = Self::new(8);
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for LmotsAlgorithmType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(LmotsAlgorithmType::new(u32::deserialize(deserializer)?))
}
}
#[derive(Copy, Clone, Debug, IntoBytes, FromBytes, Immutable, KnownLayout, PartialEq, Eq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
#[repr(C)]
pub struct LmsPublicKey<const N: usize> {
pub tree_type: LmsAlgorithmType,
pub otstype: LmotsAlgorithmType,
pub id: [u8; 16],
pub digest: [U32<LittleEndian>; N],
}
impl<const N: usize> Default for LmsPublicKey<N> {
fn default() -> Self {
Self {
tree_type: Default::default(),
otstype: Default::default(),
id: Default::default(),
digest: [Default::default(); N],
}
}
}
// Ensure there is no padding (required for IntoBytes safety)
static_assert!(
size_of::<LmsPublicKey<1>>()
== (size_of::<LmsAlgorithmType>()
+ size_of::<LmotsAlgorithmType>()
+ size_of::<[u8; 16]>()
+ size_of::<[U32<LittleEndian>; 1]>())
);
#[cfg(feature = "std")]
struct ExpectedDigestOrSeed<const N: usize>;
#[cfg(feature = "std")]
impl<const N: usize> Expected for ExpectedDigestOrSeed<N> {
fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(
formatter,
"Expected an array of {} bytes",
size_of::<[U32<LittleEndian>; N]>()
)
}
}
#[cfg(feature = "std")]
impl<'de, const N: usize> Deserialize<'de> for LmsPublicKey<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(serde_derive::Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum Field {
TreeType,
Otstype,
Id,
Digest,
}
struct FieldVisitor<const N: usize>;
impl<'de, const N: usize> Visitor<'de> for FieldVisitor<N> {
type Value = LmsPublicKey<N>;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(format!("struct LmsPublicKey<{}>", N).as_str())
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut tree_type = None;
let mut otstype = None;
let mut id = None;
let mut digest = None;
while let Some(key) = map.next_key()? {
match key {
Field::TreeType => {
if tree_type.is_some() {
return Err(de::Error::duplicate_field("tree_type"));
}
tree_type = Some(map.next_value()?);
}
Field::Otstype => {
if otstype.is_some() {
return Err(de::Error::duplicate_field("otstype"));
}
otstype = Some(map.next_value()?);
}
Field::Id => {
if id.is_some() {
return Err(de::Error::duplicate_field("id"));
}
id = Some(map.next_value()?);
}
Field::Digest => {
if digest.is_some() {
return Err(de::Error::duplicate_field("digest"));
}
let mut d = [Default::default(); N];
let digest_bytes: Vec<u8> = map.next_value()?;
if digest_bytes.len() != size_of_val(&d) {
return Err(de::Error::invalid_length(
digest_bytes.len(),
&ExpectedDigestOrSeed::<N>,
));
}
d.as_mut_bytes().copy_from_slice(&digest_bytes);
digest = Some(d);
}
}
}
let tree_type = tree_type.ok_or_else(|| de::Error::missing_field("tree_type"))?;
let otstype = otstype.ok_or_else(|| de::Error::missing_field("otstype"))?;
let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
let digest = digest.ok_or_else(|| de::Error::missing_field("digest"))?;
Ok(LmsPublicKey {
tree_type,
otstype,
id,
digest,
})
}
}
const FIELDS: &[&str] = &["tree_type", "otstype", "id", "digest"];
deserializer.deserialize_struct("LmsPublicKey", FIELDS, FieldVisitor)
}
}
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(
Copy,
Clone,
Debug,
IntoBytes,
Immutable,
KnownLayout,
Unaligned,
FromBytes,
PartialEq,
Eq,
Zeroize,
)]
#[repr(C)]
pub struct LmotsSignature<const N: usize, const P: usize> {
#[zeroize(skip)]
pub ots_type: LmotsAlgorithmType,
#[zeroize(skip)]
pub nonce: [U32<LittleEndian>; N],
#[zeroize(skip)]
pub y: [[U32<LittleEndian>; N]; P],
}
impl<const N: usize, const P: usize> Default for LmotsSignature<N, P> {
fn default() -> Self {
Self {
ots_type: Default::default(),
nonce: [Default::default(); N],
y: [[Default::default(); N]; P],
}
}
}
// Ensure there is no padding (required for IntoBytes safety)
static_assert!(
size_of::<LmotsSignature<1, 1>>()
== (size_of::<LmotsAlgorithmType>()
+ size_of::<[U32<LittleEndian>; 1]>()
+ size_of::<[[U32<LittleEndian>; 1]; 1]>())
);
#[derive(Copy, Clone, Debug, IntoBytes, Immutable, KnownLayout, FromBytes, PartialEq, Eq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(not(feature = "no-cfi"), derive(Launder))]
#[repr(C)]
pub struct LmsSignature<const N: usize, const P: usize, const H: usize> {
pub q: U32<BigEndian>,
pub ots: LmotsSignature<N, P>,
pub tree_type: LmsAlgorithmType,
pub tree_path: [[U32<LittleEndian>; N]; H],
}
impl<const N: usize, const P: usize, const H: usize> Default for LmsSignature<N, P, H> {
fn default() -> Self {
Self {
q: Default::default(),
ots: Default::default(),
tree_type: Default::default(),
tree_path: [[Default::default(); N]; H],
}
}
}
// Ensure there is no padding (required for IntoBytes safety)
static_assert!(
size_of::<LmsSignature<1, 1, 1>>()
== (size_of::<U32<BigEndian>>()
+ size_of::<LmotsSignature<1, 1>>()
+ size_of::<LmsAlgorithmType>()
+ size_of::<[[U32<LittleEndian>; 1]; 1]>())
);
// Derive doesn't support const generic arrays
// // unsafe impl<const N: usize, const P: usize, const H: usize> IntoBytes for LmsSignature<N, P, H> {
// // fn only_derive_is_allowed_to_implement_this_trait() {}
// // }
// // unsafe impl<const N: usize, const P: usize, const H: usize> FromBytes for LmsSignature<N, P, H> {
// // fn only_derive_is_allowed_to_implement_this_trait() {}
// // }
// impl<const N: usize, const P: usize, const H: usize> LmsSignature<N, P, H> {
// pub fn ref_from_prefix(bytes: &[u8]) -> Option<&Self> {
// if bytes.len() >= size_of::<Self>() {
// Some(unsafe { &*(bytes.as_ptr() as *const Self) })
// } else {
// None
// }
// }
// }
// impl<const N: usize, const P: usize, const H: usize> LmsSignature<N, P, H> {
// pub fn mut_ref_from_prefix(bytes: &mut [u8]) -> Option<&mut Self> {
// {
// if bytes.len() >= size_of::<Self>() {
// Some(unsafe { &mut *(bytes.as_mut_ptr() as *mut Self) })
// } else {
// None
// }
// }
// }
// }
#[derive(Debug, Copy, Clone, IntoBytes, Immutable, KnownLayout, FromBytes, Eq, PartialEq)]
#[repr(C)]
pub struct LmsPrivateKey<const N: usize> {
pub tree_type: LmsAlgorithmType,
pub otstype: LmotsAlgorithmType,
pub id: LmsIdentifier,
pub seed: [U32<LittleEndian>; N],
}
impl<const N: usize> Default for LmsPrivateKey<N> {
fn default() -> Self {
Self {
tree_type: Default::default(),
otstype: Default::default(),
id: Default::default(),
seed: [Default::default(); N],
}
}
}
static_assert!(
size_of::<LmsPrivateKey<1>>()
== (size_of::<LmsAlgorithmType>()
+ size_of::<LmotsAlgorithmType>()
+ size_of::<LmsIdentifier>()
+ size_of::<[U32<LittleEndian>; 1]>())
);
#[cfg(feature = "std")]
impl<'de, const N: usize> Deserialize<'de> for LmsPrivateKey<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(serde_derive::Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum Field {
TreeType,
Otstype,
Id,
Seed,
}
struct FieldVisitor<const N: usize>;
impl<'de, const N: usize> Visitor<'de> for FieldVisitor<N> {
type Value = LmsPrivateKey<N>;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str(format!("struct LmsPrivateKey<{}>", N).as_str())
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut tree_type = None;
let mut otstype = None;
let mut id = None;
let mut seed = None;
while let Some(key) = map.next_key()? {
match key {
Field::TreeType => {
if tree_type.is_some() {
return Err(de::Error::duplicate_field("tree_type"));
}
tree_type = Some(map.next_value()?);
}
Field::Otstype => {
if otstype.is_some() {
return Err(de::Error::duplicate_field("otstype"));
}
otstype = Some(map.next_value()?);
}
Field::Id => {
if id.is_some() {
return Err(de::Error::duplicate_field("id"));
}
id = Some(map.next_value()?);
}
Field::Seed => {
if seed.is_some() {
return Err(de::Error::duplicate_field("seed"));
}
let mut s = [Default::default(); N];
let seed_bytes: Vec<u8> = map.next_value()?;
if seed_bytes.len() != size_of_val(&s) {
return Err(de::Error::invalid_length(
seed_bytes.len(),
&ExpectedDigestOrSeed::<N>,
));
}
s.as_mut_bytes().copy_from_slice(&seed_bytes);
seed = Some(s);
}
}
}
let tree_type = tree_type.ok_or_else(|| de::Error::missing_field("tree_type"))?;
let otstype = otstype.ok_or_else(|| de::Error::missing_field("otstype"))?;
let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
let seed = seed.ok_or_else(|| de::Error::missing_field("seed"))?;
Ok(LmsPrivateKey {
tree_type,
otstype,
id,
seed,
})
}
}
const FIELDS: &[&str] = &["tree_type", "otstype", "id", "seed"];
deserializer.deserialize_struct("LmsPrivateKey", FIELDS, FieldVisitor)
}
}
/// Converts a byte array to word arrays as used in the LMS types. Intended for
/// use at compile-time or in tests / host utilities; not optimized for use in
/// firmware at runtime.
pub const fn bytes_to_words_6(bytes: [u8; 24]) -> [U32<LittleEndian>; 6] {
let mut result = [U32::ZERO; 6];
let mut i = 0;
while i < result.len() {
result[i] = U32::from_bytes([
bytes[i * 4],
bytes[i * 4 + 1],
bytes[i * 4 + 2],
bytes[i * 4 + 3],
]);
i += 1;
}
result
}
/// Converts a byte array to word arrays as used in the LMS types. Intended for
/// use at compile-time or in tests / host utilities; not optimized for use in
/// firmware at runtime.
pub const fn bytes_to_words_8(bytes: [u8; 32]) -> [U32<LittleEndian>; 8] {
let mut result = [U32::ZERO; 8];
let mut i = 0;
while i < result.len() {
result[i] = U32::from_bytes([
bytes[i * 4],
bytes[i * 4 + 1],
bytes[i * 4 + 2],
bytes[i * 4 + 3],
]);
i += 1;
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use zerocopy::{LittleEndian, U32};
#[test]
fn test_bytes_to_words_6() {
assert_eq!(
bytes_to_words_6([
0x7e, 0x40, 0xc3, 0xed, 0x23, 0x13, 0x9f, 0x1b, 0xa0, 0xad, 0x31, 0x02, 0x4d, 0x15,
0xe0, 0x39, 0xe8, 0x71, 0xd4, 0x79, 0xfc, 0x53, 0xca, 0xf0
]),
[
<U32<LittleEndian>>::from(0xedc3407e),
0x1b9f1323.into(),
0x0231ada0.into(),
0x39e0154d.into(),
0x79d471e8.into(),
0xf0ca53fc.into()
]
)
}
#[test]
fn test_bytes_to_words_8() {
assert_eq!(
bytes_to_words_8([
0x7e, 0x40, 0xc3, 0xed, 0x23, 0x13, 0x9f, 0x1b, 0xa0, 0xad, 0x31, 0x02, 0x4d, 0x15,
0xe0, 0x39, 0xe8, 0x71, 0xd4, 0x79, 0xfc, 0x53, 0xca, 0xf0, 0x9a, 0x3c, 0x4b, 0xb8,
0x1b, 0xde, 0x77, 0x9f
]),
[
<U32<LittleEndian>>::from(0xedc3407e),
0x1b9f1323.into(),
0x0231ada0.into(),
0x39e0154d.into(),
0x79d471e8.into(),
0xf0ca53fc.into(),
0xb84b3c9a.into(),
0x9f77de1b.into()
]
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/app/src/main.rs | sw-emulator/app/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
File contains main entrypoint for Caliptra Emulator.
--*/
use caliptra_api_types::{DeviceLifecycle, SecurityState};
use caliptra_emu_bus::{Clock, Device, Event, EventData};
use caliptra_emu_cpu::{Cpu, CpuArgs, Pic, RvInstr, StepAction};
use caliptra_emu_periph::dma::recovery::RecoveryControl;
use caliptra_emu_periph::soc_reg::DebugManufService;
use caliptra_emu_periph::{
CaliptraRootBus, CaliptraRootBusArgs, DownloadIdevidCsrCb, MailboxInternal, MailboxRequester,
ReadyForFwCb, TbServicesCb, UploadUpdateFwCb,
};
use caliptra_hw_model::BusMmio;
use caliptra_registers::i3ccsr::regs::DeviceStatus0ReadVal;
use clap::{arg, value_parser, ArgAction};
use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::exit;
use std::rc::Rc;
use std::sync::mpsc;
use tock_registers::interfaces::{ReadWriteable, Readable, Writeable};
use tock_registers::registers::InMemoryRegister;
mod gdb;
use crate::gdb::gdb_target::GdbTarget;
use gdb::gdb_state;
use tock_registers::register_bitfields;
/// Firmware Load Command Opcode
const FW_LOAD_CMD_OPCODE: u32 = 0x4657_4C44;
/// Recovery register interface download Command Opcode
const RI_DOWNLOAD_FIRMWARE: u32 = 0x5249_4644;
/// The number of CPU clock cycles it takes to write the firmware to the mailbox.
const FW_WRITE_TICKS: u64 = 1000;
const EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES: u64 = 20_000_000; // 20 million cycles
// CPU Main Loop (free_run no GDB)
fn free_run(
mut cpu: Cpu<CaliptraRootBus>,
trace_path: Option<PathBuf>,
events_to_caliptra: mpsc::Sender<Event>,
events_from_caliptra: mpsc::Receiver<Event>,
) {
let mut collected_events_from_caliptra = Vec::new();
if let Some(path) = trace_path {
let mut f = File::create(path).unwrap();
let trace_fn: &mut dyn FnMut(u32, RvInstr) = &mut |pc, instr| {
let _ = write!(&mut f, "0x{:08x} ", pc);
match instr {
RvInstr::Instr32(instr) => {
let _ = writeln!(&mut f, "0x{:08x}", instr);
}
RvInstr::Instr16(instr) => {
let _ = writeln!(&mut f, "0x{:04x}", instr);
}
}
};
// Need to have the loop in the same scope as trace_fn to prevent borrowing rules violation
while let StepAction::Continue = cpu.step(Some(trace_fn)) {
// Handle recovery flow like model_emulated
step_recovery_flow(&mut cpu);
// Handle events like model_emulated
handle_events(
&mut cpu,
&events_from_caliptra,
&events_to_caliptra,
&mut collected_events_from_caliptra,
);
}
} else {
while let StepAction::Continue = cpu.step(None) {
// Handle recovery flow like model_emulated
step_recovery_flow(&mut cpu);
// Handle events like model_emulated
handle_events(
&mut cpu,
&events_from_caliptra,
&events_to_caliptra,
&mut collected_events_from_caliptra,
);
}
};
}
fn step_recovery_flow(cpu: &mut Cpu<CaliptraRootBus>) {
// do the bare minimum for the recovery flow: activating the recovery image
const DEVICE_STATUS_PENDING: u32 = 0x4;
const ACTIVATE_RECOVERY_IMAGE_CMD: u32 = 0xF;
if DeviceStatus0ReadVal::from(cpu.bus.dma.axi.recovery.device_status_0.reg.get()).dev_status()
== DEVICE_STATUS_PENDING
{
cpu.bus
.dma
.axi
.recovery
.recovery_ctrl
.reg
.modify(RecoveryControl::ACTIVATE_RECOVERY_IMAGE.val(ACTIVATE_RECOVERY_IMAGE_CMD));
}
}
fn handle_events(
cpu: &mut Cpu<CaliptraRootBus>,
events_from_caliptra: &mpsc::Receiver<Event>,
events_to_caliptra: &mpsc::Sender<Event>,
collected_events_from_caliptra: &mut Vec<Event>,
) {
for event in events_from_caliptra.try_iter() {
collected_events_from_caliptra.push(event.clone());
// brute force respond to AXI DMA MCU SRAM read
if let (Device::MCU, EventData::MemoryRead { start_addr, len }) = (event.dest, event.event)
{
let addr = start_addr as usize;
let mcu_sram_data = cpu.bus.dma.axi.mcu_sram.data_mut();
let Some(dest) = mcu_sram_data.get_mut(addr..addr + len as usize) else {
continue;
};
events_to_caliptra
.send(Event {
src: Device::MCU,
dest: Device::CaliptraCore,
event: EventData::MemoryReadResponse {
start_addr,
data: dest.to_vec(),
},
})
.unwrap();
}
}
}
fn words_from_bytes_le(arr: &[u8; 48]) -> [u32; 12] {
let mut result = [0u32; 12];
for i in 0..result.len() {
result[i] = u32::from_le_bytes(arr[i * 4..][..4].try_into().unwrap())
}
result
}
fn main() -> io::Result<()> {
let args = clap::Command::new("caliptra-emu")
.about("Caliptra emulator")
.arg(
arg!(--"rom" <FILE> "ROM binary path")
.value_parser(value_parser!(PathBuf))
)
.arg(
arg!(--"recovery-image-fw" <FILE> "Recovery firmware image binary path")
.required(false)
.value_parser(value_parser!(PathBuf))
)
.arg(
arg!(--"update-recovery-image-fw" <FILE> "Update recovery firmware image binary path")
.required(false)
.value_parser(value_parser!(PathBuf))
)
.arg(
arg!(--"recovery-image-manifest" <FILE> "Recovery image auth manifest binary path")
.required(false)
.value_parser(value_parser!(PathBuf))
)
.arg(
arg!(--"recovery-image-mcurt" <FILE> "Recovery image mcurt binary path")
.required(false)
.value_parser(value_parser!(PathBuf))
)
.arg(
arg!(--"gdb-port" <VALUE> "Gdb Debugger")
.required(false)
)
.arg(
arg!(--"trace-instr" ... "Trace instructions to a file in log-dir")
.required(false)
.action(ArgAction::SetTrue)
)
.arg(
arg!(--"ueid" <U128> "128-bit Unique Endpoint Id")
.required(false)
.value_parser(value_parser!(u128))
.default_value(&u128::MAX.to_string())
)
.arg(
arg!(--"idevid-key-id-algo" <algo> "idevid certificate key id algorithm [sha1, sha256, sha384, fuse]")
.required(false)
.default_value("sha1"),
)
.arg(
arg!(--"req-idevid-csr" ... "Request IDevID CSR. Downloaded CSR is store in log-dir.")
.required(false)
.action(ArgAction::SetTrue)
)
.arg(
arg!(--"req-ldevid-cert" ... "Request LDevID Cert. Downloaded cert is stored in log-dir")
.required(false)
.action(ArgAction::SetTrue)
)
.arg(
arg!(--"log-dir" <DIR> "Directory to log execution artifacts")
.required(false)
.value_parser(value_parser!(PathBuf))
.default_value("/tmp")
)
.arg(
arg!(--"mfg-pk-hash" ... "Hash of the four Manufacturer Public Keys")
.required(false)
.value_parser(value_parser!(String))
.default_value(""),
)
.arg(
arg!(--"owner-pk-hash" ... "Owner Public Key Hash")
.required(false)
.value_parser(value_parser!(String))
.default_value(""),
)
.arg(
arg!(--"device-lifecycle" ... "Device Lifecycle State [unprovisioned, manufacturing, production]")
.required(false)
.value_parser(value_parser!(String))
.default_value("unprovisioned"),
)
.arg(
arg!(--"wdt-timeout" <U64> "Watchdog Timer Timeout in CPU Clock Cycles")
.required(false)
.value_parser(value_parser!(u64))
.default_value(&(EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES.to_string()))
)
.arg(
arg!(--"subsystem-mode" ... "Subsystem mode: get image update via recovery register interface")
.required(false)
.action(ArgAction::SetTrue)
)
.arg(
arg!(--"pqc-key-type" <U32> "Type of PQC key validation: 1: MLDSA; 3: LMS")
.required(true)
.value_parser(value_parser!(u32)),
)
.get_matches();
let args_rom = args.get_one::<PathBuf>("rom").unwrap();
let args_recovery_fw = args.get_one::<PathBuf>("recovery-image-fw");
let args_update_recovery_fw = args.get_one::<PathBuf>("update-recovery-image-fw");
let _args_recovery_image_manifest = args.get_one::<PathBuf>("recovery-image-manifest"); // TODO hook up to RRI
let _args_recovery_image_mcurt = args.get_one::<PathBuf>("recovery-image-mcurt"); // TODO hook up to RRI
let args_log_dir = args.get_one::<PathBuf>("log-dir").unwrap();
let args_idevid_key_id_algo = args.get_one::<String>("idevid-key-id-algo").unwrap();
let args_ueid = args.get_one::<u128>("ueid").unwrap();
let wdt_timeout = args.get_one::<u64>("wdt-timeout").unwrap();
let mut mfg_pk_hash = match hex::decode(args.get_one::<String>("mfg-pk-hash").unwrap()) {
Ok(mfg_pk_hash) => mfg_pk_hash,
Err(_) => {
println!("Manufacturer public keys hash format is incorrect",);
exit(-1);
}
};
let mut owner_pk_hash = match hex::decode(args.get_one::<String>("owner-pk-hash").unwrap()) {
Ok(owner_pk_hash) => owner_pk_hash,
Err(_) => {
println!("Owner public key hash format is incorrect",);
exit(-1);
}
};
let args_device_lifecycle = args.get_one::<String>("device-lifecycle").unwrap();
let pqc_key_type = args.get_one::<u32>("pqc-key-type").unwrap();
if !Path::new(&args_rom).exists() {
println!("ROM File {:?} does not exist", args_rom);
exit(-1);
}
if (!mfg_pk_hash.is_empty() && mfg_pk_hash.len() != 48)
|| (!owner_pk_hash.is_empty() && owner_pk_hash.len() != 48)
{
println!(
"Incorrect mfg_pk_hash: {} and/or owner_pk_hash: {} length",
mfg_pk_hash.len(),
owner_pk_hash.len()
);
exit(-1);
}
change_dword_endianess(&mut mfg_pk_hash);
change_dword_endianess(&mut owner_pk_hash);
let mut rom = File::open(args_rom)?;
let mut rom_buffer = Vec::new();
rom.read_to_end(&mut rom_buffer)?;
if rom_buffer.len() > CaliptraRootBus::ROM_SIZE {
println!(
"ROM File Size must not exceed {} bytes",
CaliptraRootBus::ROM_SIZE
);
exit(-1);
}
let mut current_fw_buf = Vec::new();
if let Some(path) = args_recovery_fw {
if !Path::new(&path).exists() {
println!(
"Current firmware file {:?} does not exist",
args_recovery_fw
);
exit(-1);
}
let mut firmware = File::open(path)?;
firmware.read_to_end(&mut current_fw_buf)?;
}
let current_fw_buf = Rc::new(current_fw_buf);
let mut update_fw_buf = Vec::new();
if let Some(path) = args_update_recovery_fw {
if !Path::new(&path).exists() {
println!(
"Update firmware file {:?} does not exist",
args_update_recovery_fw
);
exit(-1);
}
let mut firmware = File::open(path)?;
firmware.read_to_end(&mut update_fw_buf)?;
}
let update_fw_buf = Rc::new(update_fw_buf);
let log_dir = Rc::new(args_log_dir.to_path_buf());
let clock = Rc::new(Clock::new());
let req_idevid_csr = args.get_flag("req-idevid-csr");
let req_ldevid_cert = args.get_flag("req-ldevid-cert");
let mut security_state = SecurityState::default();
security_state.set_device_lifecycle(
match args_device_lifecycle.to_ascii_lowercase().as_str() {
"manufacturing" => DeviceLifecycle::Manufacturing,
"production" => DeviceLifecycle::Production,
"unprovisioned" | "" => DeviceLifecycle::Unprovisioned,
other => {
println!("Unknown device lifecycle {:?}", other);
exit(-1);
}
},
);
let subsystem_mode = args.get_flag("subsystem-mode");
// Clippy seems wrong about this clone not being necessary
#[allow(clippy::redundant_clone)]
let firmware_buffer = current_fw_buf.clone();
let bus_args = CaliptraRootBusArgs {
rom: rom_buffer,
log_dir: args_log_dir.clone(),
tb_services_cb: TbServicesCb::new(move |val| match val {
0x01 => exit(0xFF),
0xFF => exit(0x00),
_ => print!("{}", val as char),
}),
ready_for_fw_cb: if subsystem_mode {
ReadyForFwCb::new(move |args| {
args.schedule_later(FW_WRITE_TICKS, move |mailbox: &mut MailboxInternal| {
issue_ri_download_fw_mbox_cmd(mailbox)
})
})
} else {
ReadyForFwCb::new(move |args| {
let firmware_buffer = firmware_buffer.clone();
args.schedule_later(FW_WRITE_TICKS, move |mailbox: &mut MailboxInternal| {
upload_fw_to_mailbox(mailbox, firmware_buffer)
});
})
},
security_state,
upload_update_fw: UploadUpdateFwCb::new(move |mailbox: &mut MailboxInternal| {
upload_fw_to_mailbox(mailbox, update_fw_buf.clone());
}),
download_idevid_csr_cb: DownloadIdevidCsrCb::new(
move |mailbox: &mut MailboxInternal,
cptra_dbg_manuf_service_reg: &mut InMemoryRegister<
u32,
DebugManufService::Register,
>| {
download_idev_id_csr(mailbox, log_dir.clone(), cptra_dbg_manuf_service_reg);
},
),
subsystem_mode,
clock: clock.clone(),
..Default::default()
};
let mut root_bus = CaliptraRootBus::new(bus_args);
// Populate the RRI data
if subsystem_mode {
root_bus.dma.axi.recovery.cms_data = vec![current_fw_buf.as_ref().clone()];
}
let soc_ifc = unsafe {
caliptra_registers::soc_ifc::RegisterBlock::new_with_mmio(
0x3003_0000 as *mut u32,
BusMmio::new(root_bus.soc_to_caliptra_bus(MailboxRequester::SocUser(1u32))),
)
};
if !mfg_pk_hash.is_empty() {
let mfg_pk_hash = words_from_bytes_le(
&mfg_pk_hash
.try_into()
.expect("mfg_pk_hash must be 48 bytes"),
);
soc_ifc.fuse_vendor_pk_hash().write(&mfg_pk_hash);
}
if !owner_pk_hash.is_empty() {
let owner_pk_hash = words_from_bytes_le(
&owner_pk_hash
.try_into()
.expect("owner_pk_hash must be 48 bytes"),
);
soc_ifc.cptra_owner_pk_hash().write(&owner_pk_hash);
}
// Populate DBG_MANUF_SERVICE_REG
{
const GEN_IDEVID_CSR_FLAG: u32 = 1 << 0;
const GEN_LDEVID_CSR_FLAG: u32 = 1 << 1;
let mut val = 0;
if req_idevid_csr {
val |= GEN_IDEVID_CSR_FLAG;
}
if req_ldevid_cert {
val |= GEN_LDEVID_CSR_FLAG;
}
soc_ifc.cptra_dbg_manuf_service_reg().write(|_| val);
}
// Populate fuse_idevid_cert_attr
{
register_bitfields! [
u32,
IDevIdCertAttrFlags [
KEY_ID_ALGO OFFSET(0) NUMBITS(2) [
SHA1 = 0b00,
SHA256 = 0b01,
SHA384 = 0b10,
FUSE = 0b11,
],
RESERVED OFFSET(2) NUMBITS(30) [],
],
];
// Determine the Algorithm used for IDEVID Certificate Subject Key Identifier
let algo = match args_idevid_key_id_algo.to_ascii_lowercase().as_str() {
"" | "sha1" => IDevIdCertAttrFlags::KEY_ID_ALGO::SHA1,
"sha256" => IDevIdCertAttrFlags::KEY_ID_ALGO::SHA256,
"sha384" => IDevIdCertAttrFlags::KEY_ID_ALGO::SHA384,
"fuse" => IDevIdCertAttrFlags::KEY_ID_ALGO::FUSE,
_ => panic!("Unknown idev_key_id_algo {:?}", args_idevid_key_id_algo),
};
let flags: InMemoryRegister<u32, IDevIdCertAttrFlags::Register> = InMemoryRegister::new(0);
flags.write(algo);
let mut cert = [0u32; 24];
// DWORD 00 - Flags
cert[0] = flags.get();
// DWORD 01 - 05 - IDEVID Subject Key Identifier (all zeroes)
cert[6] = 1; // UEID Type
// DWORD 07 - 10 - UEID / Manufacturer Serial Number
cert[7] = *args_ueid as u32;
cert[8] = (*args_ueid >> 32) as u32;
cert[9] = (*args_ueid >> 64) as u32;
cert[10] = (*args_ueid >> 96) as u32;
soc_ifc.fuse_idevid_cert_attr().write(&cert);
}
// Populate cptra_wdt_cfg
{
soc_ifc.cptra_wdt_cfg().at(0).write(|_| *wdt_timeout as u32);
soc_ifc
.cptra_wdt_cfg()
.at(1)
.write(|_| (*wdt_timeout >> 32) as u32);
}
// Populate the pqc_key_type fuse.
soc_ifc
.fuse_pqc_key_type()
.write(|w| w.key_type(*pqc_key_type));
let pic = Rc::new(Pic::new());
let cpu_args = CpuArgs::default();
let mut cpu = Cpu::new(root_bus, clock.clone(), pic, cpu_args);
let (events_to_caliptra, events_from_caliptra) = cpu.register_events();
// Check if Optional GDB Port is passed
match args.get_one::<String>("gdb-port") {
Some(port) => {
// Create GDB Target Instance
let mut gdb_target = GdbTarget::new(cpu);
// Execute CPU through GDB State Machine
gdb_state::wait_for_gdb_run(&mut gdb_target, port.parse().unwrap());
}
_ => {
let instr_trace = if args.get_flag("trace-instr") {
let mut path = args_log_dir.clone();
path.push("caliptra_instr_trace.txt");
Some(path)
} else {
None
};
// If no GDB Port is passed, Free Run
free_run(cpu, instr_trace, events_to_caliptra, events_from_caliptra);
}
}
Ok(())
}
fn change_dword_endianess(data: &mut [u8]) {
for idx in (0..data.len()).step_by(4) {
data.swap(idx, idx + 3);
data.swap(idx + 1, idx + 2);
}
}
fn upload_fw_to_mailbox(mailbox: &mut MailboxInternal, firmware_buffer: Rc<Vec<u8>>) {
let soc_mbox = mailbox.as_external(MailboxRequester::SocUser(1u32)).regs();
// Write the cmd to mailbox.
assert!(!soc_mbox.lock().read().lock());
soc_mbox.cmd().write(|_| FW_LOAD_CMD_OPCODE);
soc_mbox.dlen().write(|_| firmware_buffer.len() as u32);
//
// Write firmware image.
//
let word_size = std::mem::size_of::<u32>();
let remainder = firmware_buffer.len() % word_size;
let n = firmware_buffer.len() - remainder;
for idx in (0..n).step_by(word_size) {
soc_mbox.datain().write(|_| {
u32::from_le_bytes(firmware_buffer[idx..idx + word_size].try_into().unwrap())
});
}
// Handle the remainder bytes.
if remainder > 0 {
let mut last_word = firmware_buffer[n] as u32;
for idx in 1..remainder {
last_word |= (firmware_buffer[n + idx] as u32) << (idx << 3);
}
soc_mbox.datain().write(|_| last_word);
}
// Set the execute register.
soc_mbox.execute().write(|w| w.execute(true));
}
fn issue_ri_download_fw_mbox_cmd(mailbox: &mut MailboxInternal) {
let soc_mbox = mailbox.as_external(MailboxRequester::SocUser(1u32)).regs();
// Write the cmd to mailbox.
assert!(!soc_mbox.lock().read().lock());
// Set command
soc_mbox.cmd().write(|_| RI_DOWNLOAD_FIRMWARE);
// No data to send so set len to 0
soc_mbox.dlen().write(|_| 0);
// Execute
soc_mbox.execute().write(|w| w.execute(true));
}
fn download_idev_id_csr(
mailbox: &mut MailboxInternal,
path: Rc<PathBuf>,
cptra_dbg_manuf_service_reg: &mut InMemoryRegister<u32, DebugManufService::Register>,
) {
let mut path = path.to_path_buf();
path.push("caliptra_ldevid_cert.der");
let mut file = std::fs::File::create(path).unwrap();
let soc_mbox = mailbox.as_external(MailboxRequester::SocUser(1u32)).regs();
let byte_count = soc_mbox.dlen().read() as usize;
let remainder = byte_count % core::mem::size_of::<u32>();
let n = byte_count - remainder;
for _ in (0..n).step_by(core::mem::size_of::<u32>()) {
let buf = soc_mbox.dataout().read();
file.write_all(&buf.to_le_bytes()).unwrap();
}
if remainder > 0 {
let part = soc_mbox.dataout().read();
for idx in 0..remainder {
let byte = ((part >> (idx << 3)) & 0xFF) as u8;
file.write_all(&[byte]).unwrap();
}
}
// Complete the mailbox command.
soc_mbox.status().write(|w| w.status(|w| w.cmd_complete()));
// Clear the Idevid CSR requested bit.
cptra_dbg_manuf_service_reg.modify(DebugManufService::REQ_IDEVID_CSR::CLEAR);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/app/src/gdb/gdb_target.rs | sw-emulator/app/src/gdb/gdb_target.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
gdb_target.rs
Abstract:
File contains gdb_target module for Caliptra Emulator.
--*/
use caliptra_emu_cpu::xreg_file::XReg;
use caliptra_emu_cpu::StepAction;
use caliptra_emu_cpu::{Cpu, WatchPtrKind};
use caliptra_emu_periph::CaliptraRootBus;
use caliptra_emu_types::RvSize;
use gdbstub::arch::SingleStepGdbBehavior;
use gdbstub::common::Signal;
use gdbstub::stub::SingleThreadStopReason;
use gdbstub::target;
use gdbstub::target::ext::base::singlethread::{SingleThreadBase, SingleThreadResume};
use gdbstub::target::ext::base::BaseOps;
use gdbstub::target::ext::breakpoints::WatchKind;
use gdbstub::target::Target;
use gdbstub::target::TargetResult;
use gdbstub_arch;
pub enum ExecMode {
Step,
Continue,
}
pub struct GdbTarget {
cpu: Cpu<CaliptraRootBus>,
exec_mode: ExecMode,
breakpoints: Vec<u32>,
}
impl GdbTarget {
// Create new instance of GdbTarget
pub fn new(cpu: Cpu<CaliptraRootBus>) -> Self {
Self {
cpu,
exec_mode: ExecMode::Continue,
breakpoints: Vec::new(),
}
}
// Conditional Run (Private function)
fn cond_run(&mut self) -> SingleThreadStopReason<u32> {
loop {
match self.cpu.step(None) {
StepAction::Continue => {
if self.breakpoints.contains(&self.cpu.read_pc()) {
return SingleThreadStopReason::SwBreak(());
}
}
StepAction::Break => {
let watch = self.cpu.get_watchptr_hit().unwrap();
return SingleThreadStopReason::Watch {
tid: (),
kind: if watch.kind == WatchPtrKind::Write {
WatchKind::Write
} else {
WatchKind::Read
},
addr: watch.addr,
};
}
_ => break,
}
}
SingleThreadStopReason::Exited(0)
}
// run the gdb target
pub fn run(&mut self) -> SingleThreadStopReason<u32> {
match self.exec_mode {
ExecMode::Step => {
self.cpu.step(None);
SingleThreadStopReason::DoneStep
}
ExecMode::Continue => self.cond_run(),
}
}
}
impl Target for GdbTarget {
type Arch = gdbstub_arch::riscv::Riscv32;
type Error = &'static str;
fn base_ops(&mut self) -> BaseOps<Self::Arch, Self::Error> {
BaseOps::SingleThread(self)
}
fn guard_rail_implicit_sw_breakpoints(&self) -> bool {
true
}
fn guard_rail_single_step_gdb_behavior(&self) -> SingleStepGdbBehavior {
SingleStepGdbBehavior::Optional
}
fn support_breakpoints(
&mut self,
) -> Option<target::ext::breakpoints::BreakpointsOps<'_, Self>> {
Some(self)
}
}
impl SingleThreadBase for GdbTarget {
fn read_registers(
&mut self,
regs: &mut gdbstub_arch::riscv::reg::RiscvCoreRegs<u32>,
) -> TargetResult<(), Self> {
// Read PC
regs.pc = self.cpu.read_pc();
// Read XReg
for idx in 0..regs.x.len() {
regs.x[idx] = self.cpu.read_xreg(XReg::from(idx as u16)).unwrap();
}
Ok(())
}
fn write_registers(
&mut self,
regs: &gdbstub_arch::riscv::reg::RiscvCoreRegs<u32>,
) -> TargetResult<(), Self> {
// Write PC
self.cpu.write_pc(regs.pc);
// Write XReg
for idx in 0..regs.x.len() {
self.cpu
.write_xreg(XReg::from(idx as u16), regs.x[idx])
.unwrap();
}
Ok(())
}
fn read_addrs(&mut self, start_addr: u32, data: &mut [u8]) -> TargetResult<(), Self> {
for (addr, val) in (start_addr..).zip(data.iter_mut()) {
*val = self.cpu.read_bus(RvSize::Byte, addr).unwrap() as u8;
}
Ok(())
}
fn write_addrs(&mut self, start_addr: u32, data: &[u8]) -> TargetResult<(), Self> {
for (addr, val) in (start_addr..).zip(data.iter().copied()) {
self.cpu.write_bus(RvSize::Byte, addr, val as u32).unwrap();
}
Ok(())
}
fn support_resume(
&mut self,
) -> Option<target::ext::base::singlethread::SingleThreadResumeOps<'_, Self>> {
Some(self)
}
}
impl target::ext::base::singlethread::SingleThreadSingleStep for GdbTarget {
fn step(&mut self, signal: Option<Signal>) -> Result<(), Self::Error> {
if signal.is_some() {
return Err("no support for stepping with signal");
}
self.exec_mode = ExecMode::Step;
Ok(())
}
}
impl SingleThreadResume for GdbTarget {
fn resume(&mut self, signal: Option<Signal>) -> Result<(), Self::Error> {
if signal.is_some() {
return Err("no support for continuing with signal");
}
self.exec_mode = ExecMode::Continue;
Ok(())
}
#[inline(always)]
fn support_single_step(
&mut self,
) -> Option<target::ext::base::singlethread::SingleThreadSingleStepOps<'_, Self>> {
Some(self)
}
}
impl target::ext::breakpoints::Breakpoints for GdbTarget {
#[inline(always)]
fn support_sw_breakpoint(
&mut self,
) -> Option<target::ext::breakpoints::SwBreakpointOps<'_, Self>> {
Some(self)
}
#[inline(always)]
fn support_hw_watchpoint(
&mut self,
) -> Option<target::ext::breakpoints::HwWatchpointOps<'_, Self>> {
Some(self)
}
}
impl target::ext::breakpoints::SwBreakpoint for GdbTarget {
fn add_sw_breakpoint(&mut self, addr: u32, _kind: usize) -> TargetResult<bool, Self> {
self.breakpoints.push(addr);
Ok(true)
}
fn remove_sw_breakpoint(&mut self, addr: u32, _kind: usize) -> TargetResult<bool, Self> {
match self.breakpoints.iter().position(|x| *x == addr) {
None => return Ok(false),
Some(pos) => self.breakpoints.remove(pos),
};
Ok(true)
}
}
impl target::ext::breakpoints::HwWatchpoint for GdbTarget {
fn add_hw_watchpoint(
&mut self,
addr: u32,
len: u32,
kind: WatchKind,
) -> TargetResult<bool, Self> {
// Add Watchpointer (and transform WatchKind to WatchPtrKind)
self.cpu.add_watchptr(
addr,
len,
if kind == WatchKind::Write {
WatchPtrKind::Write
} else {
WatchPtrKind::Read
},
);
Ok(true)
}
fn remove_hw_watchpoint(
&mut self,
addr: u32,
len: u32,
kind: WatchKind,
) -> TargetResult<bool, Self> {
// Remove Watchpointer (and transform WatchKind to WatchPtrKind)
self.cpu.remove_watchptr(
addr,
len,
if kind == WatchKind::Write {
WatchPtrKind::Write
} else {
WatchPtrKind::Read
},
);
Ok(true)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/app/src/gdb/mod.rs | sw-emulator/app/src/gdb/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
gdb_target.rs
Abstract:
File contains gdb module for Caliptra Emulator.
--*/
pub mod gdb_state;
pub mod gdb_target;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/app/src/gdb/gdb_state.rs | sw-emulator/app/src/gdb/gdb_state.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
gdb_state.rs
Abstract:
File contains gdb_state module for Caliptra Emulator.
--*/
use super::gdb_target::GdbTarget;
use gdbstub::common::Signal;
use gdbstub::conn::{Connection, ConnectionExt};
use gdbstub::stub::SingleThreadStopReason;
use gdbstub::stub::{run_blocking, DisconnectReason, GdbStub, GdbStubError};
use gdbstub::target::Target;
use std::net::TcpListener;
enum GdbEventLoop {}
// The `run_blocking::BlockingEventLoop` groups together various callbacks
// the `GdbStub::run_blocking` event loop requires you to implement.
impl run_blocking::BlockingEventLoop for GdbEventLoop {
type Target = GdbTarget;
type Connection = Box<dyn ConnectionExt<Error = std::io::Error>>;
// or MultiThreadStopReason on multi threaded targets
type StopReason = SingleThreadStopReason<u32>;
// Invoked immediately after the target's `resume` method has been
// called. The implementation should block until either the target
// reports a stop reason, or if new data was sent over the connection.
fn wait_for_stop_reason(
target: &mut GdbTarget,
_conn: &mut Self::Connection,
) -> Result<
run_blocking::Event<SingleThreadStopReason<u32>>,
run_blocking::WaitForStopReasonError<
<Self::Target as Target>::Error,
<Self::Connection as Connection>::Error,
>,
> {
// Execute Target until a stop reason (e.g. SW Breakpoint)
let stop_reason = target.run();
// Report Stop Reason
Ok(run_blocking::Event::TargetStopped(stop_reason))
}
// Invoked when the GDB client sends a Ctrl-C interrupt.
fn on_interrupt(
_target: &mut GdbTarget,
) -> Result<Option<SingleThreadStopReason<u32>>, <GdbTarget as Target>::Error> {
// a pretty typical stop reason in response to a Ctrl-C interrupt is to
// report a "Signal::SIGINT".
Ok(Some(SingleThreadStopReason::Signal(Signal::SIGINT)))
}
}
// Routine which creates TCP Socket for GDB and execute State Machine
pub fn wait_for_gdb_run(cpu: &mut GdbTarget, port: u16) {
// Create Socket
let sockaddr = format!("localhost:{}", port);
eprintln!("Waiting for a GDB connection on {:?}...", sockaddr);
let sock = TcpListener::bind(sockaddr).unwrap();
let (stream, addr) = sock.accept().unwrap();
eprintln!("Debugger connected from {}", addr);
// Create Connection
let connection: Box<dyn ConnectionExt<Error = std::io::Error>> = Box::new(stream);
// Instantiate GdbStub
let gdb = GdbStub::new(connection);
// Execute GDB until a disconnect event
match gdb.run_blocking::<GdbEventLoop>(cpu) {
Ok(disconnect_reason) => match disconnect_reason {
DisconnectReason::Disconnect => {
println!("Client disconnected")
}
DisconnectReason::TargetExited(code) => {
println!("Target exited with code {}", code)
}
DisconnectReason::TargetTerminated(sig) => {
println!("Target terminated with signal {}", sig)
}
DisconnectReason::Kill => println!("GDB sent a kill command"),
},
Err(GdbStubError::TargetError(e)) => {
println!("target encountered a fatal error: {}", e)
}
Err(e) => {
println!("gdbstub encountered a fatal error: {}", e)
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/compliance-test/src/fs.rs | sw-emulator/compliance-test/src/fs.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fs.rs
Abstract:
Offers filesystem functionality similar to std::fs but with better error
messages that include the path.
--*/
use std::fmt::Debug;
use std::path::{Path, PathBuf};
/// Same as [`std::fs::create_dir`] but with more informative errors.
pub fn create_dir<P: AsRef<Path> + Debug>(path: P) -> std::io::Result<()> {
std::fs::create_dir(&path)
.map_err(|err| annotate_error(err, &format!("while creating dir {:?}", path)))
}
/// Same as [`std::fs::write`] but with more informative errors.
#[allow(dead_code)]
pub fn write<P: AsRef<Path> + Debug, C: AsRef<[u8]>>(path: P, contents: C) -> std::io::Result<()> {
std::fs::write(&path, contents)
.map_err(|err| annotate_error(err, &format!("while writing to file {:?}", path)))
}
/// Same as [`std::fs::read`] but with more informative errors.
pub fn read<P: AsRef<Path> + Debug>(path: P) -> std::io::Result<Vec<u8>> {
std::fs::read(&path)
.map_err(|err| annotate_error(err, &format!("while reading from file {:?}", path)))
}
pub struct TempFile {
path: PathBuf,
}
impl TempFile {
#[allow(dead_code)]
pub fn new() -> std::io::Result<Self> {
Ok(Self {
path: Path::join(&std::env::temp_dir(), rand_str()?),
})
}
pub fn with_extension(ext: &str) -> std::io::Result<Self> {
Ok(Self {
path: Path::join(&std::env::temp_dir(), rand_str()? + ext),
})
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Debug for TempFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.path, f)
}
}
impl AsRef<Path> for TempFile {
fn as_ref(&self) -> &Path {
&self.path
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path());
}
}
/// A temporary directory that will be deleted (best-effort) when the
/// [`TempDir`] is dropped.
pub struct TempDir {
path: PathBuf,
}
impl TempDir {
/// Creates a new temporary directory in the system temp directory
/// with a random name.
pub fn new() -> std::io::Result<Self> {
let path = Path::join(&std::env::temp_dir(), rand_str()?);
create_dir(&path)?;
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(self.path());
}
}
impl Debug for TempDir {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.path, f)
}
}
impl AsRef<Path> for TempDir {
fn as_ref(&self) -> &Path {
&self.path
}
}
pub fn annotate_error(err: std::io::Error, suffix: &str) -> std::io::Error {
std::io::Error::new(err.kind(), err.to_string() + ": " + suffix)
}
fn rand_str() -> std::io::Result<String> {
let chars = b"abcdefghijklmnopqrstuvwxyz123456";
let mut result = vec![0u8; 24];
if let Err(err) = getrandom::getrandom(&mut result) {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Unable to retrive random data from OS: {}", err),
));
}
for ch in result.iter_mut() {
*ch = chars[usize::from(*ch & 0x1f)];
}
Ok(String::from_utf8(result).unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
use std::{io::ErrorKind, sync::Mutex};
#[test]
fn test_create_dir_success() {
let tmp_dir = TempDir::new().unwrap();
let my_dir_path = tmp_dir.path().join("my_unique_and_awesome_dir");
create_dir(&my_dir_path).unwrap();
assert!(std::fs::metadata(&my_dir_path).unwrap().is_dir());
}
#[test]
fn test_create_dir_failure() {
let tmp_dir = TempDir::new().unwrap();
let my_dir_path = tmp_dir.path().join("my_unique_and_awesome_dir");
create_dir(&my_dir_path).unwrap();
let result = create_dir(&my_dir_path);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::AlreadyExists);
assert!(err.to_string().contains("while creating dir"));
assert!(err.to_string().contains("my_unique_and_awesome_dir"));
}
#[test]
fn test_read_and_write_success() {
let tmp_file = TempFile::with_extension(".txt").unwrap();
// Read-and-write success case
write(&tmp_file, "Hello world").unwrap();
assert_eq!(read(&tmp_file).unwrap(), b"Hello world");
}
#[test]
fn test_read_failure() {
let tmp_file = TempFile::with_extension(".txt").unwrap();
let result = read(&tmp_file);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::NotFound);
assert!(err
.to_string()
.contains(&format!("while reading from file {:?}", tmp_file.path())));
}
#[test]
fn test_write_failure() {
let no_such_dir = TempFile::new().unwrap();
let file_path = no_such_dir.path().join("foobar");
let result = write(&file_path, "Hello world!");
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::NotFound);
assert!(err
.to_string()
.contains(&format!("while writing to file {:?}", file_path)));
}
#[test]
fn test_tempfile() {
let temp_files = [
TempFile::new().unwrap(),
TempFile::new().unwrap(),
TempFile::with_extension(".o").unwrap(),
TempFile::with_extension(".o").unwrap(),
];
let paths: Vec<PathBuf> = temp_files.iter().map(|t| t.path().to_path_buf()).collect();
assert!(paths.iter().all(|p| !p.exists()));
assert!([&paths[2], &paths[3]]
.iter()
.all(|p| p.to_str().unwrap().ends_with(".o")));
assert_ne!(&paths[0], &paths[1]);
assert_ne!(&paths[2], &paths[3]);
write(&paths[0], "Hello").unwrap();
write(&temp_files[2], "World").unwrap();
assert!([&paths[0], &paths[2]].iter().all(|p| p.exists()));
assert!([&paths[1], &paths[3]].iter().all(|p| !p.exists()));
drop(temp_files);
assert!(paths.iter().all(|p| !p.exists()));
}
#[test]
fn test_tempfile_drop_on_panic() {
let tmp_path: Mutex<Option<PathBuf>> = Mutex::new(None);
let err = std::panic::catch_unwind(|| {
let tmp = TempFile::new().unwrap();
write(&tmp, "hello").unwrap();
*tmp_path.lock().unwrap() = Some(tmp.path().to_owned());
assert!(tmp.path().exists());
panic!("fake panic");
})
.err()
.unwrap();
assert_eq!(*err.downcast_ref::<&'static str>().unwrap(), "fake panic");
assert!(!tmp_path.into_inner().unwrap().unwrap().exists());
}
#[test]
fn test_tempdir_deleted() {
let dir = TempDir::new().unwrap();
let path = dir.path().to_owned();
assert!(path.is_dir());
write(path.join("file0.txt"), "Hello").unwrap();
write(path.join("file1.txt"), "world!").unwrap();
assert!([&path, &path.join("file0.txt"), &path.join("file1.txt")]
.iter()
.all(|p| p.exists()));
drop(dir);
assert!([&path, &path.join("file0.txt"), &path.join("file1.txt")]
.iter()
.all(|p| !p.exists()));
}
#[cfg(target_family = "unix")]
#[test]
fn test_tempdir_delete_error() {
use std::os::unix::prelude::PermissionsExt;
let dir = TempDir::new().unwrap();
let dir_path = dir.path().to_owned();
let inner_dir = dir.path().join("inner");
create_dir(&inner_dir).unwrap();
let file_path = inner_dir.join("file0.txt");
write(file_path, "Hello").unwrap();
std::fs::set_permissions(&inner_dir, std::fs::Permissions::from_mode(0o000)).unwrap();
assert!([&dir_path, &inner_dir].iter().all(|p| p.exists()));
drop(dir);
// Note: attempts to remove the directory on drop are best effort
assert!([&dir_path, &inner_dir].iter().all(|p| p.exists()));
std::fs::set_permissions(&inner_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::remove_dir_all(dir_path).unwrap();
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/compliance-test/src/test_builder.rs | sw-emulator/compliance-test/src/test_builder.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
test_builder.rs
Abstract:
Code for compiling risc-v compliance tests from https://github.com/riscv-non-isa/riscv-arch-test.
--*/
use crate::exec::exec;
use crate::fs::{self, TempDir, TempFile};
use crate::{into_io_error, TestInfo};
use std::path::PathBuf;
use std::process::Command;
#[derive(Clone)]
pub struct TestBuilderConfig {
pub test_root_path: PathBuf,
pub compiler_path: PathBuf,
pub objcopy_path: PathBuf,
pub linker_script_contents: &'static [u8],
pub model_test_contents: &'static [u8],
}
pub struct TestBuilder {
config: TestBuilderConfig,
include_dir: TempDir,
linker_script: TempFile,
}
impl TestBuilder {
pub fn new(config: TestBuilderConfig) -> std::io::Result<Self> {
let include_dir = TempDir::new()?;
std::fs::write(
include_dir.path().join("model_test.h"),
config.model_test_contents,
)?;
let linker_script = TempFile::with_extension("ld")?;
std::fs::write(&linker_script, config.linker_script_contents)?;
Ok(Self {
config,
include_dir,
linker_script,
})
}
pub fn build_test_binary(&self, test: &TestInfo) -> std::io::Result<Vec<u8>> {
let elf_file = TempFile::with_extension(".o")?;
let bin_file = TempFile::with_extension(".bin")?;
exec(
Command::new(&self.config.compiler_path)
.arg("-march=rv32i")
.arg("-mabi=ilp32")
.arg("-DXLEN=32")
.arg("-static")
.arg("-mcmodel=medany")
.arg(if test.extension == "C" {
"-march=rv32imc"
} else {
"-march=rv32im"
})
.arg("-mabi=ilp32")
.arg("-fvisibility=hidden")
.arg("-nostdlib")
.arg("-nostartfiles")
.arg("-I")
.arg(self.config.test_root_path.join("riscv-test-suite/env/"))
.arg("-I")
.arg(self.include_dir.path())
.arg("-T")
.arg(self.linker_script.path())
.arg(
self.config
.test_root_path
.join("riscv-test-suite/rv32i_m")
.join(test.extension)
.join("src")
.join(format!("{}.S", test.name)),
)
.arg("-o")
.arg(elf_file.path()),
)?;
exec(
Command::new(&self.config.objcopy_path)
.arg("-O")
.arg("binary")
.arg(elf_file.path())
.arg(bin_file.path()),
)?;
fs::read(&bin_file)
}
pub fn get_reference_data(&self, test: &TestInfo) -> std::io::Result<String> {
String::from_utf8(fs::read(
self.config
.test_root_path
.join("riscv-test-suite/rv32i_m")
.join(test.extension)
.join("references")
.join(format!("{}.reference_output", test.name)),
)?)
.map_err(into_io_error)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/compliance-test/src/main.rs | sw-emulator/compliance-test/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
Test-runner for risc-v compliance tests from https://github.com/riscv-non-isa/riscv-arch-test.
--*/
use crate::test_builder::{TestBuilder, TestBuilderConfig};
use caliptra_emu_bus::{Bus, Clock, Ram};
use caliptra_emu_cpu::{Cpu, CpuArgs, Pic, StepAction};
use caliptra_emu_types::RvSize;
use clap::{arg, value_parser};
use std::error::Error;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::rc::Rc;
mod exec;
mod fs;
mod test_builder;
pub struct TestInfo {
extension: &'static str,
name: &'static str,
}
#[rustfmt::skip]
static TESTS_TO_RUN: &[TestInfo] = &[
TestInfo {extension: "I", name: "add-01"},
TestInfo {extension: "I", name: "addi-01"},
TestInfo {extension: "I", name: "and-01"},
TestInfo {extension: "I", name: "andi-01"},
TestInfo {extension: "I", name: "auipc-01"},
TestInfo {extension: "I", name: "beq-01"},
TestInfo {extension: "I", name: "bge-01"},
TestInfo {extension: "I", name: "bgeu-01"},
TestInfo {extension: "I", name: "blt-01"},
TestInfo {extension: "I", name: "bltu-01"},
TestInfo {extension: "I", name: "bne-01"},
TestInfo {extension: "I", name: "fence-01"},
TestInfo {extension: "I", name: "jal-01"},
//TestInfo {extension: "I", name: "jalr-01"}, // broken in Ubuntu 24.04 due to assembler rejecting la x0,0x5b
TestInfo {extension: "I", name: "lb-align-01"},
TestInfo {extension: "I", name: "lbu-align-01"},
TestInfo {extension: "I", name: "lh-align-01"},
TestInfo {extension: "I", name: "lhu-align-01"},
TestInfo {extension: "I", name: "lui-01"},
TestInfo {extension: "I", name: "lw-align-01"},
TestInfo {extension: "I", name: "or-01"},
TestInfo {extension: "I", name: "ori-01"},
TestInfo {extension: "I", name: "sb-align-01"},
TestInfo {extension: "I", name: "sh-align-01"},
TestInfo {extension: "I", name: "sll-01"},
TestInfo {extension: "I", name: "slli-01"},
TestInfo {extension: "I", name: "slt-01"},
TestInfo {extension: "I", name: "slti-01"},
TestInfo {extension: "I", name: "sltiu-01"},
TestInfo {extension: "I", name: "sltu-01"},
TestInfo {extension: "I", name: "sra-01"},
TestInfo {extension: "I", name: "srai-01"},
TestInfo {extension: "I", name: "srl-01"},
TestInfo {extension: "I", name: "srli-01"},
TestInfo {extension: "I", name: "sub-01"},
TestInfo {extension: "I", name: "sw-align-01"},
TestInfo {extension: "I", name: "xor-01"},
TestInfo {extension: "I", name: "xori-01"},
TestInfo {extension: "M", name: "div-01"},
TestInfo {extension: "M", name: "divu-01"},
TestInfo {extension: "M", name: "mul-01"},
TestInfo {extension: "M", name: "mulh-01"},
TestInfo {extension: "M", name: "mulhsu-01"},
TestInfo {extension: "M", name: "mulhu-01"},
TestInfo {extension: "M", name: "rem-01"},
TestInfo {extension: "M", name: "remu-01"},
TestInfo {extension: "C", name: "cadd-01"},
TestInfo {extension: "C", name: "caddi-01"},
TestInfo {extension: "C", name: "caddi16sp-01"},
TestInfo {extension: "C", name: "caddi4spn-01"},
TestInfo {extension: "C", name: "cand-01"},
TestInfo {extension: "C", name: "candi-01"},
TestInfo {extension: "C", name: "cbeqz-01"},
TestInfo {extension: "C", name: "cbnez-01"},
//TestInfo {extension: "C", name: "cebreak-01"},
TestInfo {extension: "C", name: "cj-01"},
TestInfo {extension: "C", name: "cjal-01"},
TestInfo {extension: "C", name: "cjalr-01"},
TestInfo {extension: "C", name: "cjr-01"},
TestInfo {extension: "C", name: "cli-01"},
TestInfo {extension: "C", name: "clui-01"},
TestInfo {extension: "C", name: "clw-01"},
TestInfo {extension: "C", name: "clwsp-01"},
TestInfo {extension: "C", name: "cmv-01"},
TestInfo {extension: "C", name: "cnop-01"},
TestInfo {extension: "C", name: "cor-01"},
TestInfo {extension: "C", name: "cslli-01"},
TestInfo {extension: "C", name: "csrai-01"},
TestInfo {extension: "C", name: "csrli-01"},
TestInfo {extension: "C", name: "csub-01"},
TestInfo {extension: "C", name: "csw-01"},
TestInfo {extension: "C", name: "cswsp-01"},
TestInfo {extension: "C", name: "cxor-01"},
];
fn into_io_error(err: impl Into<Box<dyn Error + Send + Sync>>) -> std::io::Error {
std::io::Error::new(ErrorKind::Other, err)
}
fn check_reference_data(expected_txt: &str, bus: &mut impl Bus) -> std::io::Result<()> {
let mut addr = 0x1000;
for line in expected_txt.lines() {
let expected_word = u32::from_str_radix(line, 16).map_err(into_io_error)?;
let actual_word = match bus.read(RvSize::Word, addr) {
Ok(val) => val,
Err(err) => {
return Err(into_io_error(format!(
"Error accessing memory for comparison with reference data: {:?}",
err
)))
}
};
if expected_word != actual_word {
return Err(std::io::Error::new(
ErrorKind::Other,
format!(
"At addr {:#x}, expected {:#010x} but was {:#010x}",
addr, expected_word, actual_word
),
));
}
addr += 4;
}
Ok(())
}
fn is_test_complete(bus: &mut impl Bus) -> bool {
bus.read(RvSize::Word, 0x0).unwrap() != 0
}
fn main() -> Result<(), Box<dyn Error>> {
let args = clap::Command::new("compliance-test")
.about("RISC-V compliance suite runner")
.arg(arg!(--test_root_path <DIR> "Path to directory containing https://github.com/riscv-non-isa/riscv-arch-test").value_parser(value_parser!(PathBuf)))
.arg(arg!(--compiler <FILE> "Path to risc-v build of gcc").required(false).default_value("riscv64-unknown-elf-gcc").value_parser(value_parser!(PathBuf)))
.arg(arg!(--objcopy <FILE> "Path to risc-v build of objcopy").required(false).default_value("riscv64-unknown-elf-objcopy").value_parser(value_parser!(PathBuf)))
.get_matches();
let builder = TestBuilder::new(TestBuilderConfig {
test_root_path: args.get_one::<PathBuf>("test_root_path").unwrap().clone(),
compiler_path: args.get_one::<PathBuf>("compiler").unwrap().clone(),
objcopy_path: args.get_one::<PathBuf>("objcopy").unwrap().clone(),
linker_script_contents: include_bytes!("../target-files/link.ld"),
model_test_contents: include_bytes!("../target-files/model_test.h"),
})?;
for test in TESTS_TO_RUN.iter() {
println!("Running test {}/{}", test.extension, test.name);
let binary: Vec<u8> = builder.build_test_binary(test)?;
let reference_txt = builder.get_reference_data(test)?;
let pic = Rc::new(Pic::new());
let clock = Rc::new(Clock::new());
let args = CpuArgs::default();
let mut cpu = Cpu::new(Ram::new(binary), clock, pic, args);
cpu.write_pc(0x3000);
while !is_test_complete(&mut cpu.bus) {
match cpu.step(None) {
StepAction::Continue => continue,
_ => break,
}
}
if !is_test_complete(&mut cpu.bus) {
Err(std::io::Error::new(
ErrorKind::Other,
"test did not complete",
))?;
}
check_reference_data(&reference_txt, &mut cpu.bus)?;
println!("PASSED");
drop(cpu);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_check_reference_data() {
let mut ram_bytes = vec![0u8; 4096];
ram_bytes.extend(vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]);
let pic = Rc::new(Pic::new());
let args = CpuArgs::default();
let mut cpu = Cpu::new(Ram::new(ram_bytes), Rc::new(Clock::new()), pic, args);
check_reference_data("03020100\n07060504\n", &mut cpu.bus).unwrap();
assert_eq!(
check_reference_data("03050100\n07060503\n", &mut cpu.bus)
.err()
.unwrap()
.to_string(),
"At addr 0x1000, expected 0x03050100 but was 0x03020100"
);
assert_eq!(
check_reference_data("03020100\n07060502", &mut cpu.bus)
.err()
.unwrap()
.to_string(),
"At addr 0x1004, expected 0x07060502 but was 0x07060504"
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/compliance-test/src/exec.rs | sw-emulator/compliance-test/src/exec.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
exec.rs
Abstract:
Offers exec (subprocess) functionality similar to std::process but with better error
messages that include paths, args, and stderr.
--*/
use crate::fs::annotate_error;
use std::ffi::OsString;
use std::fmt;
use std::io::{self, ErrorKind, Write};
/// Executes a command (subprocess).
///
/// If it fails, the error has a very descriptive error message that includes
/// stderr from the command along with all the arguments to command.
pub fn exec(cmd: &mut std::process::Command) -> io::Result<()> {
let output = cmd
.stdout(std::process::Stdio::inherit())
.output()
.map_err(|err| {
annotate_error(
err,
&format!("while running command {:?}", collect_args(cmd)),
)
})?;
if output.status.success() {
io::stderr().write_all(&output.stderr)?;
Ok(())
} else {
Err(ExecError {
code: output.status.code(),
args: collect_args(cmd),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
}
.into_io_error())
}
}
pub struct ExecError {
/// The exit code of the subprocess. If the subprocess could not be started,
/// this will be [`None`].
code: Option<i32>,
/// The arguments passed to the subprocess. `args[0]` will be the executable.
args: Vec<OsString>,
/// The captured stderr from the process, lossily converted to UTF-8.
stderr: String,
}
impl ExecError {
fn into_io_error(self) -> io::Error {
io::Error::new(ErrorKind::Other, self)
}
}
impl std::error::Error for ExecError {}
impl fmt::Display for ExecError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Subprocess exited with error {:?}: {:?}\n{}",
self.code, self.args, self.stderr
)
}
}
impl fmt::Debug for ExecError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
fn collect_args(cmd: &std::process::Command) -> Vec<OsString> {
std::iter::once(cmd.get_program())
.chain(cmd.get_args())
.map(OsString::from)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fs::TempFile;
#[cfg(target_family = "unix")]
#[test]
fn test_exec_success() {
let temp_file = TempFile::new().unwrap();
assert!(!temp_file.path().exists());
exec(std::process::Command::new("touch").arg(temp_file.path())).unwrap();
assert!(temp_file.path().exists());
}
#[cfg(target_family = "unix")]
#[test]
fn test_exec_process_not_found() {
let result = exec(&mut std::process::Command::new(
"/tmp/pvoruxpa5dbnjv5sj5t15omn",
));
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::NotFound);
assert!(err
.to_string()
.contains("while running command [\"/tmp/pvoruxpa5dbnjv5sj5t15omn\"]"));
}
#[cfg(target_family = "unix")]
#[test]
fn test_exec_process_returned_nonzero() {
let result = exec(std::process::Command::new("cat").arg("/tmp/pvoruxpa5dbnjv5sj5t15omn"));
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::Other);
let err = err.into_inner().unwrap().downcast::<ExecError>().unwrap();
assert_eq!(err.code, Some(1));
assert_eq!(
&err.stderr,
"cat: /tmp/pvoruxpa5dbnjv5sj5t15omn: No such file or directory\n"
);
assert_eq!(
err.args,
vec![
OsString::from("cat"),
OsString::from("/tmp/pvoruxpa5dbnjv5sj5t15omn")
]
);
assert_eq!(
format!("{}", err),
"Subprocess exited with error Some(1): [\"cat\", \"/tmp/pvoruxpa5dbnjv5sj5t15omn\"]\n\
cat: /tmp/pvoruxpa5dbnjv5sj5t15omn: No such file or directory\n"
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/example/build.rs | sw-emulator/example/build.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
build.rs
Abstract:
Cargo build file
--*/
fn main() {
println!("cargo:rerun-if-changed=src/link.ld");
println!("cargo:rerun-if-changed=src/start.S");
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/example/src/main.rs | sw-emulator/example/src/main.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
File contains entry point for bare-metal RISCV program
--*/
#![no_std]
#![no_main]
use core::arch::global_asm;
use core::ptr;
global_asm!(include_str!("start.S"));
const OUT_STR: &'static [u8; 14] = b"Hello Caliptra";
static mut COUNT: u8 = 0x41;
#[no_mangle]
pub extern "C" fn main() {
const UART0: *mut u8 = 0x2000_1041 as *mut u8;
unsafe {
for byte in OUT_STR {
ptr::write_volatile(UART0, COUNT);
ptr::write_volatile(UART0, *byte);
COUNT = COUNT + 1;
}
ptr::write_volatile(UART0, b'\n');
}
}
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/lib.rs | sw-emulator/lib/cpu/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Emulator Library.
--*/
pub mod cpu;
mod csr_file;
mod instr;
mod internal_timers;
mod pic;
mod types;
pub mod xreg_file;
pub use cpu::StepAction;
pub use cpu::WatchPtrHit;
pub use cpu::WatchPtrKind;
pub use cpu::{CodeRange, CoverageBitmaps, Cpu, ImageInfo, InstrTracer, StackInfo, StackRange};
pub use csr_file::CsrFile;
pub use internal_timers::InternalTimers;
pub use pic::{IntSource, Irq, Pic, PicMmioRegisters};
pub use types::CpuArgs;
pub use types::CpuOrgArgs;
pub use types::RvInstr;
pub use types::RvInstr32;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/xreg_file.rs | sw-emulator/lib/cpu/src/xreg_file.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
xreg_file.rs
Abstract:
File contains implementation of RISC-v general purpose register file
--*/
use caliptra_emu_types::{emu_enum, RvAddr, RvData, RvException};
emu_enum!(
/// RISCV general purpose registers
#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub XReg;
RvAddr;
{
X0 = 0,
X1 = 1,
X2 = 2,
X3 = 3,
X4 = 4,
X5 = 5,
X6 = 6,
X7 = 7,
X8 = 8,
X9 = 9,
X10 = 10,
X11 = 11,
X12 = 12,
X13 = 13,
X14 = 14,
X15 = 15,
X16 = 16,
X17 = 17,
X18 = 18,
X19 = 19,
X20 = 20,
X21 = 21,
X22 = 22,
X23 = 23,
X24 = 24,
X25 = 25,
X26 = 26,
X27 = 27,
X28 = 28,
X29 = 29,
X30 = 30,
X31 = 31,
};
Invalid
);
impl From<u16> for XReg {
fn from(val: u16) -> Self {
XReg::from(u32::from(val))
}
}
impl From<XReg> for u16 {
fn from(val: XReg) -> Self {
u16::try_from(u32::from(val)).unwrap()
}
}
/// RISCV General purpose register file
pub struct XRegFile {
/// Registers
reg: [RvData; XRegFile::REG_COUNT],
}
impl XRegFile {
/// Register count
const REG_COUNT: usize = 32;
/// Reset Value
const RESET_VAL: RvData = 0;
/// Create an instance of RISCV General purpose register file
pub fn new() -> Self {
Self {
reg: [XRegFile::RESET_VAL; XRegFile::REG_COUNT],
}
}
/// Reset all the registers to default value
#[allow(dead_code)]
pub fn reset(&mut self) {
self.reg = [XRegFile::RESET_VAL; XRegFile::REG_COUNT]
}
/// Reads the specified register
///
/// # Arguments
///
/// * `reg` - Register to read
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn read(&self, reg: XReg) -> Result<RvData, RvException> {
match reg {
XReg::X0 => Ok(0),
r if (XReg::X1..=XReg::X31).contains(&r) => {
let reg: RvAddr = reg.into();
Ok(self.reg[reg as usize])
}
_ => Err(RvException::illegal_register()),
}
}
/// Writes the value to specified register
///
/// # Arguments
///
/// * `reg` - Register to write
/// * `value` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write(&mut self, reg: XReg, val: RvData) -> Result<(), RvException> {
match reg {
XReg::X0 => Ok(()),
r if (XReg::X1..=XReg::X31).contains(&r) => {
let reg: RvAddr = reg.into();
self.reg[reg as usize] = val;
Ok(())
}
_ => Err(RvException::illegal_register()),
}
}
}
impl Default for XRegFile {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let reg_file = XRegFile::new();
for reg in 0..31u32 {
assert_eq!(reg_file.read(reg.into()).ok(), Some(0))
}
}
#[test]
fn test_reset() {
let mut reg_file = XRegFile::new();
for reg in 1..31u32 {
assert_eq!(reg_file.write(reg.into(), RvData::MAX).ok(), Some(()));
assert_eq!(reg_file.read(reg.into()).ok(), Some(RvData::MAX))
}
reg_file.reset();
for reg in 0..31u32 {
assert_eq!(reg_file.read(reg.into()).ok(), Some(0))
}
}
#[test]
fn test_x0() {
let mut reg_file = XRegFile::new();
assert_eq!(reg_file.write(XReg::X0, RvData::MAX).ok(), Some(()));
assert_eq!(reg_file.read(XReg::X0).ok(), Some(0));
}
#[test]
fn test_read_write() {
let mut reg_file = XRegFile::new();
for reg in 1..31u32 {
assert_eq!(reg_file.write(reg.into(), RvData::MAX).ok(), Some(()));
assert_eq!(reg_file.read(reg.into()).ok(), Some(RvData::MAX))
}
}
#[test]
fn test_read_invalid_reg() {
let reg_file = XRegFile::new();
assert_eq!(
reg_file.read(XReg::Invalid).err(),
Some(RvException::illegal_register())
)
}
#[test]
fn test_write_invalid_reg() {
let mut reg_file = XRegFile::new();
assert_eq!(
reg_file.write(XReg::Invalid, RvData::MAX).err(),
Some(RvException::illegal_register())
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/internal_timers.rs | sw-emulator/lib/cpu/src/internal_timers.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
uart.rs
Abstract:
File contains VeeR Internal Timers implementation.
This implementation is focused on emulator performance
at the cost of accuracy, so it does not need to poll
the CPU every cycle.
--*/
use caliptra_emu_bus::{ActionHandle, Clock, Timer, TimerAction};
use std::rc::Rc;
struct InternalTimer {
/// Which timer are we.
id: u8,
/// Clock.now() when this timer was last written to.
last_set_ticks: u64,
/// Value this timer was last set to
last_set_val: u32,
/// Bound to trigger interrupt at.
bound: u32,
/// The handle for the timer action for the last fired trap.
timer_action: Option<ActionHandle>,
/// Whether this timer is cascaded (timer 1 only).
cascade: bool,
/// True if this timer is incremented in pause mode.
pause_en: bool,
/// True if this timer is incremented in sleep mode.
halt_en: bool,
/// Whether this timer is enabled.
enabled: bool,
}
impl InternalTimer {
fn new(id: u8) -> InternalTimer {
InternalTimer {
id,
last_set_ticks: 0,
last_set_val: 0,
bound: 0xffff_ffff,
timer_action: None,
cascade: false,
pause_en: false,
halt_en: false,
enabled: true,
}
}
fn read_control(&self) -> u32 {
let mut ctl = 0;
if self.cascade {
ctl |= 1 << 3;
}
if self.pause_en {
ctl |= 1 << 2;
}
if self.halt_en {
ctl |= 1 << 1;
}
if self.enabled {
ctl |= 1;
}
ctl
}
fn write_control(&mut self, val: u32, timer: &Timer, now: u64) {
self.enabled = val & 1 == 1;
self.halt_en = val & 2 == 2;
self.pause_en = val & 4 == 4;
self.cascade = val & 8 == 8;
self.arm(timer, now);
}
fn read_time(&self, now: u64) -> u32 {
let elapsed = ((now - self.last_set_ticks) & 0xffff_ffff) as u32;
self.last_set_val.wrapping_add(elapsed)
}
fn write_time(&mut self, val: u32, timer: &Timer, now: u64) {
self.last_set_ticks = now;
self.last_set_val = val;
self.arm(timer, now);
}
fn write_bound(&mut self, val: u32, timer: &Timer, now: u64) {
self.bound = val;
self.arm(timer, now);
}
fn interrupt_pending(&self, now: u64) -> bool {
self.read_time(now) >= self.bound
}
pub(crate) fn ticks_to_interrupt(&self, now: u64) -> u32 {
self.bound.saturating_sub(self.read_time(now)).max(1)
}
pub(crate) fn disarm(&mut self, timer: &Timer) {
if let Some(action) = self.timer_action.take() {
// Cancel the timer action if it exists.
timer.cancel(action);
}
}
fn arm(&mut self, timer: &Timer, now: u64) {
if let Some(action) = self.timer_action.take() {
timer.cancel(action);
}
if !self.enabled {
return;
}
// TODO: support cascaded timer
let next_interrupt = self.ticks_to_interrupt(now);
self.timer_action = Some(timer.schedule_action_in(
next_interrupt as u64,
TimerAction::InternalTimerLocalInterrupt { timer_id: self.id },
));
}
}
pub struct InternalTimers {
clock: Rc<Clock>,
clock_timer: Timer,
timer0: InternalTimer,
timer1: InternalTimer,
}
impl InternalTimers {
pub fn new(clock: Rc<Clock>) -> Self {
let clock_timer = clock.timer();
Self {
clock: clock.clone(),
clock_timer,
timer0: InternalTimer::new(0),
timer1: InternalTimer::new(1),
}
}
pub fn write_mitcnt(&mut self, timer_id: u8, val: u32) {
match timer_id {
0 => self.write_mitcnt0(val),
1 => self.write_mitcnt1(val),
_ => panic!("Invalid timer ID: {}", timer_id),
}
}
pub fn disarm(&mut self, timer_id: u8) {
match timer_id {
0 => self.timer0.disarm(&self.clock_timer),
1 => self.timer1.disarm(&self.clock_timer),
_ => panic!("Invalid timer ID: {}", timer_id),
}
}
pub fn read_mitcnt0(&self) -> u32 {
self.timer0.read_time(self.clock.now())
}
pub fn read_mitcnt1(&self) -> u32 {
self.timer1.read_time(self.clock.now())
}
pub fn write_mitcnt0(&mut self, val: u32) {
self.timer0
.write_time(val, &self.clock_timer, self.clock.now());
}
pub fn write_mitcnt1(&mut self, val: u32) {
self.timer1
.write_time(val, &self.clock_timer, self.clock.now());
}
pub fn read_mitb0(&self) -> u32 {
self.timer0.bound
}
pub fn read_mitb1(&self) -> u32 {
self.timer0.bound
}
pub fn write_mitb0(&mut self, val: u32) {
self.timer0
.write_bound(val, &self.clock_timer, self.clock.now());
}
pub fn write_mitb1(&mut self, val: u32) {
self.timer1
.write_bound(val, &self.clock_timer, self.clock.now());
}
pub fn read_mitctl0(&self) -> u32 {
self.timer0.read_control()
}
pub fn read_mitctl1(&self) -> u32 {
self.timer1.read_control()
}
pub fn write_mitctl0(&mut self, val: u32) {
self.timer0
.write_control(val, &self.clock_timer, self.clock.now())
}
pub fn write_mitctl1(&mut self, val: u32) {
self.timer1
.write_control(val, &self.clock_timer, self.clock.now())
}
pub fn interrupts_pending(&self) -> (bool, bool) {
(
self.timer0.interrupt_pending(self.clock.now()),
self.timer1.interrupt_pending(self.clock.now()),
)
}
}
#[cfg(test)]
mod test {
use std::rc::Rc;
use super::InternalTimer;
use caliptra_emu_bus::Clock;
#[test]
fn test_ticks_to_interrupt() {
let clock = Rc::new(Clock::new());
let t = clock.timer();
let mut itimer = InternalTimer::new(0);
itimer.write_bound(300, &t, 100);
assert_eq!(200, itimer.ticks_to_interrupt(100));
}
#[test]
fn test_ticks_to_interrupt_underflow() {
let clock = Rc::new(Clock::new());
let t = clock.timer();
let mut itimer = InternalTimer::new(0);
itimer.write_bound(300, &t, 100);
assert_eq!(1, itimer.ticks_to_interrupt(400));
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/types.rs | sw-emulator/lib/cpu/src/types.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
types.rs
Abstract:
Common types used in the project.
--*/
#![allow(clippy::unusual_byte_groupings)]
use crate::xreg_file::XReg;
use bitfield::{bitfield, BitRange, BitRangeMut};
use caliptra_emu_types::emu_enum;
/// Memory offsets for CPU
#[derive(Debug, Copy, Clone)]
pub struct CpuOrgArgs {
/// ROM offset
pub rom: u32,
/// ROM size,
pub rom_size: u32,
/// ICCM offset
pub iccm: u32,
/// ICCM size
pub iccm_size: u32,
/// DCCM offset
pub dccm: u32,
/// DCCM size
pub dccm_size: u32,
/// CPU reset vector
pub reset_vector: u32,
}
impl CpuOrgArgs {
/// Default position of ROM in the memory map
pub const DEFAULT_ROM_ORG: u32 = 0x0000_0000;
/// Default size of the ROM
pub const DEFAULT_ROM_SIZE: u32 = 96 * 1024;
/// Default position of the ICCM in the memory map
pub const DEFAULT_ICCM_ORG: u32 = 0x4000_0000;
/// Default size of the ICCM memory
pub const DEFAULT_ICCM_SIZE: u32 = 256 * 1024;
/// Default position of the DCCM in the memory map
pub const DEFAULT_DCCM_ORG: u32 = 0x5000_0000;
/// Default size of the DCCM memory
pub const DEFAULT_DCCM_SIZE: u32 = 256 * 1024;
/// Default CPU reset vector
pub const DEFAULT_RESET_VECTOR: u32 = 0;
}
impl Default for CpuOrgArgs {
fn default() -> Self {
Self {
rom: Self::DEFAULT_ROM_ORG,
rom_size: Self::DEFAULT_ROM_SIZE,
iccm: Self::DEFAULT_ICCM_ORG,
iccm_size: Self::DEFAULT_ICCM_SIZE,
dccm: Self::DEFAULT_DCCM_ORG,
dccm_size: Self::DEFAULT_DCCM_SIZE,
reset_vector: Self::DEFAULT_RESET_VECTOR,
}
}
}
#[derive(Default, Debug, Copy, Clone)]
pub struct CpuArgs {
/// Memory offsets
pub org: CpuOrgArgs,
}
emu_enum! {
/// RISCV 32-bit instruction opcodes
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32Opcode;
u32;
{
/// Load Instruction Opcode
Load = 0b000_0011,
/// Op Immediate Opcode
OpImm = 0b001_0011,
/// AUIPC Opcode
Auipc = 0b001_0111,
/// Store Instruction Opcode
Store = 0b010_0011,
/// Operation Instruction Opcode
Op = 0b011_0011,
/// LUI Opcode
Lui = 0b011_0111,
/// Branch Opcode
Branch = 0b110_0011,
/// Jump and Link Register Opcode
Jalr = 0b110_0111,
/// Jump and Link Opcode
Jal = 0b110_1111,
/// System Opcode
System = 0b111_0011,
/// Fence Opcode
Fence = 0b000_1111,
};
Invalid
}
emu_enum! {
/// RISCV Load Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32LoadFunct3;
u32;
{
/// Load Byte function
Lb = 0b000,
/// Load Half Word function
Lh = 0b001,
/// Load Word function
Lw = 0b010,
/// Load Byte Unsigned function
Lbu = 0b100,
/// Load Half Word Unsigned function
Lhu = 0b101,
};
Invalid
}
emu_enum! {
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32OpImmFunct3;
u32;
{
/// Add immediate
Addi = 0b000,
/// Shift left immediate
Sli = 0b001,
/// Set less than immediate
Slti = 0b010,
/// Set less than immediate unsigned
Sltiu = 0b011,
/// Xor immediate
Xori = 0b100,
/// Shift right immediate
Sri = 0b101,
/// Or immediate
Ori = 0b110,
/// And immediate
Andi = 0b111,
};
Invalid
}
emu_enum! {
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32OpImmFunct7;
u32;
{
/// Shift right logical immediate
Srli = 0b0000000,
/// Shift right arithmetic immediate
Srai = 0b0100000,
// Bitmanip instructions
Bitmanip = 0b011_0000,
// OR-Combine byte granule
Orc = 0b001_0100,
// Bit clear
Bclr = 0b010_0100,
// Byte reverse
Rev8 = 0b011_0100,
};
Invalid
}
impl RvInstr32OpImmFunct7 {
/// Shift Left Logical function
#[allow(non_upper_case_globals)]
pub const Slli: RvInstr32OpImmFunct7 = RvInstr32OpImmFunct7::Srli;
}
emu_enum! {
/// RISCV Store Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32StoreFunct3;
u32;
{
/// Store Byte function
Sb = 0b000,
/// Store Half Word function
Sh = 0b001,
/// Store Word function
Sw = 0b010,
};
Invalid
}
emu_enum! {
/// RISCV Store Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32OpFunct3;
u32;
{
/// Function Zero
Zero = 0b000,
/// Function One
One = 0b001,
/// Function Two
Two = 0b010,
/// Function Three
Three = 0b011,
/// Function Four
Four = 0b100,
/// Function Five
Five = 0b101,
/// Function Six
Six = 0b110,
/// Function Seven
Seven = 0b111,
};
Invalid
}
emu_enum! {
/// RISCV Branch Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32BranchFunct3;
u32;
{
/// Branch on equal function
Beq = 0b000,
/// Branch on not equal function
Bne = 0b001,
/// Branch on less than
Blt = 0b100,
/// Branch on greater than equal
Bge = 0b101,
/// Branch on less than unsigned
Bltu = 0b110,
/// Branch on greater than equal unsigned
Bgeu = 0b111,
};
Invalid
}
emu_enum! {
/// RISCV System Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32SystemFunct3;
u32;
{
/// Private functions
Priv = 0b000,
/// CSR Read Write
Csrrw = 0b001,
/// CSR Read and Set bits
Csrrs = 0b010,
/// CSR Read and Clear bits
Csrrc = 0b011,
/// CSR Read Write Immediate
Csrrwi = 0b101,
/// CSR Read and Set bits Immediate
Csrrsi = 0b110,
/// CSR Read and Clear bits Immediate
Csrrci = 0b111,
};
Invalid
}
emu_enum! {
/// RISCV Fence Opcode Functions
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32FenceFunct3;
u32;
{
/// FENCE
Fence = 0b000,
/// FENCE.I
FenceI = 0b001,
};
Invalid
}
emu_enum! {
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32OpFunct10;
u32;
{
// Format is YYY_YYYY_XXX, where 'YYY_YYYY' is func7 and XXX is func3
Add = 0b000_0000_000,
Sll = 0b000_0000_001,
Slt = 0b000_0000_010,
Sltu = 0b000_0000_011,
Xor = 0b000_0000_100,
Srl = 0b000_0000_101,
Or = 0b000_0000_110,
And = 0b000_0000_111,
Mul = 0b000_0001_000,
Mulh = 0b000_0001_001,
Mulhsu = 0b000_0001_010,
Mulhu = 0b000_0001_011,
Div = 0b000_0001_100,
Divu = 0b000_0001_101,
Rem = 0b000_0001_110,
Remu = 0b000_0001_111,
Sub = 0b010_0000_000,
Sra = 0b010_0000_101,
};
Invalid
}
emu_enum! {
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32OpFunct7;
u32;
{
/// Add function
Add = 0b000_0000,
/// Multiply function
Mul = 0b000_0001,
/// Sub function
Sub = 0b010_0000,
/// Min, Max, or Clmul
MinMaxClmul = 0b000_0101,
/// Zero-extend
Zext = 0b000_0100,
/// Rotate
Rotate = 0b011_0000,
/// Shift 1 and add
Sh1add = 0b001_0000,
/// Bit set
Bset = 0b001_0100,
/// Bit clear
Bclr = 0b010_0100,
/// Bit invert
Binv = 0b011_0100,
};
Invalid
}
#[allow(non_upper_case_globals)]
impl RvInstr32OpFunct7 {
/// Shift Left Logical function
pub const Sll: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Set Less Than
pub const Slt: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Set Less Than Unsigned
pub const Sltu: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Xor
pub const Xor: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Shift Right Logical function
pub const Srl: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Shift Right Arithmetic function
pub const Sra: RvInstr32OpFunct7 = RvInstr32OpFunct7::Sub;
/// Or function
pub const Or: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// And function
pub const And: RvInstr32OpFunct7 = RvInstr32OpFunct7::Add;
/// Multiply High function
pub const Mulh: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Multiply High signed and unsigned function
pub const Mulhsu: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Multiply High unsigned function
pub const Mulhu: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Divide function
pub const Div: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Divide Unsigned function
pub const Divu: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Remainder function
pub const Rem: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// Remainder Unsigned function
pub const Remu: RvInstr32OpFunct7 = RvInstr32OpFunct7::Mul;
/// AND with inverted operand
pub const Andn: RvInstr32OpFunct7 = RvInstr32OpFunct7::Sub;
/// OR with inverted operand
pub const Orn: RvInstr32OpFunct7 = RvInstr32OpFunct7::Sub;
/// XNOR with inverted operand
pub const Xnor: RvInstr32OpFunct7 = RvInstr32OpFunct7::Sub;
// Bit manipulation extension
/// Shift 1 and adds
pub const Sh1add: RvInstr32OpFunct7 = RvInstr32OpFunct7::Sh1add;
}
emu_enum! {
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvInstr32SystemImm;
u32;
{
/// Environment call
Ecall = 0b0000_0000_0000,
/// Break
Ebreak = 0b0000_0000_0001,
/// Mret
Mret = 0b0011_0000_0010,
/// Wfi
Wfi = 0b0001_0000_0101,
};
Invalid
}
bitfield! {
/// RISCV 32-bit instruction
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct RvInstr32(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit I-Type instruction
pub struct RvInstr32I(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Destination Register
pub from into XReg, rd, set_rd: 11, 7;
/// Opcode function
pub from into u32, funct3, set_funct3: 14, 12;
/// Source Register
pub from into XReg, rs, set_rs: 19, 15;
/// Shift Amount
pub u32, shamt, set_shamt: 24, 20;
/// Opcode function
pub u32, funct7, set_funct7: 31, 25;
pub u32, funct5, set_funct5: 24, 20;
/// Immediate value
pub i32, imm, set_imm: 31, 20;
/// Immediate value
pub u32, uimm, set_uimm: 31, 20;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit U-Type instruction
pub struct RvInstr32U(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Destination Register
pub from into XReg, rd, set_rd: 11, 7;
/// Immediate value
pub i32, imm, set_imm: 31, 12;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit S-Type instruction
pub struct RvInstr32S(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Immediate value
pub u32, imm11_7, set_imm11_7: 11, 7;
/// Opcode function
pub from into u32, funct3, set_funct3: 14, 12;
/// Source Register 1
pub from into XReg, rs1, set_rs1: 19, 15;
/// Source Register 2
pub from into XReg, rs2, set_rs2: 24, 20;
/// Immediate value
pub i32, imm31_25, set_imm31_25: 31, 25;
}
impl RvInstr32S {
pub fn imm(&self) -> i32 {
(self.imm31_25() << 5) | (self.imm11_7() as i32)
}
#[allow(dead_code)]
pub fn set_imm(&mut self, imm: i32) {
let imm = imm as u32;
self.set_imm11_7(imm.bit_range(4, 0));
self.set_imm31_25(imm.bit_range(11, 5));
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit R-Type instruction
pub struct RvInstr32R(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Destination Register
pub from into XReg, rd, set_rd: 11, 7;
/// Opcode function
pub from into u32, funct3, set_funct3: 14, 12;
/// Source Register 1
pub from into XReg, rs1, set_rs1: 19, 15;
/// Source Register 2
pub from into XReg, rs2, set_rs2: 24, 20;
/// Opcode function
pub from into u32, funct7, set_funct7: 31, 25;
}
impl RvInstr32R {
pub fn set_funct10(&mut self, val: RvInstr32OpFunct10) {
self.set_funct3(u32::from(val) & 0b000_0000_111);
self.set_funct7((u32::from(val) & 0b111_1111_000) >> 3);
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit B-Type instruction
pub struct RvInstr32B(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Immediate
pub from into u32, imm7, set_imm7: 7, 7;
/// Immediate
pub from into u32, imm11_8, set_imm11_8: 11, 8;
/// Opcode function
pub from into u32, funct3, set_funct3: 14, 12;
/// Source Register 1
pub from into XReg, rs1, set_rs1: 19, 15;
/// Source Register 2
pub from into XReg, rs2, set_rs2: 24, 20;
/// Immediate
pub from into u32, imm30_25, set_imm30_25: 30, 25;
/// Immediate
pub i32, imm31, set_imm31: 31, 31;
}
impl RvInstr32B {
pub fn imm(&self) -> u32 {
let mut imm = 0u32;
imm.set_bit_range(31, 12, self.imm31());
imm.set_bit_range(11, 11, self.imm7());
imm.set_bit_range(10, 5, self.imm30_25());
imm.set_bit_range(4, 1, self.imm11_8());
imm.set_bit_range(0, 0, 0);
imm
}
#[allow(dead_code)]
pub fn set_imm(&mut self, imm: u32) {
self.set_imm7(imm.bit_range(11, 11));
self.set_imm11_8(imm.bit_range(4, 1));
self.set_imm30_25(imm.bit_range(10, 5));
self.set_imm31(imm.bit_range(12, 12));
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV 32-bit J-Type instruction
pub struct RvInstr32J(u32);
/// Opcode
pub from into RvInstr32Opcode, opcode, set_opcode: 6, 0;
/// Destination Register
pub from into XReg, rd, set_rd: 11, 7;
/// Immediate value
pub u32, imm19_12, set_imm19_12: 19, 12;
/// Immediate value
pub u32, imm20, set_imm20_20: 20, 20;
/// Immediate value
pub u32, imm30_21, set_imm30_21: 30, 21;
/// Immediate
pub i32, imm31, set_imm31: 31, 31;
}
impl RvInstr32J {
pub fn imm(&self) -> u32 {
let mut imm = 0u32;
imm.set_bit_range(31, 20, self.imm31());
imm.set_bit_range(19, 12, self.imm19_12());
imm.set_bit_range(11, 11, self.imm20());
imm.set_bit_range(10, 1, self.imm30_21());
imm
}
#[allow(dead_code)]
pub fn set_imm(&mut self, imm: u32) {
self.set_imm31(imm.bit_range(20, 20));
self.set_imm30_21(imm.bit_range(10, 1));
self.set_imm20_20(imm.bit_range(11, 11));
self.set_imm19_12(imm.bit_range(19, 12));
}
}
/// RISCV Instruction
pub enum RvInstr {
// 32-bit Instruction
Instr32(u32),
// 16-bit Instruction
Instr16(u16),
}
emu_enum! {
/// Privilege modes
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvPrivMode;
u32;
{
/// User mode
U = 0b00,
/// Machine mode
M = 0b11,
};
Invalid
}
emu_enum! {
/// Memory access types
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvMemAccessType;
u8;
{
/// Read access
Read = 0b001,
/// Write access
Write = 0b010,
/// Execute access
Execute = 0b100,
};
Invalid
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV Machine Mode Status Register
pub struct RvMStatus(u32);
/// Machine Mode Interrupt Enable
pub u32, mie, set_mie: 3, 3;
/// Machine Mode Previous Interrupt Enable
pub u32, mpie, set_mpie: 7, 7;
/// Machine Prior Privilege mode
pub from into RvPrivMode, mpp, set_mpp: 12, 11;
/// Modify Privilege level
pub u32, mprv, set_mprv: 17, 17;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV Machine Mde Interrupt Enable
pub struct RvMIE(u32);
/// Machine External Interrupt Enable
pub u32, meie, set_meie: 11, 11;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// External Interrupt Handler Address Pointer Register
pub struct RvMEIHAP(u32);
/// Machine External Interrupt Enable
pub u32, base, set_base: 31, 10;
/// External interrupt source ID of highest-priority pending interrupt
pub u32, claimid, set_claimid: 9, 2;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// Power management control Register
pub struct RvMPMC(u32);
/// Initiate core halt
pub u32, halt, _: 0, 0;
/// Control interrupt enable
pub u32, haltie, _: 1, 1;
}
emu_enum! {
/// PMP address modes
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvPmpAddrMode;
u8;
{
/// PMP entry disabled
Off = 0b00,
/// Top of range
Tor = 0b01,
/// Naturally aligned 4-byte region
Na4 = 0b10,
/// Naturally-aligned power of 2
Napot = 0b11,
};
Invalid
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// PMP control register
pub struct RvPmpiCfg(u8);
u8;
/// Read bit
pub read, set_read: 0, 0;
/// Write bit
pub write, set_write: 1, 1;
/// Execute bit
pub execute, set_execute: 2, 2;
/// Address mode
pub from into RvPmpAddrMode, addr_mode, set_addr_mode: 4, 3;
/// Lock bit
pub lock, set_lock: 7, 7;
}
impl From<u8> for RvPmpiCfg {
fn from(i: u8) -> RvPmpiCfg {
RvPmpiCfg(i)
}
}
impl From<RvPmpiCfg> for u8 {
fn from(i: RvPmpiCfg) -> u8 {
i.0
}
}
bitfield! {
/// PMP packed control register
pub struct RvPmpCfgi(u32);
u8;
/// Packed register 1
pub from into RvPmpiCfg, r1, set_r1: 7, 0;
/// Packed register 2
pub from into RvPmpiCfg, r2, set_r2: 15, 8;
/// Packed register 3
pub from into RvPmpiCfg, r3, set_r3: 23, 16;
/// Packed register 4
pub from into RvPmpiCfg, r4, set_r4: 31, 24;
}
bitfield! {
/// Machine security configuration register (low)
pub struct RvMsecCfg(u32);
u8;
/// Machine mode lockdown
pub mml, set_mml: 0, 0;
/// Machine Mode Whitelist Policy
pub mmwp, set_mmwp: 1, 1;
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/csr_file.rs | sw-emulator/lib/cpu/src/csr_file.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
csr_file.rs
Abstract:
File contains implementation of RISC-V Config and status register file
--*/
use std::rc::Rc;
use crate::internal_timers::InternalTimers;
use crate::types::{RvMIE, RvMPMC, RvMStatus, RvPmpAddrMode, RvPmpCfgi, RvPmpiCfg, RvPrivMode};
use crate::Pic;
use caliptra_emu_bus::{Clock, Timer, TimerAction};
use caliptra_emu_types::{RvAddr, RvData, RvException};
/// Configuration & Status Register
#[derive(Copy, Clone, Default)]
pub struct Csr {
pub val: RvData,
default_val: RvData,
pub mask: u32,
}
pub enum MipBits {
Mitip0 = 29,
Mitip1 = 28,
//bit 7 marks the machine timer interrupt as pending.
Mtip = 7,
}
impl Csr {
/// ISA CSR
pub const MISA: RvAddr = 0x301;
/// Vendor ID CSR
pub const MVENDORID: RvAddr = 0xF11;
/// Architecture ID CSR
pub const MARCHID: RvAddr = 0xF12;
/// Implementation ID CSR
pub const MIMPIID: RvAddr = 0xF13;
/// HART ID CSR
pub const MHARTID: RvAddr = 0xF14;
/// HART Status CSR
pub const MSTATUS: RvAddr = 0x300;
/// Interrupt Enable CSR
pub const MIE: RvAddr = 0x304;
/// Interrupt Vector Table Address CSR
pub const MTVEC: RvAddr = 0x305;
/// Performance Counter Inhibit register CSR
pub const MCOUNTINHIBIT: RvAddr = 0x320;
/// Scratch Register CSR
pub const MSCRATCH: RvAddr = 0x340;
/// Exception Program Counter CSR
pub const MEPC: RvAddr = 0x341;
/// Exception Cause CSR
pub const MCAUSE: RvAddr = 0x342;
/// Exception Value CSR
pub const MTVAL: RvAddr = 0x343;
/// Interrupt Pending CSR
pub const MIP: RvAddr = 0x344;
/// Power management const CSR
pub const MPMC: RvAddr = 0x7C6;
/// Machine security configuration CSR
pub const MSECCFG: RvAddr = 0x747;
/// Cycle Low Counter CSR
pub const MCYCLE: RvAddr = 0xB00;
/// Instruction Retired Low Counter CSR
pub const MINSTRET: RvAddr = 0xB02;
/// Cycle High Counter CSR
pub const MCYCLEH: RvAddr = 0xB80;
/// Instruction Retired High Counter CSR
pub const MINSTRETH: RvAddr = 0xB82;
/// External Interrupt Vector Table CSR
pub const MEIVT: RvAddr = 0xBC8;
/// External Interrupt Handler Address Pointer CSR
pub const MEIHAP: RvAddr = 0xFC8;
/// Internal Timer Counter 0
pub const MITCNT0: RvAddr = 0x7D2;
/// Internal Timer Counter 1
pub const MITCNT1: RvAddr = 0x7D5;
/// Internal Timer Bound 0
pub const MITB0: RvAddr = 0x7D3;
/// Internal Timer Bound 1
pub const MITB1: RvAddr = 0x7D6;
/// Internal Timer Control 0
pub const MITCTL0: RvAddr = 0x7D4;
/// Internal Timer Control 0
pub const MITCTL1: RvAddr = 0x7D5;
/// PMP configuration register range start, inclusive
pub const PMPCFG_START: RvAddr = 0x3A0;
/// PMP configuration register range end, inclusive
pub const PMPCFG_END: RvAddr = 0x3AF;
/// PMP address register range start, inclusive
pub const PMPADDR_START: RvAddr = 0x3B0;
/// PMP address register range end, inclusive
pub const PMPADDR_END: RvAddr = 0x3EF;
/// Number of PMP address/cfg registers
pub const PMPCOUNT: usize = 64;
/// Create a new Configurations and Status register
///
/// # Arguments
///
/// * `default_val` - Reset value
/// * `mask` - Write Mask
pub fn new(default_val: RvData, mask: RvData) -> Self {
Self {
val: default_val,
default_val,
mask,
}
}
pub fn reset(&mut self) -> &Self {
self.val = self.default_val;
self
}
}
type CsrReadFn = fn(&CsrFile, RvPrivMode, RvAddr) -> Result<RvData, RvException>;
type CsrWriteFn = fn(&mut CsrFile, RvPrivMode, RvAddr, RvData) -> Result<(), RvException>;
/// CSR read/write functions
#[derive(Copy, Clone)]
struct CsrFn {
/// CSR read function
read_fn: CsrReadFn,
/// CSR write function
write_fn: CsrWriteFn,
}
impl CsrFn {
/// Perform a CSR read
///
/// # Arguments
/// * `csr_file` - CSR file
/// * `priv_mode` - Effective privilege mode
/// * `addr` - CSR address to read from
///
/// # Return
///
/// * `RvData` - Register value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn read(
&self,
csr_file: &CsrFile,
priv_mode: RvPrivMode,
addr: RvAddr,
) -> Result<RvData, RvException> {
(self.read_fn)(csr_file, priv_mode, addr)
}
/// Perform a CSR write
///
/// # Arguments
/// * `csr_file` - CSR file
/// * `priv_mode` - Effective privilege mode
/// * `addr` - CSR address to write to
/// * `val` - Data to write
///
/// # Return
///
/// * `RvData` - Register value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write(
&self,
csr_file: &mut CsrFile,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
(self.write_fn)(csr_file, priv_mode, addr, val)
}
}
/// Configuration and status register file
pub struct CsrFile {
/// CSRS
csrs: Box<[Csr; CsrFile::CSR_COUNT]>,
/// Timer
timer: Timer,
/// Maximum set PMPCFGi register
max_pmpcfgi: Option<usize>,
/// Internal Timers
pub(crate) internal_timers: InternalTimers,
/// Reference to PIC
pic: Rc<Pic>,
}
/// Initalise a CSR read/write function in the CSR table
macro_rules! csr_fn {
($csrs:ident, $index:expr, $read_fn:path, $write_fn:path) => {
// Because this is used in a constant expression, and write_fn is considered mutable,
// a constructor can't be const. Therefore, we do it manually.
$csrs[($index) as usize] = CsrFn {
read_fn: $read_fn,
write_fn: $write_fn,
};
};
}
/// Initialise the read/write functions of a block of CSRs in the CSR table
macro_rules! csr_fn_block {
($csrs:ident, $start:path, $end:path, $read_fn:path, $write_fn:path) => {
let mut i = $start;
// For loops aren't allowed in constant expressions; but loops are.
loop {
if i > $end {
break;
}
csr_fn!($csrs, i, $read_fn, $write_fn);
i += 1;
}
};
}
/// Initalise the default value and mask of a CSR
macro_rules! csr_val {
($csrs:ident, $index:expr, $default_val:literal, $mask:literal) => {
$csrs[($index) as usize] = Csr::new($default_val, $mask);
};
}
/// Initalise the default value and mask of a block of CSRs
macro_rules! csr_val_block {
($csrs:ident, $start:path, $end:path, $default_val:literal, $mask:literal) => {
for i in ($start..=$end) {
csr_val!($csrs, i, $default_val, $mask);
}
};
}
impl CsrFile {
/// Supported CSR Count
const CSR_COUNT: usize = 4096;
/// CSR function table
const CSR_FN: [CsrFn; CsrFile::CSR_COUNT] = {
let default = CsrFn {
read_fn: CsrFile::system_read,
write_fn: CsrFile::system_write,
};
let mut table = [default; CsrFile::CSR_COUNT];
csr_fn!(
table,
Csr::MSTATUS,
CsrFile::system_read,
CsrFile::mstatus_write
);
csr_fn!(table, Csr::MIP, CsrFile::mip_read, CsrFile::mip_write);
csr_fn!(table, Csr::MIE, CsrFile::system_read, CsrFile::mie_write);
csr_fn!(table, Csr::MPMC, CsrFile::system_read, CsrFile::mpmc_write);
csr_fn!(
table,
Csr::MSECCFG,
CsrFile::system_read,
CsrFile::mseccfg_write
);
csr_fn!(
table,
Csr::MEIVT,
CsrFile::system_read,
CsrFile::meivt_write
);
csr_fn_block!(
table,
Csr::PMPCFG_START,
Csr::PMPCFG_END,
CsrFile::system_read,
CsrFile::pmpcfg_write
);
csr_fn_block!(
table,
Csr::PMPADDR_START,
Csr::PMPADDR_END,
CsrFile::system_read,
CsrFile::pmpaddr_write
);
// internal timer registers
csr_fn!(
table,
Csr::MITCNT0,
CsrFile::mitcnt_read,
CsrFile::mitcnt_write
);
csr_fn!(
table,
Csr::MITCNT1,
CsrFile::mitcnt_read,
CsrFile::mitcnt_write
);
csr_fn!(table, Csr::MITB0, CsrFile::mitb_read, CsrFile::mitb_write);
csr_fn!(table, Csr::MITB1, CsrFile::mitb_read, CsrFile::mitb_write);
csr_fn!(
table,
Csr::MITCTL0,
CsrFile::mitctl_read,
CsrFile::mitctl_write
);
csr_fn!(
table,
Csr::MITCTL1,
CsrFile::mitctl_read,
CsrFile::mitctl_write
);
csr_fn!(
table,
Csr::MEIHAP,
CsrFile::meihap_read,
CsrFile::system_write
);
csr_fn!(
table,
Csr::MCYCLE,
CsrFile::mcycle_read,
CsrFile::mcycle_write
);
csr_fn!(
table,
Csr::MCYCLEH,
CsrFile::mcycleh_read,
CsrFile::mcycleh_write
);
table
};
/// Create a new Configuration and status register file
pub fn new(clock: Rc<Clock>, pic: Rc<Pic>) -> Self {
let mut csrs = Box::new([Csr::default(); CsrFile::CSR_COUNT]);
csr_val!(csrs, Csr::MISA, 0x4010_1104, 0x0000_0000);
csr_val!(csrs, Csr::MVENDORID, 0x0000_0045, 0x0000_0000);
csr_val!(csrs, Csr::MARCHID, 0x0000_0010, 0x0000_0000);
csr_val!(csrs, Csr::MIMPIID, 0x0000_0004, 0x0000_0000);
csr_val!(csrs, Csr::MHARTID, 0x0000_0000, 0x0000_0000);
csr_val!(csrs, Csr::MSTATUS, 0x1800_1800, 0x0002_1888);
csr_val!(csrs, Csr::MIE, 0x0000_0000, 0x7000_0888);
csr_val!(csrs, Csr::MTVEC, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MCOUNTINHIBIT, 0x0000_0000, 0x0000_007D);
csr_val!(csrs, Csr::MSCRATCH, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MEPC, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MCAUSE, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MTVAL, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MIP, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MPMC, 0x0000_0002, 0x0000_0002);
csr_val!(csrs, Csr::MSECCFG, 0x0000_0000, 0x0000_0003);
csr_val!(csrs, Csr::MCYCLE, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MCYCLEH, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MINSTRET, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MINSTRETH, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MEIVT, 0x0000_0000, 0xFFFF_FC00);
csr_val_block!(
csrs,
Csr::PMPCFG_START,
Csr::PMPCFG_END,
0x0000_0000,
0x9F9F_9F9F
);
csr_val_block!(
csrs,
Csr::PMPADDR_START,
Csr::PMPADDR_END,
0x0000_0000,
0x3FFF_FFFF
);
csr_val!(csrs, Csr::MITCNT0, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MITCNT1, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MITB0, 0xFFFF_FFFF, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MITB1, 0xFFFF_FFFF, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MITCTL0, 0x0000_0001, 0x0000_000F);
csr_val!(csrs, Csr::MITCTL1, 0x0000_0001, 0x0000_000F);
csr_val!(csrs, Csr::MCYCLE, 0x0000_0000, 0xFFFF_FFFF);
csr_val!(csrs, Csr::MCYCLEH, 0x0000_0000, 0xFFFF_FFFF);
Self {
csrs,
timer: Timer::new(&clock),
max_pmpcfgi: None,
internal_timers: crate::internal_timers::InternalTimers::new(clock.clone()),
pic,
}
}
/// Reset the CSR file
pub fn reset(&mut self) {
for csr in self.csrs.iter_mut() {
csr.reset();
}
self.max_pmpcfgi = None;
}
/// Allow all reads from the given CSR
fn any_read(&self, _: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
Ok(self.csrs[addr as usize].val)
}
/// Allow all writes to the given CSR, taking into account the mask
fn any_write(&mut self, _: RvPrivMode, addr: RvAddr, val: RvData) -> Result<(), RvException> {
let csr = &mut self.csrs[addr as usize];
csr.val = (csr.val & !csr.mask) | (val & csr.mask);
Ok(())
}
/// Allow only system reads from the given CSR
fn system_read(&self, priv_mode: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode == RvPrivMode::U {
return Err(RvException::illegal_register());
}
self.any_read(priv_mode, addr)
}
/// Allow only system writes to the given CSR
fn system_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mode == RvPrivMode::U {
return Err(RvException::illegal_register());
}
self.any_write(priv_mode, addr, val)
}
fn meihap_read(&self, priv_mode: RvPrivMode, _: RvAddr) -> Result<RvData, RvException> {
if priv_mode == RvPrivMode::U {
return Err(RvException::illegal_register());
}
self.system_read(RvPrivMode::M, Csr::MEIVT)
.map(|v| v + ((self.pic.highest_priority_irq_total().unwrap_or(0) as u32) << 2))
}
/// Perform a write to the MEIVT CSR
fn meivt_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
//println!("Setting MEIVT to {:x}", val);
self.system_write(priv_mode, addr, val)?;
let csr = self.csrs[addr as usize];
self.timer
.schedule_action_in(0, TimerAction::SetExtIntVec { addr: csr.val });
Ok(())
}
/// Perform a write to the MSTATUS CSR
fn mstatus_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
// Write new mstatus value
let csr = self.csrs[addr as usize];
let mstatus_old = RvMStatus(csr.val);
let mut mstatus_new = RvMStatus(val);
if mstatus_new.mpp() == RvPrivMode::Invalid {
// Ignore invalid write
mstatus_new.set_mpp(mstatus_old.mpp());
}
self.system_write(priv_mode, addr, mstatus_new.0)?;
// Read back mstatus register after masking
let csr = self.csrs[addr as usize];
let mstatus_new = RvMStatus(csr.val);
self.timer.schedule_action_in(
0,
TimerAction::SetGlobalIntEn {
en: mstatus_new.mie() == 1,
},
);
// Let's see if the soc wants to interrupt
self.timer.schedule_poll_in(2);
Ok(())
}
/// Perform a read of the MIP CSR.
fn mip_read(&self, priv_mode: RvPrivMode, _: RvAddr) -> Result<RvData, RvException> {
if priv_mode == RvPrivMode::U {
return Err(RvException::illegal_register());
}
let mie = self.system_read(priv_mode, Csr::MIE)?;
let (pending0, pending1) = self.internal_timers.interrupts_pending();
let mitip0: RvData = if pending0 {
1 << (MipBits::Mitip0 as u32)
} else {
0
};
let mitip1: RvData = if pending1 {
1 << (MipBits::Mitip1 as u32)
} else {
0
};
// MTIP pending comes from MIP’s bit 7, which set_mtip() toggles.
let mtip_pending: RvData = self.csrs[Csr::MIP as usize].val & (1 << (MipBits::Mtip as u32));
// Keep your current behavior of masking pending by MIE.
let masked_internal = mie & (mitip0 | mitip1);
let masked_mtip = (mie & (1 << (MipBits::Mtip as u32))) & mtip_pending;
Ok(masked_internal | masked_mtip)
}
/// Perform a (no-op) write to the MIP CSR.
fn mip_write(
&mut self,
priv_mode: RvPrivMode,
_: RvAddr,
_: RvData,
) -> Result<(), RvException> {
if priv_mode == RvPrivMode::U {
return Err(RvException::illegal_register());
}
// do nothing as this is a read-only register
Ok(())
}
/// Perform a write to the MIE CSR
fn mie_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
self.system_write(priv_mode, addr, val)?;
let csr = self.csrs[addr as usize];
let mie = RvMIE(csr.val);
self.timer.schedule_action_in(
0,
TimerAction::SetExtIntEn {
en: mie.meie() == 1,
},
);
// Let's see if the soc wants to interrupt
self.timer.schedule_poll_in(2);
Ok(())
}
/// Perform a write to the MPMC CSR
fn mpmc_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
self.system_write(priv_mode, addr, val)?;
let csr = self.csrs[addr as usize];
let mpmc_write = RvMPMC(val);
if mpmc_write.halt() == 1 {
let mpcm = RvMPMC(csr.val);
if mpcm.haltie() == 1 {
let mut mstatus = RvMStatus(self.read(priv_mode, Csr::MSTATUS)?);
mstatus.set_mie(1);
self.write(priv_mode, Csr::MSTATUS, mstatus.0)?;
}
self.timer.schedule_action_in(0, TimerAction::Halt);
}
Ok(())
}
/// Perform a write to the MSECCFG register
fn mseccfg_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
let csr = self.csrs[addr as usize];
// All current bits are sticky
let val = val | csr.val;
self.any_write(priv_mode, addr, val)
}
/// Perform a write to a PMPCFG CSR
fn pmpcfg_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
// Locate the specific packed PMP config register
let mut pmpcfgi = RvPmpCfgi(self.read(priv_mode, addr)?);
// None: no change
// Some(true): is set
// Some(false): is unset
let mut is_set: Option<bool> = None;
// Do not write if the entry is locked
if pmpcfgi.r1().lock() == 0 {
let val = (val & 0xFF) as u8;
is_set = Some(val > 0);
pmpcfgi.set_r1(RvPmpiCfg(val));
}
if pmpcfgi.r2().lock() == 0 {
let val = ((val >> 8) & 0xFF) as u8;
if is_set.is_none() || is_set == Some(false) {
is_set = Some(val > 0);
}
pmpcfgi.set_r2(RvPmpiCfg(val));
}
if pmpcfgi.r3().lock() == 0 {
let val = ((val >> 16) & 0xFF) as u8;
if is_set.is_none() || is_set == Some(false) {
is_set = Some(val > 0);
}
pmpcfgi.set_r3(RvPmpiCfg(val));
}
if pmpcfgi.r4().lock() == 0 {
let val = ((val >> 24) & 0xFF) as u8;
if is_set.is_none() || is_set == Some(false) {
is_set = Some(val > 0);
}
pmpcfgi.set_r4(RvPmpiCfg(val));
}
let index = (addr - Csr::PMPCFG_START) as usize;
match is_set {
Some(true) => {
// New highest index?
if self.max_pmpcfgi.is_none() || self.max_pmpcfgi < Some(index) {
self.max_pmpcfgi = Some(index);
}
}
Some(false) => {
// Was this the highest index?
if self.max_pmpcfgi == Some(index) {
// Find new highest index, or fall back to None
self.max_pmpcfgi = None;
for i in (0..index).rev() {
if self.any_read(RvPrivMode::M, Csr::PMPCFG_START + i as RvAddr)? > 0 {
self.max_pmpcfgi = Some(i);
break;
}
}
}
}
_ => return Ok(()),
}
self.any_write(priv_mode, addr, pmpcfgi.0)
}
/// Perform a write to a PMPADDR register
fn pmpaddr_write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
// Find corresponding pmpcfg register
let index: usize = (addr - Csr::PMPADDR_START) as usize;
let mut pmpicfg = self.read_pmpicfg(index)?;
if pmpicfg.lock() != 0 {
// Ignore the write
return Ok(());
}
// If pmpicfg is TOR, writes to pmpaddri-1 are ignored
// Therefore, check pmpi+1cfg, which corresponds to pmpaddri
if index < (Csr::PMPCOUNT - 1) {
pmpicfg = self.read_pmpicfg(index + 1)?;
if pmpicfg.addr_mode() == RvPmpAddrMode::Tor && pmpicfg.lock() != 0 {
// Ignore the write
return Ok(());
}
}
self.any_write(priv_mode, addr, val)
}
/// Read the specified PMPiCFG status register
///
/// # Arguments
///
/// * `reg` - PMP configuration register to read
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
fn read_pmpicfg(&self, reg: usize) -> Result<RvPmpiCfg, RvException> {
// Find corresponding pmpcfg register
let pmpcfgi_index = (reg / 4) as RvAddr + Csr::PMPCFG_START;
let pmpcfg_offset = reg % 4;
let pmpcfgi = RvPmpCfgi(self.any_read(RvPrivMode::M, pmpcfgi_index)?);
let result = match pmpcfg_offset {
0 => pmpcfgi.r1(),
1 => pmpcfgi.r2(),
2 => pmpcfgi.r3(),
3 => pmpcfgi.r4(),
_ => unreachable!(),
};
Ok(result)
}
/// Check if an address matches against one PMP register.
/// Return the first configuration register that does, or None.
///
/// This function performs no other checks.
///
/// # Arguments
///
/// * `pmpicfg` - PMPiCFG register to check
/// * `index` - index of PMPADDR register to check
/// * `addr` - Address to check
///
/// # Return
///
/// * `true` if PMP entry matches, otherwise `false`
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
fn pmp_match_one_addr(
&self,
pmpicfg: RvPmpiCfg,
index: usize,
addr: RvAddr,
) -> Result<bool, RvException> {
let addr_mode = pmpicfg.addr_mode();
if addr_mode == RvPmpAddrMode::Off {
// No need for additional checks
return Ok(false);
}
let addr = addr as u64;
let pmpaddr = self.any_read(RvPrivMode::M, Csr::PMPADDR_START + index as RvAddr)?;
let pmpaddr_shift = (pmpaddr as u64) << 2;
let addr_top;
let addr_bottom;
match addr_mode {
RvPmpAddrMode::Tor => {
// Bottom address is 0 if this register is 0
// otherwise it's the previous one
addr_top = pmpaddr_shift;
addr_bottom = if index > 0 {
(self.any_read(RvPrivMode::M, Csr::PMPADDR_START + (index - 1) as RvAddr)?
as u64)
<< 2
} else {
0
};
}
RvPmpAddrMode::Na4 => {
// Four-byte range
addr_top = pmpaddr_shift + 4;
addr_bottom = pmpaddr_shift;
}
RvPmpAddrMode::Napot => {
let (bot, top) = decode_napot_pmpaddr(pmpaddr);
addr_bottom = bot;
addr_top = top;
}
_ => unreachable!(),
}
Ok(addr >= addr_bottom && addr < addr_top)
}
/// Check if an address matches against the PMP registers.
/// Return the first configuration register that does, or None.
///
/// This function performs no other checks.
///
/// # Arguments
///
/// * `addr` - Address to check
///
/// # Return
///
/// * `RvPmpCfg` - Configuration value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn pmp_match_addr(&self, addr: RvAddr) -> Result<Option<RvPmpiCfg>, RvException> {
let max_pmpcfgi = match self.max_pmpcfgi {
// Optimisation: ignore PMP if no registers are set
None => return Ok(None),
Some(val) => val,
};
for i in 0..=max_pmpcfgi {
let pmpcfgi = RvPmpCfgi(self.any_read(RvPrivMode::M, Csr::PMPCFG_START + i as RvAddr)?);
let pmpicfg_1 = pmpcfgi.r1();
let pmpicfg_2 = pmpcfgi.r2();
let pmpicfg_3 = pmpcfgi.r3();
let pmpicfg_4 = pmpcfgi.r4();
// Check packed registers
if self.pmp_match_one_addr(pmpicfg_1, i * 4, addr)? {
return Ok(Some(pmpicfg_1));
} else if self.pmp_match_one_addr(pmpicfg_2, (i * 4) + 1, addr)? {
return Ok(Some(pmpicfg_2));
} else if self.pmp_match_one_addr(pmpicfg_3, (i * 4) + 2, addr)? {
return Ok(Some(pmpicfg_3));
} else if self.pmp_match_one_addr(pmpicfg_4, (i * 4) + 3, addr)? {
return Ok(Some(pmpicfg_4));
}
}
Ok(None)
}
fn mitcnt_read(&self, priv_mode: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITCNT0 => Ok(self.internal_timers.read_mitcnt0()),
Csr::MITCNT1 => Ok(self.internal_timers.read_mitcnt1()),
_ => unreachable!(),
}
}
fn mitcnt_write(
&mut self,
priv_mod: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mod != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITCNT0 => self.internal_timers.write_mitcnt0(val),
Csr::MITCNT1 => self.internal_timers.write_mitcnt1(val),
_ => unreachable!(),
};
Ok(())
}
fn mitb_read(&self, priv_mode: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITB0 => Ok(self.internal_timers.read_mitb0()),
Csr::MITB1 => Ok(self.internal_timers.read_mitb1()),
_ => unreachable!(),
}
}
fn mitb_write(
&mut self,
priv_mod: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mod != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITB0 => self.internal_timers.write_mitb0(val),
Csr::MITB1 => self.internal_timers.write_mitb1(val),
_ => unreachable!(),
};
Ok(())
}
fn mitctl_read(&self, priv_mode: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITCTL0 => Ok(self.internal_timers.read_mitctl0()),
Csr::MITCTL1 => Ok(self.internal_timers.read_mitctl1()),
_ => unreachable!(),
}
}
fn mitctl_write(
&mut self,
priv_mod: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
if priv_mod != RvPrivMode::M {
return Err(RvException::illegal_register());
}
match addr {
Csr::MITCTL0 => self.internal_timers.write_mitctl0(val),
Csr::MITCTL1 => self.internal_timers.write_mitctl1(val),
_ => unreachable!(),
}
Ok(())
}
fn mcycle_read(&self, priv_mode: RvPrivMode, _addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
Ok(self.timer.now() as u32)
}
fn mcycle_write(
&mut self,
_priv_mod: RvPrivMode,
_addr: RvAddr,
_val: RvData,
) -> Result<(), RvException> {
// TODO: this should set the low 32 bits of the cycle counter to this value
Ok(())
}
fn mcycleh_read(&self, priv_mode: RvPrivMode, _addr: RvAddr) -> Result<RvData, RvException> {
if priv_mode != RvPrivMode::M {
return Err(RvException::illegal_register());
}
Ok((self.timer.now() >> 32) as u32)
}
fn mcycleh_write(
&mut self,
_priv_mod: RvPrivMode,
_addr: RvAddr,
_val: RvData,
) -> Result<(), RvException> {
// TODO: this should set the high 32 bits of the cycle counter to this value
Ok(())
}
/// Read the specified configuration status register, taking into account the privilege mode
///
/// # Arguments
///
/// * `priv_mode` - Privilege mode
/// * `csr` - Configuration status register to read
///
/// # Return
///
/// * `RvData` - Register value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister``
pub fn read(&self, priv_mode: RvPrivMode, addr: RvAddr) -> Result<RvData, RvException> {
const CSR_MAX: usize = CsrFile::CSR_COUNT - 1;
if addr as usize > CSR_MAX {
return Err(RvException::illegal_register());
}
Self::CSR_FN[addr as usize].read(self, priv_mode, addr)
}
/// Write the specified Configuration status register, taking into account the privilege mode
///
/// # Arguments
///
/// * `priv_mode` - Privilege mode
/// * `reg` - Configuration status register to write
/// * `val` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write(
&mut self,
priv_mode: RvPrivMode,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
const CSR_MAX: usize = CsrFile::CSR_COUNT - 1;
if addr as usize > CSR_MAX {
return Err(RvException::illegal_register());
}
Self::CSR_FN[addr as usize].write(self, priv_mode, addr, val)
}
pub fn set_mtip(&mut self, asserted: bool) {
let mip = &mut self.csrs[Csr::MIP as usize];
let bit: RvData = 1u32 << (MipBits::Mtip as u32);
if asserted {
mip.val |= bit;
} else {
mip.val &= !bit;
}
// request an immediate poll so the core sees the new pending bit
self.timer.schedule_poll_in(0);
}
}
// Returns the base address (inclusive) and end address (exclusive) of a NAPOT PMP address
fn decode_napot_pmpaddr(addr: u32) -> (u64, u64) {
let bits = addr.trailing_ones();
let addr = addr as u64;
let base = (addr & !((1 << bits) - 1)) << 2;
(base, base + (1 << (bits + 3)))
}
#[cfg(test)]
mod tests {
use super::*;
use std::rc::Rc;
#[test]
fn test_decode_napot_pmpaddr() {
assert_eq!((0x0000_0000, 0x0000_0008), decode_napot_pmpaddr(0x00000000));
assert_eq!((0x0000_0000, 0x0000_0010), decode_napot_pmpaddr(0x00000001));
assert_eq!((0x0040_0000, 0x0040_8000), decode_napot_pmpaddr(0x00100fff));
assert_eq!((0x1000_0000, 0x2000_0000), decode_napot_pmpaddr(0x05ffffff));
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/pic.rs | sw-emulator/lib/cpu/src/pic.rs | // Licensed under the Apache-2.0 license
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use caliptra_emu_bus::{
Bus, BusError, Clock, ReadWriteRegister, ReadWriteRegisterArray, Register, Timer, TimerAction,
};
use caliptra_emu_derive::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use tock_registers::interfaces::Readable;
use tock_registers::register_bitfields;
pub enum IntSource {
DoeErr = 1,
DoeNotif = 2,
EccErr = 3,
EccNotif = 4,
HmacErr = 5,
HmacNotif = 6,
KvErr = 7,
KvNotif = 8,
Sha512Err = 9,
Sha512Notif = 10,
Sha256Err = 11,
Sha256Notif = 12,
QspiErr = 13,
QspiNotif = 14,
UartErr = 15,
UartNotif = 16,
I3cErr = 17,
I3cNotif = 18,
SocIfcErr = 19,
SocIfcNotif = 20,
Sha512AccErr = 21,
Sha512AccNotif = 22,
}
impl From<IntSource> for u8 {
fn from(source: IntSource) -> Self {
source as Self
}
}
const MAX_PRIORITY: u8 = 15;
#[derive(Clone)]
pub struct Pic {
pic: Rc<PicImpl>,
}
impl Pic {
pub fn new() -> Pic {
Pic {
pic: Rc::new(PicImpl::new()),
}
}
pub fn register_irq(&self, id: u8) -> Irq {
Irq {
id,
pic: self.pic.clone(),
}
}
pub fn mmio_regs(&self, clock: Rc<Clock>) -> PicMmioRegisters {
PicMmioRegisters {
pic: self.pic.clone(),
timer: clock.timer(),
}
}
pub fn highest_priority_irq(&self, prithresh: u8) -> Option<u8> {
self.pic.highest_priority_irq(prithresh)
}
pub fn highest_priority_irq_total(&self) -> Option<u8> {
for i in (0..MAX_PRIORITY).rev() {
match self.highest_priority_irq(i) {
Some(irq) => {
return Some(irq);
}
None => continue,
}
}
None
}
}
impl Default for Pic {
fn default() -> Self {
Pic::new()
}
}
fn irq_id_from_addr(addr: u32) -> u8 {
u8::try_from((addr & 0x7f) / 4).unwrap()
}
pub struct PicMmioRegisters {
pic: Rc<PicImpl>,
timer: Timer,
}
impl PicMmioRegisters {
// priority levels
const MEIPL_OFFSET: RvAddr = 0x0000;
const MEIPL_MIN: RvAddr = Self::MEIPL_OFFSET + 4;
const MEIPL_MAX: RvAddr = Self::MEIPL_OFFSET + 255 * 4;
// pending interrupts
#[allow(dead_code)]
const MEIP_OFFSET: RvAddr = 0x1000;
// interrupt enable
const MEIE_OFFSET: RvAddr = 0x2000;
const MEIE_MIN: RvAddr = Self::MEIE_OFFSET + 4;
const MEIE_MAX: RvAddr = Self::MEIE_OFFSET + 255 * 4;
// PIC configuration register
const MPICCFG_OFFSET: RvAddr = 0x3000;
// machine external interrupt gateway configuration/control registers
const MEIGWCTRL_OFFSET: RvAddr = 0x4000;
const MEIGWCTRL_MIN: RvAddr = Self::MEIGWCTRL_OFFSET + 4;
const MEIGWCTRL_MAX: RvAddr = Self::MEIGWCTRL_OFFSET + 255 * 4;
// machine external interrupt gateway clear registers
const MEIGWCLR_OFFSET: RvAddr = 0x5000;
const MEIGWCLR_MIN: RvAddr = Self::MEIGWCLR_OFFSET + 4;
const MEIGWCLR_MAX: RvAddr = Self::MEIGWCLR_OFFSET + 255 * 4;
pub fn register_irq(&self, id: u8) -> Irq {
Irq {
id,
pic: self.pic.clone(),
}
}
}
impl Bus for PicMmioRegisters {
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match addr {
// The first element of each register array is invalid. (S=1..31)
Self::MEIPL_OFFSET
| Self::MEIE_OFFSET
| Self::MEIGWCTRL_OFFSET
| Self::MEIGWCLR_OFFSET => Err(BusError::LoadAccessFault),
Self::MEIGWCLR_MIN..=Self::MEIGWCLR_MAX => Ok(0),
_ => self.pic.regs.borrow_mut().read(size, addr),
}
}
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match addr {
// The first element of each register array is invalid. (S=1..31)
Self::MEIPL_OFFSET
| Self::MEIE_OFFSET
| Self::MEIGWCTRL_OFFSET
| Self::MEIGWCLR_OFFSET => Err(BusError::StoreAccessFault),
Self::MEIGWCTRL_MIN..=Self::MEIGWCTRL_MAX => {
self.pic.regs.borrow_mut().write(size, addr, val)?;
self.pic.refresh_gateway(irq_id_from_addr(addr));
Ok(())
}
// meigwclrS: External Interrupt Gateway Clear Register
Self::MEIGWCLR_MIN..=Self::MEIGWCLR_MAX => {
let id = irq_id_from_addr(addr);
// Any write to this register will clear the pending bit in the gateway
self.pic.gw_pending_ff.set(id, false);
self.pic.refresh_gateway(id);
Ok(())
}
Self::MEIPL_MIN..=Self::MEIPL_MAX | Self::MPICCFG_OFFSET => {
self.pic.regs.borrow_mut().write(size, addr, val)?;
self.pic.refresh_order();
Ok(())
}
Self::MEIE_MIN..=Self::MEIE_MAX => {
let mut regs = self.pic.regs.borrow_mut();
regs.write(size, addr, val)?;
self.pic.refresh_enabled(®s, irq_id_from_addr(addr));
Ok(())
}
_ => {
self.pic.regs.borrow_mut().write(size, addr, val)?;
Ok(())
}
}
}
fn poll(&mut self) {
const EXT_INT_DELAY: u64 = 2;
if let Some(irq) = self.pic.highest_priority_irq(MAX_PRIORITY - 1) {
self.timer.schedule_action_in(
EXT_INT_DELAY,
TimerAction::ExtInt {
irq,
can_wake: true,
},
);
} else if let Some(irq) = self.pic.highest_priority_irq(0) {
self.timer.schedule_action_in(
EXT_INT_DELAY,
TimerAction::ExtInt {
irq,
can_wake: true,
},
);
}
}
}
pub struct Irq {
/// The interrupt source id. A number between 1 and 31.
id: u8,
pic: Rc<PicImpl>,
}
impl Irq {
pub fn id(&self) -> u8 {
self.id
}
/// Set the level of the interrupt line (logic high or low). Whether logic
/// high means interrupt-firing or interrupt-not-firing depends on the
/// meigwctrl register's polarity field.
pub fn set_level(&self, is_high: bool) {
self.pic.irq_set_level(self.id, is_high);
}
}
register_bitfields! [
u32,
Meipl [
PRIORITY OFFSET(0) NUMBITS(4) [],
],
Mpiccfg [
PRIORITY_ORDER OFFSET(0) NUMBITS(1) [
Standard = 0,
Reverse = 1,
],
],
Meie [
INTEN OFFSET(0) NUMBITS(1) [],
],
Meigwctrl [
POLARITY OFFSET(0) NUMBITS(1) [
ActiveHigh = 0,
ActiveLow = 1,
],
TYPE OFFSET(1) NUMBITS(1) [
LevelTriggered = 0,
EdgeTriggered = 1,
],
],
];
#[derive(Bus)]
struct PicImplRegs {
// External interrupt priority level register. Irq id #1 starts at
// meipl[1] (address 0x0004); meipl[0] is reserved.
#[peripheral(offset = 0x0000, len = 0x400)]
meipl: ReadWriteRegisterArray<u32, 256, Meipl::Register>,
// External Interrupt Pending. Irq id #1 starts at meip[1]; meip[0] is
// reserved.
#[register_array(offset = 0x1000, item_size = 4, len = 8)]
meip: [Bits32; 8],
// External Interrupt Enabled. Irq id #1 starts at meie[1] (address 0x2004);
// meie[0] is reserved.
#[peripheral(offset = 0x2000, len = 0x400)]
meie: ReadWriteRegisterArray<u32, 256, Meie::Register>,
#[register(offset = 0x3000)]
mpiccfg: ReadWriteRegister<u32, Mpiccfg::Register>,
// External Interrupt Gateway Configuration. Irq id #1 starts at
// meigwctrl[1] (address 0x4004); meigwctrl[0] is reserved.
#[peripheral(offset = 0x4000, len = 0x400)]
meigwctrl: ReadWriteRegisterArray<u32, 256, Meigwctrl::Register>,
}
impl PicImplRegs {
fn new() -> Self {
Self {
meipl: ReadWriteRegisterArray::new(0x0000_0000),
meip: [
Bits32::new(),
Bits32::new(),
Bits32::new(),
Bits32::new(),
Bits32::new(),
Bits32::new(),
Bits32::new(),
Bits32::new(),
],
meie: ReadWriteRegisterArray::new(0x0000_0000),
mpiccfg: ReadWriteRegister::new(0x0000_0000),
meigwctrl: ReadWriteRegisterArray::new(0x0000_0000),
}
}
}
struct Bits256 {
bits: [Cell<u128>; 2],
}
impl Bits256 {
fn new() -> Self {
Self {
bits: [Cell::new(0), Cell::new(0)],
}
}
fn all_bits_cleared(&self) -> bool {
self.bits[0].get() == 0 && self.bits[1].get() == 0
}
fn first_set_index(&self) -> Option<u8> {
if self.all_bits_cleared() {
None
} else {
let a = self.bits[0].get().trailing_zeros();
let b = self.bits[1].get().trailing_zeros();
if a != 128 {
Some(a as u8)
} else {
Some(128 + b as u8)
}
}
}
fn get(&self, idx: u8) -> bool {
(self.bits[idx as usize / 128].get() & (1 << (idx % 128))) != 0
}
fn set(&self, idx: u8, val: bool) {
let mask = 1 << (idx % 128);
if val {
self.bits[idx as usize / 128].set(self.bits[idx as usize / 128].get() | mask);
} else {
self.bits[idx as usize / 128].set(self.bits[idx as usize / 128].get() & !mask);
}
}
}
struct Bits32 {
bits: Cell<u32>,
}
impl Bits32 {
fn new() -> Self {
Self { bits: Cell::new(0) }
}
fn get(&self, idx: u8) -> bool {
(self.bits.get() & (1 << idx)) != 0
}
fn set(&self, idx: u8, val: bool) {
let mask = 1 << idx;
if val {
self.bits.set(self.bits.get() | mask);
} else {
self.bits.set(self.bits.get() & !mask);
}
}
}
impl Register for Bits32 {
const SIZE: usize = 4;
fn read(&self, _size: RvSize) -> Result<RvData, BusError> {
Ok(self.bits.get())
}
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
if size != RvSize::Word {
return Err(BusError::StoreAccessFault);
}
self.bits.set(val);
Ok(())
}
}
#[derive(Clone, Copy, Default, Eq, Ord, PartialEq, PartialOrd)]
struct IrqPriority {
// The priority, xored such that the highest priority is always 0
priority_xored: u8,
id: u8,
}
struct PicImpl {
regs: RefCell<PicImplRegs>,
// levels.get(2) is true if the most recent call to Irq #2's set_level() was
// high, false if it was low.
irq_levels: Bits256,
gw_pending_ff: Bits256,
/// priority_order[0] is the id/priority of the highest priority Irq,
/// priority_order[31] is the id/priority of the lowest priority Irq.
priority_order: Cell<[IrqPriority; 256]>,
/// id_to_order[1] is the index of Irq #1 in self.priority_order. For example,
/// if Irq #1 is pending, `self.ordered_irq_pending.get(self.id_to_order[1])` will be true.
id_to_order: Cell<[u8; 256]>,
/// ordered_irq_pending.get(0) is true if the highest priority interrupt is
/// pending and enabled. ordered_irq_pending.get(31) is true if the lowest priority
/// interrupt is pending and enabled. Look at self.priority_order
/// to determine their ids.
ordered_irq_pending: Bits256,
// The value to xor a priority threshold with before comparing it with
// IrqPriority::priority_xored
priority_xor: Cell<u8>,
}
impl PicImpl {
fn new() -> Self {
let result = Self {
regs: RefCell::new(PicImplRegs::new()),
irq_levels: Bits256::new(),
gw_pending_ff: Bits256::new(),
priority_order: Cell::new([IrqPriority::default(); 256]),
id_to_order: Cell::new([0u8; 256]),
ordered_irq_pending: Bits256::new(),
priority_xor: Cell::new(0),
};
result.refresh_order();
result
}
fn highest_priority_irq(&self, prithresh: u8) -> Option<u8> {
assert!(prithresh <= MAX_PRIORITY);
match self.ordered_irq_pending.first_set_index() {
Some(idx) => {
let firing_irq = self.priority_order.get()[usize::from(idx)];
if firing_irq.priority_xored < prithresh ^ self.priority_xor.get() {
Some(firing_irq.id)
} else {
None
}
}
None => None,
}
}
fn irq_set_level(&self, id: u8, mut is_high: bool) {
let regs = self.regs.borrow();
self.irq_levels.set(id, is_high);
let ctrl = regs.meigwctrl[id.into()];
is_high ^= ctrl.is_set(Meigwctrl::POLARITY);
if is_high {
self.gw_pending_ff.set(id, true);
}
if ctrl.matches_all(Meigwctrl::TYPE::EdgeTriggered) {
is_high = self.gw_pending_ff.get(id)
}
regs.meip[(id as usize) / 32].set(id % 32, is_high);
self.set_ordered_irq_pending(®s, id, is_high);
}
fn set_ordered_irq_pending(&self, regs: &PicImplRegs, id: u8, is_pending: bool) {
let enabled = regs.meie[usize::from(id)].is_set(Meie::INTEN);
self.ordered_irq_pending.set(
self.id_to_order.get()[usize::from(id)],
enabled && is_pending,
);
}
fn refresh_gateway(&self, id: u8) {
self.irq_set_level(id, self.irq_levels.get(id));
}
fn refresh_enabled(&self, regs: &PicImplRegs, id: u8) {
let val = regs.meip[(id as usize) / 32].get(id % 32);
self.set_ordered_irq_pending(regs, id, val);
}
fn refresh_order(&self) {
let regs = self.regs.borrow();
let priority_xor = if regs
.mpiccfg
.reg
.matches_all(Mpiccfg::PRIORITY_ORDER::Reverse)
{
0x00
} else {
0x0f
};
let mut priorities: [IrqPriority; 256] = std::array::from_fn(|i| {
if i == 0 {
IrqPriority::default()
} else {
IrqPriority {
priority_xored: (regs.meipl[i].read(Meipl::PRIORITY) as u8) ^ priority_xor,
id: i as u8,
}
}
});
priorities.sort();
// priorities is now sorted with the highest priority Irqs at the front
let mut id_to_order = [0u8; 256];
for (index, p) in priorities.iter().enumerate() {
id_to_order[usize::from(p.id)] = u8::try_from(index).unwrap();
}
self.priority_xor.set(priority_xor);
self.priority_order.set(priorities);
self.id_to_order.set(id_to_order);
for i in 0..32u8 {
self.refresh_enabled(®s, i);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_interrupt_priority_order() {
let pic = Pic::new();
let mut regs = pic.mmio_regs(Rc::new(Clock::new()));
// Register some IRQs; typically these would be given to various peripherals that
// want to raise IRQ signals
let irq1 = pic.register_irq(1);
let irq2 = pic.register_irq(2);
let irq3 = pic.register_irq(3);
assert_eq!(pic.highest_priority_irq(0), None);
// drive irq1 and irq2 lines high
irq1.set_level(true);
irq2.set_level(true);
// No IRQs have been enabled
assert_eq!(pic.highest_priority_irq(0), None);
// enable irq2
regs.write(RvSize::Word, PicMmioRegisters::MEIE_OFFSET + 2 * 4, 1)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), None);
// enable irq1
regs.write(RvSize::Word, PicMmioRegisters::MEIE_OFFSET + 4, 1)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), None);
// Set the priority of irq2 from 0 to 1 (0 was disabled)
regs.write(RvSize::Word, PicMmioRegisters::MEIPL_OFFSET + 2 * 4, 1)
.unwrap();
// irq2 is the highest priority firing interrupt
assert_eq!(pic.highest_priority_irq(0), Some(2));
// Set the priority of irq1 from 0 to 1 (0 was disabled)
regs.write(RvSize::Word, PicMmioRegisters::MEIPL_OFFSET + 4, 1)
.unwrap();
// When two pending irqs have the same priority, the one with the lower id wins.
assert_eq!(pic.highest_priority_irq(0), Some(1));
// Reverse priorities (0 is the highest)
regs.write(RvSize::Word, PicMmioRegisters::MPICCFG_OFFSET, 1)
.unwrap();
assert_eq!(pic.highest_priority_irq(15), Some(1));
// Go back to normal priority order (15 is the highest)
regs.write(RvSize::Word, PicMmioRegisters::MPICCFG_OFFSET, 0)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(1));
// raise priority of irq2 to 2
regs.write(RvSize::Word, PicMmioRegisters::MEIPL_OFFSET + 2 * 4, 2)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(2));
// Reverse priorities (0 is the highest)
regs.write(RvSize::Word, PicMmioRegisters::MPICCFG_OFFSET, 1)
.unwrap();
assert_eq!(pic.highest_priority_irq(15), Some(1));
// Go back to normal priority order (15 is the highest)
regs.write(RvSize::Word, PicMmioRegisters::MPICCFG_OFFSET, 0)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(2));
// raise priority of irq1 to 2
regs.write(RvSize::Word, PicMmioRegisters::MEIPL_OFFSET + 4, 2)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(1));
// raise priority of irq3 to 15 (even though it is not firing yet)
regs.write(RvSize::Word, PicMmioRegisters::MEIPL_OFFSET + 3 * 4, 15)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(1));
// enable irq3 (but the signal isn't high yet)
regs.write(RvSize::Word, PicMmioRegisters::MEIE_OFFSET + 3 * 4, 1)
.unwrap();
assert_eq!(pic.highest_priority_irq(0), Some(1));
// set irq3 high
irq3.set_level(true);
assert_eq!(pic.highest_priority_irq(0), Some(3));
assert_eq!(pic.highest_priority_irq(14), Some(3));
assert_eq!(pic.highest_priority_irq(15), None);
irq3.set_level(false);
assert_eq!(pic.highest_priority_irq(0), Some(1));
assert_eq!(pic.highest_priority_irq(1), Some(1));
assert_eq!(pic.highest_priority_irq(2), None);
irq1.set_level(false);
assert_eq!(pic.highest_priority_irq(0), Some(2));
assert_eq!(pic.highest_priority_irq(1), Some(2));
assert_eq!(pic.highest_priority_irq(2), None);
irq2.set_level(false);
assert_eq!(pic.highest_priority_irq(0), None);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/cpu.rs | sw-emulator/lib/cpu/src/cpu.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
cpu.rs
Abstract:
File contains the implementation of Caliptra CPU.
--*/
use crate::csr_file::{Csr, CsrFile};
use crate::instr::Instr;
use crate::types::{
CpuArgs, CpuOrgArgs, RvInstr, RvMEIHAP, RvMStatus, RvMemAccessType, RvMsecCfg, RvPrivMode,
};
use crate::xreg_file::{XReg, XRegFile};
use crate::Pic;
use bit_vec::BitVec;
use caliptra_emu_bus::{Bus, BusError, Clock, Event, TimerAction};
use caliptra_emu_types::{RvAddr, RvData, RvException, RvSize};
use std::rc::Rc;
use std::sync::mpsc;
pub type InstrTracer<'a> = dyn FnMut(u32, RvInstr) + 'a;
/// Describes a Caliptra stack memory region
#[allow(dead_code)] // Stack start never checked
pub struct StackRange(u32, u32);
impl StackRange {
/// **Note:** `stack_start` MUST be greater than `stack_end`. Caliptra's stack grows
/// to a lower address.
pub fn new(stack_start: u32, stack_end: u32) -> Self {
if stack_start < stack_end {
panic!("Caliptra's stack grows to a lower address");
}
Self(stack_start, stack_end)
}
}
/// Describes a Caliptra code region
pub struct CodeRange(u32, u32);
impl CodeRange {
pub fn new(code_start: u32, code_end: u32) -> Self {
if code_start > code_end {
panic!("code grows to a higher address");
}
Self(code_start, code_end)
}
}
/// Contains metadata describing a Caliptra image
pub struct ImageInfo {
stack_range: StackRange,
code_range: CodeRange,
}
impl ImageInfo {
pub fn new(stack_range: StackRange, code_range: CodeRange) -> Self {
Self {
stack_range,
code_range,
}
}
/// Checks if the program counter is contained in `self`
///
/// returns `true` if the pc is in the image. `false` otherwise.
fn contains_pc(&self, pc: u32) -> bool {
self.code_range.0 <= pc && pc <= self.code_range.1
}
/// Checks if the stack pointer has overflowed.
///
/// Returns `Some(u32)` if an overflow has occurred. The `u32` is set
/// to the overflow amount.
///
/// Returns `None` if no overflow has occurred.
fn check_overflow(&self, sp: u32) -> Option<u32> {
let stack_end = self.stack_range.1;
// Stack grows to a lower address
if sp < stack_end {
let current_overflow = stack_end - sp;
Some(current_overflow)
} else {
None
}
}
}
/// Describes the shape of Caliptra's stacks.
///
/// Used to monitor stack usage and check for overflows.
pub struct StackInfo {
images: Vec<ImageInfo>,
max_stack_overflow: u32,
has_overflowed: bool,
}
impl StackInfo {
/// Create a new `StackInfo` by describing the start and end of the stack and code segment for each
/// Caliptra image.
pub fn new(images: Vec<ImageInfo>) -> Self {
Self {
images,
max_stack_overflow: 0,
has_overflowed: false,
}
}
}
impl StackInfo {
/// Fetch the largest stack overflow.
///
/// If the stack never overflowed, returns `None`.
fn max_stack_overflow(&self) -> Option<u32> {
if self.has_overflowed {
Some(self.max_stack_overflow)
} else {
None
}
}
/// Checks if the stack will overflow when pushed to `stack_address`.
///
/// Returns `Some(u32)` if the stack will overflow and by how much, `None` if it will not overflow.
fn check_overflow(&mut self, pc: u32, stack_address: u32) -> Option<u32> {
if stack_address == 0 {
// sp is initialized to 0.
return None;
}
for image in self.images.iter() {
if image.contains_pc(pc) {
if let Some(overflow_amount) = image.check_overflow(stack_address) {
self.max_stack_overflow = self.max_stack_overflow.max(overflow_amount);
self.has_overflowed = true;
return Some(overflow_amount);
}
}
}
None
}
}
#[derive(Clone)]
pub struct CodeCoverage {
org: CpuOrgArgs,
rom_bit_vec: BitVec,
iccm_bit_vec: BitVec,
}
pub struct CoverageBitmaps<'a> {
pub rom: &'a bit_vec::BitVec,
pub iccm: &'a bit_vec::BitVec,
}
impl CodeCoverage {
pub fn new(org: CpuOrgArgs) -> Self {
Self {
org,
rom_bit_vec: BitVec::from_elem(org.rom_size as usize, false),
iccm_bit_vec: BitVec::from_elem(org.iccm_size as usize, false),
}
}
pub fn log_execution(&mut self, pc: RvData, instr: &Instr) {
let num_bytes = match instr {
Instr::Compressed(_) => 2,
Instr::General(_) => 4,
};
if (self.org.rom..(self.org.rom + self.org.rom_size)).contains(&pc) {
// Mark the bytes corresponding to the executed instruction as true.
for i in 0..num_bytes {
let byte_index = ((pc - self.org.rom) + i) as usize;
if byte_index < self.rom_bit_vec.len() {
self.rom_bit_vec.set(byte_index, true);
}
}
} else if (self.org.iccm..(self.org.iccm + self.org.iccm_size)).contains(&pc) {
// Mark the bytes corresponding to the executed instruction as true.
for i in 0..num_bytes {
let byte_index = ((pc - self.org.iccm) + i) as usize;
if byte_index < self.iccm_bit_vec.len() {
self.iccm_bit_vec.set(byte_index, true);
}
}
}
}
pub fn code_coverage_bitmap(&self) -> CoverageBitmaps {
CoverageBitmaps {
rom: &self.rom_bit_vec,
iccm: &self.iccm_bit_vec,
}
}
}
#[derive(PartialEq)]
pub enum WatchPtrKind {
Read,
Write,
}
pub struct WatchPtrHit {
pub addr: u32,
pub kind: WatchPtrKind,
}
pub struct WatchPtrCfg {
pub write: Vec<u32>,
pub read: Vec<u32>,
pub hit: Option<WatchPtrHit>,
}
impl WatchPtrCfg {
pub fn new() -> Self {
Self {
write: Vec::new(),
read: Vec::new(),
hit: None,
}
}
}
impl Default for WatchPtrCfg {
fn default() -> Self {
Self::new()
}
}
/// RISCV CPU
pub struct Cpu<TBus: Bus> {
/// General Purpose register file
xregs: XRegFile,
/// Configuration & status registers
csrs: CsrFile,
// Program counter
pc: RvData,
/// The next program counter after the current instruction is finished executing.
next_pc: RvData,
/// The NMI vector. In the real CPU, this is hardwired from the outside.
nmivec: u32,
/// The External interrupt vector table.
ext_int_vec: u32,
/// Global interrupt enabled
global_int_en: bool,
/// Machine External interrupt enabled
ext_int_en: bool,
/// Halted state
halted: bool,
// The bus the CPU uses to talk to memory and peripherals.
pub bus: TBus,
pub clock: Rc<Clock>,
pub pic: Rc<Pic>,
/// Current privilege mode
pub priv_mode: RvPrivMode,
// Track if Execution is in progress
pub(crate) is_execute_instr: bool,
// This is used to track watchpointers
pub(crate) watch_ptr_cfg: WatchPtrCfg,
pub code_coverage: CodeCoverage,
stack_info: Option<StackInfo>,
/// CPU arguments
args: CpuArgs,
#[cfg(test)]
internal_timer_local_int_counter: usize,
#[cfg(test)]
external_int_counter: usize,
// incoming communication with other components
incoming_events: Option<mpsc::Receiver<Event>>,
// events sent to other components
outgoing_events: Option<mpsc::Sender<Event>>,
}
impl<TBus: Bus> Drop for Cpu<TBus> {
fn drop(&mut self) {
if let Some(stack_info) = &self.stack_info {
if stack_info.has_overflowed {
panic!(
"[EMU] Fatal: Caliptra's stack overflowed by {} bytes!",
stack_info.max_stack_overflow().unwrap()
)
}
}
}
}
/// Cpu instruction step action
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum StepAction {
/// Continue
Continue,
/// Break
Break,
/// Fatal
Fatal,
}
impl<TBus: Bus> Cpu<TBus> {
/// Create a new RISCV CPU
pub fn new(bus: TBus, clock: Rc<Clock>, pic: Rc<Pic>, args: CpuArgs) -> Self {
Self {
xregs: XRegFile::new(),
csrs: CsrFile::new(clock.clone(), pic.clone()),
pc: args.org.reset_vector,
next_pc: args.org.reset_vector,
bus,
clock,
pic,
priv_mode: RvPrivMode::M,
is_execute_instr: false,
watch_ptr_cfg: WatchPtrCfg::new(),
nmivec: 0,
ext_int_vec: 0,
global_int_en: false,
ext_int_en: false,
halted: false,
// TODO: Pass in code_coverage from the outside (as caliptra-emu-cpu
// isn't supposed to know anything about the caliptra memory map)
code_coverage: CodeCoverage::new(args.org),
stack_info: None,
args,
#[cfg(test)]
internal_timer_local_int_counter: 0,
#[cfg(test)]
external_int_counter: 0,
incoming_events: None,
outgoing_events: None,
}
}
pub fn with_stack_info(&mut self, stack_info: StackInfo) {
self.stack_info = Some(stack_info);
}
/// Read the RISCV CPU Program counter
///
/// # Return
///
/// * `RvData` - PC value.
pub fn read_pc(&self) -> RvData {
self.pc
}
/// Write the RISCV CPU Program counter
///
/// # Arguments
///
/// * `pc` - Program counter value
pub fn write_pc(&mut self, pc: RvData) {
self.pc = pc;
}
/// Resets program counter to default reset vector
fn reset_pc(&mut self) {
self.pc = self.args.org.reset_vector;
}
/// Returns the next program counter after the current instruction is finished executing.
pub fn next_pc(&self) -> RvData {
self.next_pc
}
/// Set the next program counter after the current instruction is finished executing.
///
/// Should only be set by instruction implementations.
pub fn set_next_pc(&mut self, next_pc: RvData) {
self.next_pc = next_pc;
}
/// Read the specified RISCV General Purpose Register
///
/// # Arguments
///
/// * `reg` - Register to read
///
/// # Return
///
/// * `RvData` - Register value if addr is valid; u32::MAX otherwise.
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn read_xreg(&self, reg: XReg) -> Result<RvData, RvException> {
self.xregs.read(reg)
}
/// Write the specified RISCV General Purpose Register
///
/// # Arguments
///
/// * `reg` - Register to write
/// * `val` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write_xreg(&mut self, reg: XReg, val: RvData) -> Result<(), RvException> {
// XReg::X2 is the sp register.
if reg == XReg::X2 {
self.check_stack(val);
}
self.xregs.write(reg, val)?;
Ok(())
}
// Check if the stack overflows at the requested address.
fn check_stack(&mut self, val: RvData) {
if let Some(stack_info) = &mut self.stack_info {
if let Some(overflow_amount) = stack_info.check_overflow(self.pc, val) {
eprintln!(
"[EMU] Caliptra's stack overflowed by {} bytes at pc 0x{:x}.",
overflow_amount, self.pc
);
}
}
}
/// Read the specified configuration status register with the current privilege mode
///
/// # Arguments
///
/// * `csr` - Configuration status register to read
///
/// # Return
///
/// * `RvData` - Register value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn read_csr(&self, csr: RvAddr) -> Result<RvData, RvException> {
self.csrs.read(self.priv_mode, csr)
}
/// Read the specified configuration status register as if we were in M mode
///
/// # Arguments
///
/// * `csr` - Configuration status register to read
///
/// # Return
///
/// * `RvData` - Register value
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn read_csr_machine(&self, csr: RvAddr) -> Result<RvData, RvException> {
self.csrs.read(RvPrivMode::M, csr)
}
/// Write the specified Configuration status register with the current privilege mode
///
/// # Arguments
///
/// * `reg` - Configuration status register to write
/// * `val` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write_csr(&mut self, csr: RvAddr, val: RvData) -> Result<(), RvException> {
self.csrs.write(self.priv_mode, csr, val)
}
/// Write the specified Configuration status register as if we were in M mode
///
/// # Arguments
///
/// * `reg` - Configuration status register to write
/// * `val` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::IllegalRegister`
pub fn write_csr_machine(&mut self, csr: RvAddr, val: RvData) -> Result<(), RvException> {
self.csrs.write(RvPrivMode::M, csr, val)
}
/// Check memory privileges of given address
///
/// # Arguments
///
/// * `addr` - Address to check
/// * `access` - Access type to check
///
/// # Return
///
/// * `RvException` - Exception with cause `RvException::LoadAccessFault`,
/// `RvException::store_access_fault`, or `RvException::instr_access_fault`.
fn check_mem_priv_addr(
&self,
addr: RvAddr,
access: RvMemAccessType,
) -> Result<(), RvException> {
let fault = || match access {
RvMemAccessType::Read => RvException::load_access_fault(addr),
RvMemAccessType::Write => RvException::store_access_fault(addr),
RvMemAccessType::Execute => RvException::instr_access_fault(addr),
_ => unreachable!(),
};
let mstatus = RvMStatus(self.read_csr_machine(Csr::MSTATUS)?);
let priv_mode = if mstatus.mprv() != 0
&& (access == RvMemAccessType::Read || access == RvMemAccessType::Write)
{
mstatus.mpp()
} else {
self.priv_mode
};
let mseccfg = RvMsecCfg(self.read_csr_machine(Csr::MSECCFG)?);
if let Some(pmpicfg) = self.csrs.pmp_match_addr(addr)? {
if mseccfg.mml() != 0 {
// Perform enhanced privilege check
let check_mask = (pmpicfg.execute() & 0x1)
| ((pmpicfg.write() & 0x1) << 1)
| ((pmpicfg.read() & 0x1) << 2)
| ((pmpicfg.lock() & 0x1) << 3);
// This matches the spec truth table
let allowed_mask = match priv_mode {
RvPrivMode::M => match check_mask {
0 | 1 | 4..=8 => 0,
2 | 3 | 14 => RvMemAccessType::Read as u8 | RvMemAccessType::Write as u8,
9 | 10 => RvMemAccessType::Execute as u8,
11 | 13 => RvMemAccessType::Read as u8 | RvMemAccessType::Execute as u8,
12 | 15 => RvMemAccessType::Read as u8,
_ => unreachable!(),
},
RvPrivMode::U => match check_mask {
0 | 8 | 9 | 12..=14 => 0,
1 | 10 | 11 => RvMemAccessType::Execute as u8,
2 | 4 | 15 => RvMemAccessType::Read as u8,
3 | 6 => RvMemAccessType::Read as u8 | RvMemAccessType::Write as u8,
5 => RvMemAccessType::Read as u8 | RvMemAccessType::Execute as u8,
7 => {
RvMemAccessType::Read as u8
| RvMemAccessType::Write as u8
| RvMemAccessType::Execute as u8
}
_ => unreachable!(),
},
_ => unreachable!(),
};
if (access as u8 & allowed_mask) != access as u8 {
return Err(fault());
}
} else {
let check_bit = match access {
RvMemAccessType::Read => pmpicfg.read(),
RvMemAccessType::Write => pmpicfg.write(),
RvMemAccessType::Execute => pmpicfg.execute(),
_ => unreachable!(),
};
if check_bit == 0 && (priv_mode != RvPrivMode::M || pmpicfg.lock() != 0) {
return Err(fault());
}
}
} else if priv_mode == RvPrivMode::M && mseccfg.mmwp() != 0 {
return Err(fault());
}
Ok(())
}
/// Check memory privileges of given address
///
/// # Arguments
///
/// * `addr` - Address to check
/// * `size` - Size of region
/// * `access` - Access type to check
///
/// # Return
///
/// * `RvException` - Exception with cause `RvException::LoadAccessFault`,
/// `RvException::store_access_fault`, or `RvException::instr_access_fault`.
pub fn check_mem_priv(
&self,
addr: RvAddr,
size: RvSize,
access: RvMemAccessType,
) -> Result<(), RvException> {
self.check_mem_priv_addr(addr, access)?;
if size == RvSize::Word && addr & 0x3 != 0 {
// If unaligned, check permissions of intermediate addresses
for i in 1..RvSize::Word.into() {
self.check_mem_priv_addr(addr + i as u32, access)?;
}
}
Ok(())
}
/// Read from bus
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::LoadAccessFault`
/// or `RvExceptionCause::LoadAddrMisaligned`
pub fn read_bus(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, RvException> {
// Check if we are in step mode
if self.is_execute_instr {
self.watch_ptr_cfg.hit = match self.watch_ptr_cfg.read.contains(&addr) {
true => Some(WatchPtrHit {
addr,
kind: WatchPtrKind::Read,
}),
false => None,
}
}
self.check_mem_priv(addr, size, RvMemAccessType::Read)?;
match self.bus.read(size, addr) {
Ok(val) => Ok(val),
Err(exception) => match exception {
BusError::InstrAccessFault => Err(RvException::instr_access_fault(addr)),
BusError::LoadAccessFault => Err(RvException::load_access_fault(addr)),
BusError::LoadAddrMisaligned => Err(RvException::load_addr_misaligned(addr)),
BusError::StoreAccessFault => Err(RvException::store_access_fault(addr)),
BusError::StoreAddrMisaligned => Err(RvException::store_addr_misaligned(addr)),
},
}
}
/// Write to bus
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
/// * `val` - Value to write
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::StoreAccessFault`
/// or `RvExceptionCause::StoreAddrMisaligned`
pub fn write_bus(
&mut self,
size: RvSize,
addr: RvAddr,
val: RvData,
) -> Result<(), RvException> {
// Check if we are in step mode
if self.is_execute_instr {
self.watch_ptr_cfg.hit = match self.watch_ptr_cfg.write.contains(&addr) {
true => Some(WatchPtrHit {
addr,
kind: WatchPtrKind::Write,
}),
false => None,
}
}
self.check_mem_priv(addr, size, RvMemAccessType::Write)?;
match self.bus.write(size, addr, val) {
Ok(val) => Ok(val),
Err(exception) => match exception {
BusError::InstrAccessFault => Err(RvException::instr_access_fault(addr)),
BusError::LoadAccessFault => Err(RvException::load_access_fault(addr)),
BusError::LoadAddrMisaligned => Err(RvException::load_addr_misaligned(addr)),
BusError::StoreAccessFault => Err(RvException::store_access_fault(addr)),
BusError::StoreAddrMisaligned => Err(RvException::store_addr_misaligned(addr)),
},
}
}
/// Read instruction
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::LoadAccessFault`
/// or `RvExceptionCause::LoadAddrMisaligned`
pub fn read_instr(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, RvException> {
self.check_mem_priv(addr, size, RvMemAccessType::Execute)?;
match size {
RvSize::Byte => Err(RvException::instr_access_fault(addr)),
_ => match self.bus.read(size, addr) {
Ok(val) => Ok(val),
Err(exception) => match exception {
BusError::InstrAccessFault => Err(RvException::instr_access_fault(addr)),
BusError::LoadAccessFault => Err(RvException::instr_access_fault(addr)),
BusError::LoadAddrMisaligned => Err(RvException::instr_addr_misaligned(addr)),
BusError::StoreAccessFault => Err(RvException::store_access_fault(addr)),
BusError::StoreAddrMisaligned => Err(RvException::store_addr_misaligned(addr)),
},
},
}
}
/// Perform a reset of the CPU
pub fn do_reset(&mut self) {
self.halted = false;
self.priv_mode = RvPrivMode::M;
self.csrs.reset();
self.reset_pc();
}
pub fn warm_reset(&mut self) {
self.clock
.timer()
.schedule_action_in(0, TimerAction::WarmReset);
}
/// Step a single instruction
pub fn step(&mut self, instr_tracer: Option<&mut InstrTracer>) -> StepAction {
let mut fired_action_types: Vec<TimerAction> = self
.clock
.increment_and_process_timer_actions(1, &mut self.bus)
.into_iter()
.collect();
fired_action_types.sort_by_key(|a| -a.priority());
let mut step_action = None;
let mut saved = vec![];
while let Some(action_type) = fired_action_types.pop() {
let mut save = false;
match action_type {
TimerAction::WarmReset => {
self.do_reset();
break;
}
TimerAction::UpdateReset => {
self.do_reset();
break;
}
TimerAction::Nmi { mcause } => {
self.halted = false;
step_action = Some(self.handle_nmi(mcause, 0));
break;
}
TimerAction::SetNmiVec { addr } => self.nmivec = addr,
TimerAction::ExtInt { irq, can_wake } => {
if self.global_int_en && self.ext_int_en && (!self.halted || can_wake) {
self.halted = false;
step_action = Some(self.handle_external_int(irq));
break;
} else {
save = true;
}
}
TimerAction::SetExtIntVec { addr } => self.ext_int_vec = addr,
TimerAction::SetGlobalIntEn { en } => self.global_int_en = en,
TimerAction::SetExtIntEn { en } => self.ext_int_en = en,
TimerAction::InternalTimerLocalInterrupt { timer_id } => {
// Reset the timer value to 0 when it reaches its bound.
self.csrs.internal_timers.write_mitcnt(timer_id, 0);
self.csrs.internal_timers.disarm(timer_id);
if self.global_int_en && !self.halted {
step_action = Some(self.handle_internal_timer_local_interrupt(timer_id));
break;
} else {
save = true;
}
}
TimerAction::MachineTimerInterrupt => {
self.csrs.set_mtip(true);
if self.global_int_en && !self.halted {
step_action = Some(self.handle_machine_timer_intteruppt());
break;
} else {
save = true;
}
}
TimerAction::Halt => self.halted = true,
_ => {}
}
if save {
saved.push(action_type);
}
}
// reschedule actions that were not processed
for action in saved {
self.clock.timer().schedule_action_in(1, action);
}
for action in fired_action_types {
self.clock.timer().schedule_action_in(1, action);
}
// if we already processed an interrupt, then return immediately
if let Some(returned_action) = step_action {
return returned_action;
}
// We are in a halted state. Don't continue executing but poll the bus for interrupts
if self.halted {
self.set_next_pc(self.pc);
return StepAction::Continue;
}
let action = match self.exec_instr(instr_tracer) {
Ok(result) => result,
Err(exception) => self.handle_exception(exception),
};
// handle incoming events at this point, if there are any
self.handle_incoming_events();
action
}
fn handle_internal_timer_local_interrupt(&mut self, timer_id: u8) -> StepAction {
#[cfg(test)]
{
self.internal_timer_local_int_counter += 1;
}
let mcause = 0x8000_001D - (timer_id as u32);
match self.handle_trap(
self.read_pc(),
mcause,
0,
// Cannot panic; mtvec is a valid CSR
self.read_csr_machine(Csr::MTVEC).unwrap() & !0b11,
) {
Ok(_) => StepAction::Continue,
Err(_) => StepAction::Fatal,
}
}
fn handle_machine_timer_intteruppt(&mut self) -> StepAction {
#[cfg(test)]
{
self.internal_timer_local_int_counter += 1;
}
let mcause = 0x8000_0007;
match self.handle_trap(
self.read_pc(),
mcause,
0,
// Cannot panic; mtvec is a valid CSR
self.read_csr_machine(Csr::MTVEC).unwrap() & !0b11,
) {
Ok(_) => StepAction::Continue,
Err(_) => StepAction::Fatal,
}
}
/// Handle synchronous exception
fn handle_exception(&mut self, exception: RvException) -> StepAction {
let ret = self.handle_trap(
self.read_pc(),
exception.cause().into(),
exception.info(),
// Cannot panic; mtvec is a valid CSR
self.read_csr_machine(Csr::MTVEC).unwrap() & !0b11,
);
match ret {
Ok(_) => StepAction::Continue,
Err(_) => StepAction::Fatal,
}
}
/// Handle non-maskable interrupt (VeeR-specific)
fn handle_nmi(&mut self, cause: u32, info: u32) -> StepAction {
let ret = self.handle_trap(self.read_pc(), cause, info, self.nmivec);
match ret {
Ok(_) => StepAction::Continue,
Err(_) => StepAction::Fatal,
}
}
/// Handle synchronous & asynchronous trap
///
/// # Error
///
/// * `RvException` - Exception
fn handle_trap(
&mut self,
pc: RvAddr,
cause: u32,
info: u32,
next_pc: u32,
) -> Result<(), RvException> {
self.write_csr_machine(Csr::MEPC, pc)?;
self.write_csr_machine(Csr::MCAUSE, cause)?;
self.write_csr_machine(Csr::MTVAL, info)?;
let mut status = RvMStatus(self.read_csr_machine(Csr::MSTATUS)?);
match self.priv_mode {
RvPrivMode::U => {
// All traps are handled in M mode
self.priv_mode = RvPrivMode::M;
status.set_mpp(RvPrivMode::U);
}
RvPrivMode::M => {
status.set_mpp(RvPrivMode::M);
}
_ => unreachable!(),
}
status.set_mpie(status.mie());
status.set_mie(0);
self.write_csr_machine(Csr::MSTATUS, status.0)?;
// Don't rely on write_csr to disable global interrupts as the scheduled action could be
// after a next interrupt
self.global_int_en = false;
self.write_pc(next_pc);
// println!(
// "handle_trap: cause={:x}, mtval={:x}, pc={:x}, next_pc={:x}",
// cause, info, pc, next_pc
// );
Ok(())
}
//// Handle external interrupts
fn handle_external_int(&mut self, irq: u8) -> StepAction {
#[cfg(test)]
{
self.external_int_counter += 1;
}
const REDIRECT_ENTRY_SIZE: u32 = 4;
const MAX_IRQ: u32 = 32;
let vec_table = self.ext_int_vec;
if vec_table < self.args.org.dccm
|| vec_table + MAX_IRQ * REDIRECT_ENTRY_SIZE
> self.args.org.dccm + self.args.org.dccm_size
{
const NON_DCCM_NMI: u32 = 0xF000_1002;
return self.handle_nmi(NON_DCCM_NMI, 0);
}
// Elevate to M Mode before reading the vector table
let mut status = match self.read_csr_machine(Csr::MSTATUS) {
Ok(value) => RvMStatus(value),
Err(_) => return StepAction::Fatal,
};
match self.priv_mode {
RvPrivMode::U => {
self.priv_mode = RvPrivMode::M;
status.set_mpp(RvPrivMode::U);
}
RvPrivMode::M => {
status.set_mpp(RvPrivMode::M);
}
_ => unreachable!(),
}
let next_pc_ptr = vec_table + REDIRECT_ENTRY_SIZE * u32::from(irq);
let mut meihap = RvMEIHAP(vec_table);
meihap.set_claimid(irq.into());
if self.write_csr_machine(Csr::MEIHAP, meihap.0).is_err() {
return StepAction::Fatal;
}
let Ok(next_pc) = self.read_bus(RvSize::Word, next_pc_ptr) else {
return StepAction::Fatal;
};
const MACHINE_EXTERNAL_INT: u32 = 0x8000_000B;
let ret = self.handle_trap(self.read_pc(), MACHINE_EXTERNAL_INT, 0, next_pc);
match ret {
Ok(_) => StepAction::Continue,
Err(_) => StepAction::Fatal,
}
}
//// Append WatchPointer
pub fn add_watchptr(&mut self, addr: u32, len: u32, kind: WatchPtrKind) {
for addr in addr..(addr + len) {
match kind {
WatchPtrKind::Read => self.watch_ptr_cfg.read.push(addr),
WatchPtrKind::Write => self.watch_ptr_cfg.write.push(addr),
}
}
}
//// Remove WatchPointer
pub fn remove_watchptr(&mut self, addr: u32, len: u32, kind: WatchPtrKind) {
let watch_ptr = match kind {
WatchPtrKind::Read => &mut self.watch_ptr_cfg.read,
WatchPtrKind::Write => &mut self.watch_ptr_cfg.write,
};
watch_ptr.retain(|&x| -> bool { (x < addr) || (x > (addr + len)) });
}
//// Get WatchPointer
pub fn get_watchptr_hit(&self) -> Option<&WatchPtrHit> {
self.watch_ptr_cfg.hit.as_ref()
}
// returns a sender (that sends events to this CPU)
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/op.rs | sw-emulator/lib/cpu/src/instr/op.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
op.rs
Abstract:
File contains implementation of RISCV Register Operation instructions
References:
https://riscv.org/wp-content/uploads/2019/06/riscv-spec.pdf
https://github.com/d0iasm/rvemu for arithmetic operations.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32OpFunct3, RvInstr32OpFunct7, RvInstr32Opcode, RvInstr32R};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvData, RvException};
impl<TBus: Bus> Cpu<TBus> {
/// Execute register operation instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_op_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32R(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Op);
let val1 = self.read_xreg(instr.rs1())?;
let val2 = self.read_xreg(instr.rs2())?;
let data = match (instr.funct3().into(), instr.funct7().into()) {
// Add (`add`) instruction
(RvInstr32OpFunct3::Zero, RvInstr32OpFunct7::Add) => val1.wrapping_add(val2) as RvData,
// Multiply (`mul`) instruction
(RvInstr32OpFunct3::Zero, RvInstr32OpFunct7::Mul) => {
let val1 = val1 as i32;
let val2 = val2 as i32;
val1.wrapping_mul(val2) as RvData
}
// Subtract (`sub`) instruction
(RvInstr32OpFunct3::Zero, RvInstr32OpFunct7::Sub) => val1.wrapping_sub(val2) as RvData,
// Shift Left Logical (`sll`) instruction
(RvInstr32OpFunct3::One, RvInstr32OpFunct7::Sll) => val1.wrapping_shl(val2) as RvData,
// Multiply High (`mul`) instruction
(RvInstr32OpFunct3::One, RvInstr32OpFunct7::Mulh) => {
let val1 = val1 as i32 as i64;
let val2 = val2 as i32 as i64;
(val1.wrapping_mul(val2) >> 32) as RvData
}
// Set Less Than (`slt`) instruction
(RvInstr32OpFunct3::Two, RvInstr32OpFunct7::Slt) => {
if (val1 as i32) < (val2 as i32) {
1
} else {
0
}
}
// Multiply High Signed and Unsigned (`mulhsu`) instruction
(RvInstr32OpFunct3::Two, RvInstr32OpFunct7::Mulhsu) => {
let val1 = val1 as i32 as i64 as u64;
let val2 = val2 as u64;
(val1.wrapping_mul(val2) >> 32) as RvData
}
// Set Less Than Unsigned (`sltu`) instruction
(RvInstr32OpFunct3::Three, RvInstr32OpFunct7::Sltu) => {
if val1 < val2 {
1
} else {
0
}
}
// Multiply High Unsigned (`mulhu`) instruction
(RvInstr32OpFunct3::Three, RvInstr32OpFunct7::Mulhu) => {
let val1 = val1 as u64;
let val2 = val2 as u64;
(val1.wrapping_mul(val2) >> 32) as RvData
}
// Xor (`xor`) instruction
(RvInstr32OpFunct3::Four, RvInstr32OpFunct7::Xor) => val1 ^ val2,
// Division (`div`) instruction
(RvInstr32OpFunct3::Four, RvInstr32OpFunct7::Div) => {
let dividend = val1 as i32;
let divisor = val2 as i32;
if divisor == 0 {
RvData::MAX
} else if dividend == i32::MIN && divisor == -1 {
dividend as RvData
} else {
dividend.wrapping_div(divisor) as RvData
}
}
// Shift Right Logical (`srl`) instruction
(RvInstr32OpFunct3::Five, RvInstr32OpFunct7::Srl) => val1.wrapping_shr(val2) as RvData,
// Division Unsigned (`divu`) instruction
(RvInstr32OpFunct3::Five, RvInstr32OpFunct7::Divu) => {
let dividend = val1;
let divisor = val2;
if divisor == 0 {
RvData::MAX
} else {
dividend.wrapping_div(divisor) as RvData
}
}
// Shift Right Arithmetic (`sra`) instruction
(RvInstr32OpFunct3::Five, RvInstr32OpFunct7::Sra) => {
(val1 as i32).wrapping_shr(val2) as RvData
}
// Or (`or`) instruction
(RvInstr32OpFunct3::Six, RvInstr32OpFunct7::Or) => val1 | val2,
// Remainder (`rem`) instruction
(RvInstr32OpFunct3::Six, RvInstr32OpFunct7::Rem) => {
let dividend = val1 as i32;
let divisor = val2 as i32;
if divisor == 0 {
dividend as RvData
} else if dividend == i32::MIN && divisor == -1 {
0
} else {
dividend.wrapping_rem(divisor) as RvData
}
}
// And (`and`) instruction
(RvInstr32OpFunct3::Seven, RvInstr32OpFunct7::And) => val1 & val2,
// Remained Unsigned (`remu`) instruction
(RvInstr32OpFunct3::Seven, RvInstr32OpFunct7::Remu) => {
let dividend = val1;
let divisor = val2;
if divisor == 0 {
dividend as RvData
} else {
dividend.wrapping_rem(divisor) as RvData
}
}
// Illegal instruction
_ => match self.exec_bit_instr_op(instr, val1, val2) {
Some(val) => val,
_ => Err(RvException::illegal_instr(instr.0))?,
},
};
self.write_xreg(instr.rd(), data)
}
}
#[allow(clippy::identity_op)]
#[cfg(test)]
mod tests {
use crate::{
test_rr_op, test_rr_src12_eq_dest, test_rr_src1_eq_dest, test_rr_src2_eq_dest,
test_rr_zerodest, test_rr_zerosrc1, test_rr_zerosrc12, test_rr_zerosrc2,
};
// ---------------------------------------------------------------------------------------------
// Tests For Add (`add`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/add.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_add_2, add, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_add_3, add, 0x00000002, 0x00000001, 0x00000001);
test_rr_op!(test_add_4, add, 0x0000000a, 0x00000003, 0x00000007);
test_rr_op!(test_add_5, add, 0xFFFF8000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_add_6, add, 0x80000000, 0x80000000, 0x00000000);
test_rr_op!(test_add_7, add, 0x7FFF8000, 0x80000000, 0xFFFF8000);
test_rr_op!(test_add_8, add, 0x00007FFF, 0x00000000, 0x00007FFF);
test_rr_op!(test_add_9, add, 0x7FFFFFFF, 0x7FFFFFFF, 0x00000000);
test_rr_op!(test_add_10, add, 0x80007FFE, 0x7FFFFFFF, 0x00007FFF);
test_rr_op!(test_add_11, add, 0x80007FFF, 0x80000000, 0x00007FFF);
test_rr_op!(test_add_12, add, 0x7FFF7FFF, 0x7FFFFFFF, 0xFFFF8000);
test_rr_op!(test_add_13, add, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF);
test_rr_op!(test_add_14, add, 0x00000000, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_add_15, add, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF);
test_rr_op!(test_add_16, add, 0x80000000, 0x00000001, 0x7FFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_add_17, add, 24, 13, 11);
test_rr_src2_eq_dest!(test_add_18, add, 25, 14, 11);
test_rr_src12_eq_dest!(test_add_19, add, 26, 13);
// Bypassing tests
test_rr_zerosrc1!(test_add_35, add, 15, 15);
test_rr_zerosrc2!(test_add_36, add, 32, 32);
test_rr_zerosrc12!(test_add_37, add, 0);
test_rr_zerodest!(test_add_38, add, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests For Mul (`mul`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/mul.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_mul_32, mul, 0x00001200, 0x00007e00, 0xb6db6db7);
test_rr_op!(test_mul_33, mul, 0x00001240, 0x00007fc0, 0xb6db6db7);
test_rr_op!(test_mul_2, mul, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_mul_3, mul, 0x00000001, 0x00000001, 0x00000001);
test_rr_op!(test_mul_4, mul, 0x00000015, 0x00000003, 0x00000007);
test_rr_op!(test_mul_5, mul, 0x00000000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_mul_6, mul, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_mul_7, mul, 0x00000000, 0x80000000, 0xFFFF8000);
test_rr_op!(test_mul_30, mul, 0x0000FF7F, 0xaaaaaaab, 0x0002fe7d);
test_rr_op!(test_mul_31, mul, 0x0000FF7F, 0x0002fe7d, 0xaaaaaaab);
test_rr_op!(test_mul_34, mul, 0x00000000, 0xFF000000, 0xFF000000);
test_rr_op!(test_mul_35, mul, 0x00000001, 0xFFFFFFFF, 0xFFFFFFFF);
test_rr_op!(test_mul_36, mul, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_mul_37, mul, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_mul_8, mul, 143, 13, 11);
test_rr_src2_eq_dest!(test_mul_9, mul, 154, 14, 11);
test_rr_src12_eq_dest!(test_mul_10, mul, 169, 13);
// Bypassing tests
test_rr_zerosrc1!(test_mul_26, mul, 0, 31);
test_rr_zerosrc2!(test_mul_27, mul, 0, 32);
test_rr_zerosrc12!(test_mul_28, mul, 0);
test_rr_zerodest!(test_mul_29, mul, 33, 34);
// ---------------------------------------------------------------------------------------------
// Tests For Sub (`sub`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sub.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_sub_2, sub, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_sub_3, sub, 0x00000000, 0x00000001, 0x00000001);
test_rr_op!(test_sub_4, sub, 0xFFFFFFFC, 0x00000003, 0x00000007);
test_rr_op!(test_sub_5, sub, 0x00008000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_sub_6, sub, 0x80000000, 0x80000000, 0x00000000);
test_rr_op!(test_sub_7, sub, 0x80008000, 0x80000000, 0xFFFF8000);
test_rr_op!(test_sub_8, sub, 0xFFFF8001, 0x00000000, 0x00007FFF);
test_rr_op!(test_sub_9, sub, 0x7FFFFFFF, 0x7FFFFFFF, 0x00000000);
test_rr_op!(test_sub_10, sub, 0x7FFF8000, 0x7FFFFFFF, 0x00007FFF);
test_rr_op!(test_sub_11, sub, 0x7FFF8001, 0x80000000, 0x00007FFF);
test_rr_op!(test_sub_12, sub, 0x80007FFF, 0x7FFFFFFF, 0xFFFF8000);
test_rr_op!(test_sub_13, sub, 0x00000001, 0x00000000, 0xFFFFFFFF);
test_rr_op!(test_sub_14, sub, 0xFFFFFFFE, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_sub_15, sub, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_sub_16, sub, 2, 13, 11);
test_rr_src2_eq_dest!(test_sub_17, sub, 3, 14, 11);
test_rr_src12_eq_dest!(test_sub_18, sub, 0, 13);
// Bypassing tests
test_rr_zerosrc1!(test_sub_34, sub, 15, -15i32 as u32);
test_rr_zerosrc2!(test_sub_35, sub, 32, 32);
test_rr_zerosrc12!(test_sub_36, sub, 0);
test_rr_zerodest!(test_sub_37, sub, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests For Shift Logical Left (`sll`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-sofware-src/riscv-tests/blob/master/isa/rv64ui/sll.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_sll_2, sll, 0x00000001, 0x00000001, 0);
test_rr_op!(test_sll_3, sll, 0x00000002, 0x00000001, 1);
test_rr_op!(test_sll_4, sll, 0x00000080, 0x00000001, 7);
test_rr_op!(test_sll_5, sll, 0x00004000, 0x00000001, 14);
test_rr_op!(test_sll_6, sll, 0x80000000, 0x00000001, 31);
test_rr_op!(test_sll_7, sll, 0xFFFFFFFF, 0xFFFFFFFF, 0);
test_rr_op!(test_sll_8, sll, 0xFFFFFFFE, 0xFFFFFFFF, 1);
test_rr_op!(test_sll_9, sll, 0xFFFFFF80, 0xFFFFFFFF, 7);
test_rr_op!(test_sll_10, sll, 0xFFFFC000, 0xFFFFFFFF, 14);
test_rr_op!(test_sll_11, sll, 0x80000000, 0xFFFFFFFF, 31);
test_rr_op!(test_sll_12, sll, 0x21212121, 0x21212121, 0);
test_rr_op!(test_sll_13, sll, 0x42424242, 0x21212121, 1);
test_rr_op!(test_sll_14, sll, 0x90909080, 0x21212121, 7);
test_rr_op!(test_sll_15, sll, 0x48484000, 0x21212121, 14);
test_rr_op!(test_sll_16, sll, 0x80000000, 0x21212121, 31);
test_rr_op!(test_sll_17, sll, 0x21212121, 0x21212121, 0xFFFFFFC0);
test_rr_op!(test_sll_18, sll, 0x42424242, 0x21212121, 0xFFFFFFC1);
test_rr_op!(test_sll_19, sll, 0x90909080, 0x21212121, 0xFFFFFFC7);
test_rr_op!(test_sll_20, sll, 0x48484000, 0x21212121, 0xFFFFFFCE);
// Source/Destination tests
test_rr_src1_eq_dest!(test_sll_22, sll, 0x00000080, 0x00000001, 7);
test_rr_src2_eq_dest!(test_sll_23, sll, 0x00004000, 0x00000001, 14);
test_rr_src12_eq_dest!(test_sll_24, sll, 24, 3);
// Bypassing tests
test_rr_zerosrc1!(test_sll_40, sll, 0, 15);
test_rr_zerosrc2!(test_sll_41, sll, 32, 32);
test_rr_zerosrc12!(test_sll_42, sll, 0);
test_rr_zerodest!(test_sll_43, sll, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests For Multiply High (`mulh`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-sofware-src/riscv-tests/blob/master/isa/rv64um/mulh.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_mulh_2, mulh, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_mulh_3, mulh, 0x00000000, 0x00000001, 0x00000001);
test_rr_op!(test_mulh_4, mulh, 0x00000000, 0x00000003, 0x00000007);
test_rr_op!(test_mulh_5, mulh, 0x00000000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_mulh_6, mulh, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_mulh_7, mulh, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_mulh_30, mulh, 0xFFFF0081, 0xAAAAAAAB, 0x0002FE7D);
test_rr_op!(test_mulh_31, mulh, 0xFFFF0081, 0x0002FE7D, 0xAAAAAAAB);
test_rr_op!(test_mulh_32, mulh, 0x00010000, 0xFF000000, 0xFF000000);
test_rr_op!(test_mulh_33, mulh, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF);
test_rr_op!(test_mulh_34, mulh, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_mulh_35, mulh, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_mulh_8, mulh, 36608, 13 << 20, 11 << 20);
test_rr_src2_eq_dest!(test_mulh_9, mulh, 39424, 14 << 20, 11 << 20);
test_rr_src12_eq_dest!(test_mulh_10, mulh, 43264, 13 << 20);
// Bypassing tests
test_rr_zerosrc1!(test_mulh_26, mulh, 0, 31 << 26);
test_rr_zerosrc2!(test_mulh_27, mulh, 0, 32 << 26);
test_rr_zerosrc12!(test_mulh_28, mulh, 0);
test_rr_zerodest!(test_mulh_29, mulh, 33 << 20, 34 << 20);
// ---------------------------------------------------------------------------------------------
// Tests For Set Less Than (`slt`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/slt.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_slt_2, slt, 0, 0x00000000, 0x00000000);
test_rr_op!(test_slt_3, slt, 0, 0x00000001, 0x00000001);
test_rr_op!(test_slt_4, slt, 1, 0x00000003, 0x00000007);
test_rr_op!(test_slt_5, slt, 0, 0x00000007, 0x00000003);
test_rr_op!(test_slt_6, slt, 0, 0x00000000, 0xFFFF8000);
test_rr_op!(test_slt_7, slt, 1, 0x80000000, 0x00000000);
test_rr_op!(test_slt_8, slt, 1, 0x80000000, 0xFFFF8000);
test_rr_op!(test_slt_9, slt, 1, 0x00000000, 0x00007FFF);
test_rr_op!(test_slt_10, slt, 0, 0x7FFFFFFF, 0x00000000);
test_rr_op!(test_slt_11, slt, 0, 0x7FFFFFFF, 0x00007FFF);
test_rr_op!(test_slt_12, slt, 1, 0x80000000, 0x00007FFF);
test_rr_op!(test_slt_13, slt, 0, 0x7FFFFFFF, 0xFFFF8000);
test_rr_op!(test_slt_14, slt, 0, 0x00000000, 0xFFFFFFFF);
test_rr_op!(test_slt_15, slt, 1, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_slt_16, slt, 0, 0xFFFFFFFF, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_slt_17, slt, 0, 14, 13);
test_rr_src2_eq_dest!(test_slt_18, slt, 1, 11, 13);
test_rr_src12_eq_dest!(test_slt_19, slt, 0, 13);
// Bypassing tests
test_rr_zerosrc1!(test_slt_35, slt, 0, -1i32 as u32);
test_rr_zerosrc2!(test_slt_36, slt, 1, -1i32 as u32);
test_rr_zerosrc12!(test_slt_37, slt, 0);
test_rr_zerodest!(test_slt_38, slt, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests For Multiply High Singed and Unsigned (`mulhsu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/mulhsu.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_mulhsu_2, mulhsu, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_mulhsu_3, mulhsu, 0x00000000, 0x00000001, 0x00000001);
test_rr_op!(test_mulhsu_4, mulhsu, 0x00000000, 0x00000003, 0x00000007);
test_rr_op!(test_mulhsu_5, mulhsu, 0x00000000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_mulhsu_6, mulhsu, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_mulhsu_7, mulhsu, 0x80004000, 0x80000000, 0xFFFF8000);
test_rr_op!(test_mulhsu_30, mulhsu, 0xFFFF0081, 0xaaaaaaab, 0x0002fe7d);
test_rr_op!(test_mulhsu_31, mulhsu, 0x0001fefe, 0x0002fe7d, 0xaaaaaaab);
test_rr_op!(test_mulhsu_32, mulhsu, 0xFF010000, 0xFF000000, 0xFF000000);
test_rr_op!(test_mulhsu_33, mulhsu, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF);
test_rr_op!(test_mulhsu_34, mulhsu, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_mulhsu_35, mulhsu, 0x00000000, 0x00000001, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_mulhsu_8, mulhsu, 36608, 13 << 20, 11 << 20);
test_rr_src2_eq_dest!(test_mulhsu_9, mulhsu, 39424, 14 << 20, 11 << 20);
test_rr_src12_eq_dest!(test_mulhsu_10, mulhsu, 43264, 13 << 20);
// Bypassing tests
test_rr_zerosrc1!(test_mulhsu_26, mulhsu, 0, 31 << 26);
test_rr_zerosrc2!(test_mulhsu_27, mulhsu, 0, 32 << 26);
test_rr_zerosrc12!(test_mulhsu_28, mulhsu, 0);
test_rr_zerodest!(test_mulhsu_29, mulhsu, 33 << 20, 34 << 20);
// ---------------------------------------------------------------------------------------------
// Tests For Set Less Than Unsigned (`sltu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sltu.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_sltu_2, sltu, 0, 0x00000000, 0x00000000);
test_rr_op!(test_sltu_3, sltu, 0, 0x00000001, 0x00000001);
test_rr_op!(test_sltu_4, sltu, 1, 0x00000003, 0x00000007);
test_rr_op!(test_sltu_5, sltu, 0, 0x00000007, 0x00000003);
test_rr_op!(test_sltu_6, sltu, 1, 0x00000000, 0xFFFF8000);
test_rr_op!(test_sltu_7, sltu, 0, 0x80000000, 0x00000000);
test_rr_op!(test_sltu_8, sltu, 1, 0x80000000, 0xFFFF8000);
test_rr_op!(test_sltu_9, sltu, 1, 0x00000000, 0x00007FFF);
test_rr_op!(test_sltu_10, sltu, 0, 0x7FFFFFFF, 0x00000000);
test_rr_op!(test_sltu_11, sltu, 0, 0x7FFFFFFF, 0x00007FFF);
test_rr_op!(test_sltu_12, sltu, 0, 0x80000000, 0x00007FFF);
test_rr_op!(test_sltu_13, sltu, 1, 0x7FFFFFFF, 0xFFFF8000);
test_rr_op!(test_sltu_14, sltu, 1, 0x00000000, 0xFFFFFFFF);
test_rr_op!(test_sltu_15, sltu, 0, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_sltu_16, sltu, 0, 0xFFFFFFFF, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_sltu_17, sltu, 0, 14, 13);
test_rr_src2_eq_dest!(test_sltu_18, sltu, 1, 11, 13);
test_rr_src12_eq_dest!(test_sltu_19, sltu, 0, 13);
// Bypassing tests
test_rr_zerosrc1!(test_sltu_35, sltu, 1, -1i32 as u32);
test_rr_zerosrc2!(test_sltu_36, sltu, 0, -1i32 as u32);
test_rr_zerosrc12!(test_sltu_37, sltu, 0);
test_rr_zerodest!(test_sltu_38, sltu, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests For Multiply High Unsigned (`mulhu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/mulhu.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_mulhu_2, mulhu, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_mulhu_3, mulhu, 0x00000000, 0x00000001, 0x00000001);
test_rr_op!(test_mulhu_4, mulhu, 0x00000000, 0x00000003, 0x00000007);
test_rr_op!(test_mulhu_5, mulhu, 0x00000000, 0x00000000, 0xFFFF8000);
test_rr_op!(test_mulhu_6, mulhu, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_mulhu_7, mulhu, 0x7FFFC000, 0x80000000, 0xFFFF8000);
test_rr_op!(test_mulhu_30, mulhu, 0x0001FEFE, 0xAAAAAAAB, 0x0002FE7D);
test_rr_op!(test_mulhu_31, mulhu, 0x0001FEFE, 0x0002FE7D, 0xAAAAAAAB);
test_rr_op!(test_mulhu_32, mulhu, 0xFE010000, 0xFF000000, 0xFF000000);
test_rr_op!(test_mulhu_33, mulhu, 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF);
test_rr_op!(test_mulhu_34, mulhu, 0x00000000, 0xFFFFFFFF, 0x00000001);
test_rr_op!(test_mulhu_35, mulhu, 0x00000000, 0x00000001, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_mulhu_8, mulhu, 36608, 13 << 20, 11 << 20);
test_rr_src2_eq_dest!(test_mulhu_9, mulhu, 39424, 14 << 20, 11 << 20);
test_rr_src12_eq_dest!(test_mulhu_10, mulhu, 43264, 13 << 20);
// Bypassing tests
test_rr_zerosrc1!(test_mulhu_26, mulhu, 0, 31 << 26);
test_rr_zerosrc2!(test_mulhu_27, mulhu, 0, 32 << 26);
test_rr_zerosrc12!(test_mulhu_28, mulhu, 0);
test_rr_zerodest!(test_mulhu_29, mulhu, 33 << 20, 34 << 20);
// ---------------------------------------------------------------------------------------------
// Tests For Xor (`xor`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/xor.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_xor_2, xor, 0xF00FF00F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_op!(test_xor_3, xor, 0xFF00FF00, 0x0FF00FF0, 0xF0F0F0F0);
test_rr_op!(test_xor_4, xor, 0x0FF00FF0, 0x00FF00FF, 0x0F0F0F0F);
test_rr_op!(test_xor_5, xor, 0x00FF00FF, 0xF00FF00F, 0xF0F0F0F0);
// Source/Destination tests
test_rr_src1_eq_dest!(test_xor_6, xor, 0xF00FF00F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_src2_eq_dest!(test_xor_7, xor, 0xF00FF00F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_src12_eq_dest!(test_xor_8, xor, 0x00000000, 0xFF00FF00);
// Bypassing tests
test_rr_zerosrc1!(test_xor_24, xor, 0xFF00FF00, 0xFF00FF00);
test_rr_zerosrc2!(test_xor_25, xor, 0x00FF00FF, 0x00FF00FF);
test_rr_zerosrc12!(test_xor_26, xor, 0);
test_rr_zerodest!(test_xor_27, xor, 0x11111111, 0x22222222);
// ---------------------------------------------------------------------------------------------
// Tests For Division (`div`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/div.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_div_2, div, 3, 20, 6);
test_rr_op!(test_div_3, div, (-3i32 as u32), (-20i32 as u32), 6);
test_rr_op!(test_div_4, div, (-3i32 as u32), 20, (-6i32 as u32));
test_rr_op!(test_div_5, div, 3, (-20i32 as u32), (-6i32 as u32));
test_rr_op!(
test_div_6,
div,
(-1i32 as u32) << 31,
(-1i32 as u32) << 31,
1
);
test_rr_op!(
test_div_7,
div,
(-1i32 as u32) << 31,
(-1i32 as u32) << 31,
(-1i32 as u32)
);
test_rr_op!(test_div_8, div, (-1i32 as u32), (-1i32 as u32) << 31, 0);
test_rr_op!(test_div_9, div, (-1i32 as u32), 1, 0);
test_rr_op!(test_div_10, div, (-1i32 as u32), 0, 0);
// ---------------------------------------------------------------------------------------------
// Tests For Shift Right Logical (`srl`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/srl.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_srl_2, srl, 0x80000000 >> 0, 0x80000000, 0);
test_rr_op!(test_srl_3, srl, 0x80000000 >> 1, 0x80000000, 1);
test_rr_op!(test_srl_4, srl, 0x80000000 >> 7, 0x80000000, 7);
test_rr_op!(test_srl_5, srl, 0x80000000 >> 14, 0x80000000, 14);
test_rr_op!(test_srl_6, srl, 0x80000001 >> 31, 0x80000001, 31);
test_rr_op!(test_srl_7, srl, 0xFFFFFFFF >> 0, 0xFFFFFFFF, 0);
test_rr_op!(test_srl_8, srl, 0xFFFFFFFF >> 1, 0xFFFFFFFF, 1);
test_rr_op!(test_srl_9, srl, 0xFFFFFFFF >> 7, 0xFFFFFFFF, 7);
test_rr_op!(test_srl_10, srl, 0xFFFFFFFF >> 14, 0xFFFFFFFF, 14);
test_rr_op!(test_srl_11, srl, 0xFFFFFFFF >> 31, 0xFFFFFFFF, 31);
test_rr_op!(test_srl_12, srl, 0x21212121 >> 0, 0x21212121, 0);
test_rr_op!(test_srl_13, srl, 0x21212121 >> 1, 0x21212121, 1);
test_rr_op!(test_srl_14, srl, 0x21212121 >> 7, 0x21212121, 7);
test_rr_op!(test_srl_15, srl, 0x21212121 >> 14, 0x21212121, 14);
test_rr_op!(test_srl_16, srl, 0x21212121 >> 31, 0x21212121, 31);
test_rr_op!(test_srl_17, srl, 0x21212121, 0x21212121, 0xFFFFFFC0);
test_rr_op!(test_srl_18, srl, 0x10909090, 0x21212121, 0xFFFFFFC1);
test_rr_op!(test_srl_19, srl, 0x00424242, 0x21212121, 0xFFFFFFC7);
test_rr_op!(test_srl_20, srl, 0x00008484, 0x21212121, 0xFFFFFFCE);
test_rr_op!(test_srl_21, srl, 0x00000000, 0x21212121, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_srl_22, srl, 0x01000000, 0x80000000, 7);
test_rr_src2_eq_dest!(test_srl_23, srl, 0x00020000, 0x80000000, 14);
test_rr_src12_eq_dest!(test_srl_24, srl, 0, 7);
// Bypassing tests
test_rr_zerosrc1!(test_srl_40, srl, 0, 15);
test_rr_zerosrc2!(test_srl_41, srl, 32, 32);
test_rr_zerosrc12!(test_srl_42, srl, 0);
test_rr_zerodest!(test_srl_43, srl, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests For Division Unsigned (`divu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/divu.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_divu_2, divu, 3, 20, 6);
test_rr_op!(test_divu_3, divu, 715827879, (-20i32 as u32), 6);
test_rr_op!(test_divu_4, divu, 0, 20, (-6i32 as u32));
test_rr_op!(test_divu_5, divu, 0, (-20i32 as u32), (-6i32 as u32));
test_rr_op!(
test_divu_6,
divu,
(-1i32 as u32) << 31,
(-1i32 as u32) << 31,
1
);
test_rr_op!(test_divu_7, divu, 0, (-1i32 as u32) << 31, (-1i32 as u32));
test_rr_op!(test_divu_8, divu, (-1i32 as u32), (-1i32 as u32) << 31, 0);
test_rr_op!(test_divu_9, divu, (-1i32 as u32), 1, 0);
test_rr_op!(test_divu_10, divu, (-1i32 as u32), 0, 0);
// ---------------------------------------------------------------------------------------------
// Tests For Shift Right Arithmetic (`sra`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sra.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_sra_2, sra, 0x80000000, 0x80000000, 0);
test_rr_op!(test_sra_3, sra, 0xC0000000, 0x80000000, 1);
test_rr_op!(test_sra_4, sra, 0xFF000000, 0x80000000, 7);
test_rr_op!(test_sra_5, sra, 0xFFFE0000, 0x80000000, 14);
test_rr_op!(test_sra_6, sra, 0xFFFFFFFF, 0x80000001, 31);
test_rr_op!(test_sra_7, sra, 0x7FFFFFFF, 0x7FFFFFFF, 0);
test_rr_op!(test_sra_8, sra, 0x3FFFFFFF, 0x7FFFFFFF, 1);
test_rr_op!(test_sra_9, sra, 0x00FFFFFF, 0x7FFFFFFF, 7);
test_rr_op!(test_sra_10, sra, 0x0001FFFF, 0x7FFFFFFF, 14);
test_rr_op!(test_sra_11, sra, 0x00000000, 0x7FFFFFFF, 31);
test_rr_op!(test_sra_12, sra, 0x81818181, 0x81818181, 0);
test_rr_op!(test_sra_13, sra, 0xC0C0C0C0, 0x81818181, 1);
test_rr_op!(test_sra_14, sra, 0xFF030303, 0x81818181, 7);
test_rr_op!(test_sra_15, sra, 0xFFFE0606, 0x81818181, 14);
test_rr_op!(test_sra_16, sra, 0xFFFFFFFF, 0x81818181, 31);
test_rr_op!(test_sra_17, sra, 0x81818181, 0x81818181, 0xFFFFFFC0);
test_rr_op!(test_sra_18, sra, 0xC0C0C0C0, 0x81818181, 0xFFFFFFC1);
test_rr_op!(test_sra_19, sra, 0xFF030303, 0x81818181, 0xFFFFFFC7);
test_rr_op!(test_sra_20, sra, 0xFFFE0606, 0x81818181, 0xFFFFFFCE);
test_rr_op!(test_sra_21, sra, 0xFFFFFFFF, 0x81818181, 0xFFFFFFFF);
// Source/Destination tests
test_rr_src1_eq_dest!(test_sra_22, sra, 0xFF000000, 0x80000000, 7);
test_rr_src2_eq_dest!(test_sra_23, sra, 0xFFFE0000, 0x80000000, 14);
test_rr_src12_eq_dest!(test_sra_24, sra, 0, 7);
// Bypassing tests
test_rr_zerosrc1!(test_sra_40, sra, 0, 15);
test_rr_zerosrc2!(test_sra_41, sra, 32, 32);
test_rr_zerosrc12!(test_sra_42, sra, 0);
test_rr_zerodest!(test_sra_43, sra, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests For Or (`or`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/or.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_or_2, or, 0xFF0FFF0F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_op!(test_or_3, or, 0xFFF0FFF0, 0x0FF00FF0, 0xF0F0F0F0);
test_rr_op!(test_or_4, or, 0x0FFF0FFF, 0x00FF00FF, 0x0F0F0F0F);
test_rr_op!(test_or_5, or, 0xF0FFF0FF, 0xF00FF00F, 0xF0F0F0F0);
// Source/Destination tests
test_rr_src1_eq_dest!(test_or_6, or, 0xFF0FFF0F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_src2_eq_dest!(test_or_7, or, 0xFF0FFF0F, 0xFF00FF00, 0x0F0F0F0F);
test_rr_src12_eq_dest!(test_or_8, or, 0xFF00FF00, 0xFF00FF00);
// Bypassing tests
test_rr_zerosrc1!(test_or_24, or, 0xFF00FF00, 0xFF00FF00);
test_rr_zerosrc2!(test_or_25, or, 0x00FF00FF, 0x00FF00FF);
test_rr_zerosrc12!(test_or_26, or, 0);
test_rr_zerodest!(test_or_27, or, 0x11111111, 0x22222222);
// ---------------------------------------------------------------------------------------------
// Tests For Remainder (`rem`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64um/rem.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_rr_op!(test_rem_2, rem, 2, 20, 6);
test_rr_op!(test_rem_3, rem, (-2i32 as u32), (-20i32 as u32), 6);
test_rr_op!(test_rem_4, rem, 2, 20, (-6i32 as u32));
test_rr_op!(
test_rem_5,
rem,
(-2i32 as u32),
(-20i32 as u32),
(-6i32 as u32)
);
test_rr_op!(test_rem_6, rem, 0, (-1i32 as u32) << 31, 1);
test_rr_op!(test_rem_7, rem, 0, (-1i32 as u32) << 31, (-1i32 as u32));
test_rr_op!(
test_rem_8,
rem,
(-1i32 as u32) << 31,
(-1i32 as u32) << 31,
0
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/test_macros.rs | sw-emulator/lib/cpu/src/instr/test_macros.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
test_macros.rs
Abstract:
File contains implementation of RISCV Instruction encoding
--*/
#[cfg(test)]
mod test {
#[macro_export]
macro_rules! test_ld_op {
($test:ident, $instr:ident, $result:expr, $offset:expr, $base:expr, $data:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X14, $offset, XReg::X1);
],
0x1000 => $data,
{
XReg::X1 = $base;
},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_op {
($test:ident, $instr:ident, $result:expr, $data:expr, $imm:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X14, XReg::X1, $imm);
],
0x1000 => vec![0],
{
XReg::X1 = $data;
},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_dest_bypass {
($test:ident, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x000C
tests::addi(XReg::X6, XReg::X14, 0); // 0x0010
tests::addi(XReg::X4, XReg::X4, 1); // 0x0014
tests::addi(XReg::X5, XReg::X0, 2); // 0x0018
tests::bne(XReg::X4, XReg::X5, 0xFFE8); // 0x001C
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 1, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x000C
tests::nop(); // 0x0010
tests::addi(XReg::X6, XReg::X14, 0); // 0x0014
tests::addi(XReg::X4, XReg::X4, 1); // 0x0018
tests::addi(XReg::X5, XReg::X0, 2); // 0x001C
tests::bne(XReg::X4, XReg::X5, 0xFFE4); // 0x0020
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 2, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x000C
tests::nop(); // 0x0010
tests::nop(); // 0x0014
tests::addi(XReg::X6, XReg::X14, 0); // 0x0018
tests::addi(XReg::X4, XReg::X4, 1); // 0x001C
tests::addi(XReg::X5, XReg::X0, 2); // 0x0020
tests::bne(XReg::X4, XReg::X5, 0xFFE0); // 0x0024
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_src1_bypass {
($test:ident, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x000C
tests::addi(XReg::X4, XReg::X4, 1); // 0x0010
tests::addi(XReg::X5, XReg::X0, 2); // 0x0014
tests::bne(XReg::X4, XReg::X5, 0xFFEC); // 0x0018
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 1, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::nop(); // 0x000C
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x0010
tests::addi(XReg::X4, XReg::X4, 1); // 0x0014
tests::addi(XReg::X5, XReg::X0, 2); // 0x0018
tests::bne(XReg::X4, XReg::X5, 0xFFE8); // 0x001C
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 2, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::nop(); // 0x000C
tests::nop(); // 0x0010
tests::$instr(XReg::X14, XReg::X1, tests::sign_extend($val2)); // 0x0014
tests::addi(XReg::X4, XReg::X4, 1); // 0x0018
tests::addi(XReg::X5, XReg::X0, 2); // 0x001C
tests::bne(XReg::X4, XReg::X5, 0xFFE4); // 0x0020
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_src1_eq_dest {
($test:ident, $instr:ident, $result:expr, $data:expr, $imm:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X1, XReg::X1, $imm);
],
0x1000 => vec![0],
{
XReg::X1 = $data;
},
{
XReg::X1 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_zero_src1 {
($test:ident, $instr:ident, $result:expr, $imm:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X1, XReg::X0, $imm);
],
0x1000 => vec![0],
{},
{
XReg::X1 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_imm_zero_dest {
($test:ident, $instr:ident, $data:expr, $imm:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X0, XReg::X1, $imm);
],
0x1000 => vec![0],
{
XReg::X1 = $data;
},
{
XReg::X0 = 0;
}
);
}
};
}
#[macro_export]
macro_rules! test_st_op {
($test:ident, $ld_instr:ident, $st_instr:ident, $result:expr, $offset:expr, $base:expr, $data:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$st_instr(XReg::X2, $offset, XReg::X1);
tests::$ld_instr(XReg::X14, $offset, XReg::X1);
],
0x1000 => $data,
{
XReg::X1 = $base;
XReg::X2 = $result;
},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_r_op {
($test:ident, $instr:ident, $result:expr, $val1:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X14, XReg::X1);
],
0x1000 => vec![0],
{
XReg::X1 = $val1;
},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_op {
($test:ident, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X14, XReg::X1, XReg::X2);
],
0x1000 => vec![0],
{
XReg::X1 = $val1;
XReg::X2 = $val2;
},
{
XReg::X14 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_r_src1_eq_dest{
($test:ident, $instr:ident, $result:expr, $val1:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X1, XReg::X1);
],
0x1000 => vec![0],
{
XReg::X1 = $val1;
},
{
XReg::X1 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_src1_eq_dest{
($test:ident, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X1, XReg::X1, XReg::X2);
],
0x1000 => vec![0],
{
XReg::X1 = $val1;
XReg::X2 = $val2;
},
{
XReg::X1 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_src2_eq_dest{
($test:ident, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X2, XReg::X1, XReg::X2);
],
0x1000 => vec![0],
{
XReg::X1 = $val1;
XReg::X2 = $val2;
},
{
XReg::X2 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_src12_eq_dest{
($test:ident, $instr:ident, $result:expr, $val:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::$instr(XReg::X1, XReg::X1, XReg::X1);
],
0x1000 => vec![0],
{
XReg::X1 = $val;
},
{
XReg::X1 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_r_dest_bypass {
($test:ident, 0, $instr:ident, $result:expr, $val1:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1); // 0x000C
tests::addi(XReg::X6, XReg::X14, 0); // 0x0010
tests::addi(XReg::X4, XReg::X4, 1); // 0x0014
tests::addi(XReg::X5, XReg::X0, 2); // 0x0018
tests::bne(XReg::X4, XReg::X5, 0xFFE8); // 0x001C
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 1, $instr:ident, $result:expr, $val1:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1); // 0x000C
tests::nop(); // 0x0010
tests::addi(XReg::X6, XReg::X14, 0); // 0x0014
tests::addi(XReg::X4, XReg::X4, 1); // 0x0018
tests::addi(XReg::X5, XReg::X0, 2); // 0x001C
tests::bne(XReg::X4, XReg::X5, 0xFFE4); // 0x0020
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 2, $instr:ident, $result:expr, $val1:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::$instr(XReg::X14, XReg::X1); // 0x000C
tests::nop(); // 0x0010
tests::nop(); // 0x0014
tests::addi(XReg::X6, XReg::X14, 0); // 0x0018
tests::addi(XReg::X4, XReg::X4, 1); // 0x001C
tests::addi(XReg::X5, XReg::X0, 2); // 0x0020
tests::bne(XReg::X4, XReg::X5, 0xFFE0); // 0x0024
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_dest_bypass {
($test:ident, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0014
tests::addi(XReg::X6, XReg::X14, 0); // 0x0018
tests::addi(XReg::X4, XReg::X4, 1); // 0x001C
tests::addi(XReg::X5, XReg::X0, 2); // 0x0020
tests::bne(XReg::X4, XReg::X5, 0xFFE0); // 0x0024
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 1, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0014
tests::nop(); // 0x0018
tests::addi(XReg::X6, XReg::X14, 0); // 0x001C
tests::addi(XReg::X4, XReg::X4, 1); // 0x0020
tests::addi(XReg::X5, XReg::X0, 2); // 0x0024
tests::bne(XReg::X4, XReg::X5, 0xFFDC); // 0x0028
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
($test:ident, 2, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0014
tests::nop(); // 0x0018
tests::nop(); // 0x001C
tests::addi(XReg::X6, XReg::X14, 0); // 0x0020
tests::addi(XReg::X4, XReg::X4, 1); // 0x0024
tests::addi(XReg::X5, XReg::X0, 2); // 0x0028
tests::bne(XReg::X4, XReg::X5, 0xFFD8); // 0x002C
],
0x1000 => vec![0],
{},
{
XReg::X6 = $result;
}
);
}
};
}
#[macro_export]
macro_rules! test_rr_src12_bypass {
($test:ident, 0, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0014
tests::addi(XReg::X4, XReg::X4, 1); // 0x0018
tests::addi(XReg::X5, XReg::X0, 2); // 0x001C
tests::bne(XReg::X4, XReg::X5, 0xFFE4); // 0x0020
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 0, 1, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::nop(); // 0x0014
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0018
tests::addi(XReg::X4, XReg::X4, 1); // 0x001C
tests::addi(XReg::X5, XReg::X0, 2); // 0x0020
tests::bne(XReg::X4, XReg::X5, 0xFFE0); // 0x0024
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 0, 2, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::li0(XReg::X2, $val2); // 0x000C
tests::li1(XReg::X2, $val2); // 0x0010
tests::nop(); // 0x0014
tests::nop(); // 0x0018
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x001C
tests::addi(XReg::X4, XReg::X4, 1); // 0x0020
tests::addi(XReg::X5, XReg::X0, 2); // 0x0024
tests::bne(XReg::X4, XReg::X5, 0xFFDC); // 0x0028
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 1, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::nop(); // 0x000C
tests::li0(XReg::X2, $val2); // 0x0010
tests::li1(XReg::X2, $val2); // 0x0014
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x0018
tests::addi(XReg::X4, XReg::X4, 1); // 0x001C
tests::addi(XReg::X5, XReg::X0, 2); // 0x0020
tests::bne(XReg::X4, XReg::X5, 0xFFE0); // 0x0024
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 1, 1, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::nop(); // 0x000C
tests::li0(XReg::X2, $val2); // 0x0010
tests::li1(XReg::X2, $val2); // 0x0014
tests::nop(); // 0x0018
tests::$instr(XReg::X14, XReg::X1, XReg::X2); // 0x001C
tests::addi(XReg::X4, XReg::X4, 1); // 0x0020
tests::addi(XReg::X5, XReg::X0, 2); // 0x0024
tests::bne(XReg::X4, XReg::X5, 0xFFDC); // 0x0028
],
0x1000 => vec![0],
{},
{
XReg::X14 = $result;
}
);
}
};
($test:ident, 2, 0, $instr:ident, $result:expr, $val1:expr, $val2:expr) => {
#[test]
fn $test() {
use $crate::xreg_file::XReg;
use $crate::instr::test_encoder::tests;
$crate::isa_test!(
0x0000 => $crate::text![
tests::addi(XReg::X4, XReg::X0, 0); // 0x0000
tests::li0(XReg::X1, $val1); // 0x0004
tests::li1(XReg::X1, $val1); // 0x0008
tests::nop(); // 0x000C
tests::nop(); // 0x0010
tests::li0(XReg::X2, $val2); // 0x0014
tests::li1(XReg::X2, $val2); // 0x0018
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/jal.rs | sw-emulator/lib/cpu/src/instr/jal.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
jal.rs
Abstract:
File contains implementation of Jump and Link instructions.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32J, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvException;
impl<TBus: Bus> Cpu<TBus> {
/// Execute `jal` Instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_jal_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32J(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Jal);
// Calculate the new program counter
let next_pc = self.read_pc().wrapping_add(instr.imm());
// Calculate the return address
let lr = self.next_pc();
// Update the registers
self.set_next_pc(next_pc);
self.write_xreg(instr.rd(), lr)
}
}
#[cfg(test)]
mod tests {
use crate::instr::test_encoder::tests::{addi, jal, nop};
use crate::xreg_file::XReg;
use crate::{isa_test, text};
#[test]
fn test_jal_2() {
isa_test!(
0x0000 => text![
jal(XReg::X1, 0x0008);
nop();
addi(XReg::X2, XReg::X0, 1);
nop();
],
0x1000 => vec![0],
{
},
{
XReg::X2 = 0x0001;
XReg::X1 = 0x0004;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/branch.rs | sw-emulator/lib/cpu/src/instr/branch.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
branch.rs
Abstract:
File contains implementation of branch instructions.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32B, RvInstr32BranchFunct3, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvException;
impl<TBus: Bus> Cpu<TBus> {
/// Execute branch Instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_branch_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32B(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Branch);
let val1 = self.read_xreg(instr.rs1())?;
let val2 = self.read_xreg(instr.rs2())?;
let pc = self.read_pc();
match instr.funct3().into() {
// Branch on equal to
RvInstr32BranchFunct3::Beq => {
if val1 == val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Branch on not equal to
RvInstr32BranchFunct3::Bne => {
if val1 != val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Branch on less than
RvInstr32BranchFunct3::Blt => {
let val1 = val1 as i32;
let val2 = val2 as i32;
if val1 < val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Branch on greater than equal
RvInstr32BranchFunct3::Bge => {
let val1 = val1 as i32;
let val2 = val2 as i32;
if val1 >= val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Branch on less than unsigned
RvInstr32BranchFunct3::Bltu => {
if val1 < val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Branch on greater than unsigned
RvInstr32BranchFunct3::Bgeu => {
if val1 >= val2 {
self.set_next_pc(pc.wrapping_add(instr.imm()));
}
}
// Illegal instruction
_ => Err(RvException::illegal_instr(instr.0))?,
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::{test_br2_op_not_taken, test_br2_op_taken};
// ---------------------------------------------------------------------------------------------
// Tests For Branch on equal (`beq`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/beq.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_beq_2, beq, 0, 0);
test_br2_op_taken!(test_beq_3, beq, 1, 1);
test_br2_op_taken!(test_beq_4, beq, -1i32 as u32, -1i32 as u32);
test_br2_op_not_taken!(test_beq_5, beq, 0, 1);
test_br2_op_not_taken!(test_beq_6, beq, 1, 0);
test_br2_op_not_taken!(test_beq_7, beq, -1i32 as u32, 1);
test_br2_op_not_taken!(test_beq_8, beq, 1, -1i32 as u32);
// ---------------------------------------------------------------------------------------------
// Tests For Branch on not equal (`bne`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/bne.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_bne_2, bne, 0, 1);
test_br2_op_taken!(test_bne_3, bne, 1, 0);
test_br2_op_taken!(test_bne_4, bne, -1i32 as u32, 1);
test_br2_op_taken!(test_bne_5, bne, 1, -1i32 as u32);
test_br2_op_not_taken!(test_bne_6, bne, 0, 0);
test_br2_op_not_taken!(test_bne_7, bne, 1, 1);
test_br2_op_not_taken!(test_bne_8, bne, -1i32 as u32, -1i32 as u32);
// ---------------------------------------------------------------------------------------------
// Tests For Branch on less than (`blt`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/blt.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_blt_2, blt, 0, 1);
test_br2_op_taken!(test_blt_3, blt, -1i32 as u32, 1);
test_br2_op_taken!(test_blt_4, blt, -2i32 as u32, -1i32 as u32);
test_br2_op_not_taken!(test_blt_5, blt, 1, 0);
test_br2_op_not_taken!(test_blt_6, blt, 1, -1i32 as u32);
test_br2_op_not_taken!(test_blt_7, blt, -1i32 as u32, -2i32 as u32);
test_br2_op_not_taken!(test_blt_8, blt, 1, -2i32 as u32);
// ---------------------------------------------------------------------------------------------
// Tests For Branch on greater than equal (`bge`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/bge.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_bge_2, bge, 0, 0);
test_br2_op_taken!(test_bge_3, bge, 1, 1);
test_br2_op_taken!(test_bge_4, bge, -1i32 as u32, -1i32 as u32);
test_br2_op_taken!(test_bge_5, bge, 1, 0);
test_br2_op_taken!(test_bge_6, bge, 1, -1i32 as u32);
test_br2_op_taken!(test_bge_7, bge, -1i32 as u32, -2i32 as u32);
test_br2_op_not_taken!(test_bge_8, bge, 0, 1);
test_br2_op_not_taken!(test_bge_9, bge, -1i32 as u32, 1);
test_br2_op_not_taken!(test_bge_10, bge, -2i32 as u32, -1i32 as u32);
test_br2_op_not_taken!(test_bge_11, bge, -2i32 as u32, 1);
// ---------------------------------------------------------------------------------------------
// Tests For Branch on less than unsigned (`bltu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/bltu.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_bltu_2, bltu, 0x00000000, 0x00000001);
test_br2_op_taken!(test_bltu_3, bltu, 0xfffffffe, 0xffffffff);
test_br2_op_taken!(test_bltu_4, bltu, 0x00000000, 0xffffffff);
test_br2_op_not_taken!(test_bltu_5, bltu, 0x00000001, 0x00000000);
test_br2_op_not_taken!(test_bltu_6, bltu, 0xffffffff, 0xfffffffe);
test_br2_op_not_taken!(test_bltu_7, bltu, 0xffffffff, 0x00000000);
test_br2_op_not_taken!(test_bltu_8, bltu, 0x80000000, 0x7fffffff);
// ---------------------------------------------------------------------------------------------
// Tests For Branch on greater than equal unsigned (`bgeu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/bgeu.S
// ---------------------------------------------------------------------------------------------
test_br2_op_taken!(test_bgeu_2, bgeu, 0x00000000, 0x00000000);
test_br2_op_taken!(test_bgeu_3, bgeu, 0x00000001, 0x00000001);
test_br2_op_taken!(test_bgeu_4, bgeu, 0xffffffff, 0xffffffff);
test_br2_op_taken!(test_bgeu_5, bgeu, 0x00000001, 0x00000000);
test_br2_op_taken!(test_bgeu_6, bgeu, 0xffffffff, 0xfffffffe);
test_br2_op_taken!(test_bgeu_7, bgeu, 0xffffffff, 0x00000000);
test_br2_op_not_taken!(test_bgeu_8, bgeu, 0x00000000, 0x00000001);
test_br2_op_not_taken!(test_bgeu_9, bgeu, 0xfffffffe, 0xffffffff);
test_br2_op_not_taken!(test_bgeu_10, bgeu, 0x00000000, 0xffffffff);
test_br2_op_not_taken!(test_bgeu_11, bgeu, 0x7fffffff, 0x80000000);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/auipc.rs | sw-emulator/lib/cpu/src/instr/auipc.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
auipc.rs
Abstract:
File contains implementation of Add Upper Immediate to Program Counter (`auipc`) instruction.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32Opcode, RvInstr32U};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvData, RvException};
use std::ops::Shl;
impl<TBus: Bus> Cpu<TBus> {
/// Execute `auipc` Instruction
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_auipc_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32U(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Auipc);
// Calculate value
let imm = instr.imm().shl(12) as RvData;
let val = self.read_pc().wrapping_add(imm) as RvData;
// Save the contents to register
self.write_xreg(instr.rd(), val)
}
}
#[cfg(test)]
mod tests {
use crate::instr::test_encoder::tests::{auipc, nop};
use crate::xreg_file::XReg;
use crate::{isa_test, text};
#[test]
fn test_auipc_2() {
isa_test!(
0x0000 => text![
nop();
auipc(XReg::X10, 10000);
],
0x1000 => vec![0],
{},
{
XReg::X10 = (10000 << 12) + 4;
}
);
}
#[test]
fn test_auipc_3() {
isa_test!(
0x0000 => text![
nop();
auipc(XReg::X10, -10000);
],
0x1000 => vec![0],
{},
{
XReg::X10 = ((-10000i32 as u32) << 12) + 4;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/store.rs | sw-emulator/lib/cpu/src/instr/store.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
store.rs
Abstract:
File contains implementation of RISCV Store Instructions
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32Opcode, RvInstr32S, RvInstr32StoreFunct3};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvAddr, RvException, RvSize};
impl<TBus: Bus> Cpu<TBus> {
/// Execute store instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_store_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32S(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Store);
// Calculate the address to load the data from
let addr = (self.read_xreg(instr.rs1())? as RvAddr).wrapping_add(instr.imm() as RvAddr);
let val = self.read_xreg(instr.rs2())?;
match instr.funct3().into() {
// Store Byte ('sb') Instruction
RvInstr32StoreFunct3::Sb => self.write_bus(RvSize::Byte, addr, val),
// Store Half Word ('sh') Instruction
RvInstr32StoreFunct3::Sh => self.write_bus(RvSize::HalfWord, addr, val),
// Store Word ('sw') Instruction
RvInstr32StoreFunct3::Sw => self.write_bus(RvSize::Word, addr, val),
// Illegal Instruction
_ => Err(RvException::illegal_instr(instr.0)),
}
}
}
#[cfg(test)]
mod tests {
use crate::instr::test_encoder::tests::{addi, lb, lh, lw, sb, sh, sw};
use crate::xreg_file::XReg;
use crate::{data, db, dh, dw, isa_test, test_st_op, text};
use lazy_static::lazy_static;
// ---------------------------------------------------------------------------------------------
// Tests For Store Byte (`sb`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sb.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LB: Vec<u8> = data![
db!(0xEF); db!(0xEF); db!(0xEF); db!(0xEF); db!(0xEF);
db!(0xEF); db!(0xEF); db!(0xEF); db!(0xEF); db!(0xEF);
];
}
// Basic Tests
test_st_op!(test_sb_2, lb, sb, 0xFFFF_FFAA, 0, 0x1000, DATA_LB);
test_st_op!(test_sb_3, lb, sb, 0x0000_0000, 1, 0x1000, DATA_LB);
test_st_op!(test_sb_4, lh, sb, 0xFFFF_EFA0, 2, 0x1000, DATA_LB);
test_st_op!(test_sb_5, lb, sb, 0x0000_000A, 3, 0x1000, DATA_LB);
// Test with negative offset
test_st_op!(test_sb_6, lb, sb, 0xFFFF_FFAA, -3, 0x1003, DATA_LB);
test_st_op!(test_sb_7, lb, sb, 0x0000_0000, -2, 0x1003, DATA_LB);
test_st_op!(test_sb_8, lb, sb, 0xFFFF_FFA0, -1, 0x1003, DATA_LB);
test_st_op!(test_sb_9, lb, sb, 0x0000_000A, -0, 0x1003, DATA_LB);
// Test with negative base
#[test]
fn test_sb_10() {
isa_test!(
0x0000 => text![
addi(XReg::X4, XReg::X1, -32);
sb(XReg::X2, 32, XReg::X4);
lb(XReg::X5, 0, XReg::X1);
],
0x1000 => DATA_LB,
{
XReg::X1 = 0x0000_1000;
XReg::X2 = 0x1234_5678;
},
{
XReg::X5 = 0x0000_0078;
}
);
}
// Test with unaligned base
#[test]
fn test_sb_11() {
isa_test!(
0x0000 => text![
addi(XReg::X1, XReg::X1, -6);
sb(XReg::X2, 7, XReg::X1);
lb(XReg::X5, 0, XReg::X4);
],
0x1000 => DATA_LB,
{
XReg::X1 = 0x0000_1008;
XReg::X2 = 0x0000_3098;
XReg::X4 = 0x0000_1009;
},
{
XReg::X5 = 0xFFFF_FF98;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests For Store HalF Word (`sh`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sh.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LH: Vec<u8> = data![
dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF);
dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF); dh!(0xBEEF);
];
}
// Basic Tests
test_st_op!(test_sh_2, lh, sh, 0x000000AA, 0, 0x1000, DATA_LH);
test_st_op!(test_sh_3, lh, sh, 0xFFFFAA00, 2, 0x1000, DATA_LH);
test_st_op!(test_sh_4, lw, sh, 0xBEEF0AA0, 4, 0x1000, DATA_LH);
test_st_op!(test_sh_5, lh, sh, 0xFFFFA00A, 6, 0x1000, DATA_LH);
// Test with negative offset
test_st_op!(test_sh_6, lh, sh, 0x000000AA, -6, 0x1010, DATA_LH);
test_st_op!(test_sh_7, lh, sh, 0xFFFFAA00, -4, 0x1010, DATA_LH);
test_st_op!(test_sh_8, lh, sh, 0x00000AA0, -2, 0x1010, DATA_LH);
test_st_op!(test_sh_9, lh, sh, 0xFFFFA00A, -0, 0x1010, DATA_LH);
// Test with negative base
#[test]
fn test_sh_10() {
isa_test!(
0x0000 => text![
addi(XReg::X4, XReg::X1, -32);
sh(XReg::X2, 32, XReg::X4);
lh(XReg::X5, 0, XReg::X1);
],
0x1000 => DATA_LH,
{
XReg::X1 = 0x0000_1000;
XReg::X2 = 0x1234_5678;
},
{
XReg::X5 = 0x0000_5678;
}
);
}
// Test with unaligned base
#[test]
fn test_sh_11() {
isa_test!(
0x0000 => text![
addi(XReg::X1, XReg::X1, -5);
sh(XReg::X2, 7, XReg::X1);
lh(XReg::X5, 0, XReg::X4);
],
0x1000 => DATA_LH,
{
XReg::X1 = 0x0000_1010;
XReg::X2 = 0x0000_3098;
XReg::X4 = 0x0000_1012;
},
{
XReg::X5 = 0x0000_3098;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests For Store Word (`sw`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sw.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LW: Vec<u8> = data![
dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF);
dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF); dw!(0xDEAD_BEEF);
];
}
// Basic Tests
test_st_op!(test_sw_2, lw, sw, 0x00AA_00AA, 0, 0x1000, DATA_LW);
test_st_op!(test_sw_3, lw, sw, 0xAA00_AA00, 4, 0x1000, DATA_LW);
test_st_op!(test_sw_4, lw, sw, 0x0AA0_0AA0, 8, 0x1000, DATA_LW);
test_st_op!(test_sw_5, lw, sw, 0xA00A_A00A, 12, 0x1000, DATA_LW);
// Test with negative offset
test_st_op!(test_sw_6, lw, sw, 0x00AA_00AA, -12, 0x1010, DATA_LW);
test_st_op!(test_sw_7, lw, sw, 0xAA00_AA00, -8, 0x1010, DATA_LW);
test_st_op!(test_sw_8, lw, sw, 0x0AA0_0AA0, -4, 0x1010, DATA_LW);
test_st_op!(test_sw_9, lw, sw, 0xA00A_A00A, -0, 0x1010, DATA_LW);
// Test with negative base
#[test]
fn test_sw_10() {
isa_test!(
0x0000 => text![
addi(XReg::X4, XReg::X1, -32);
sw(XReg::X2, 32, XReg::X4);
lw(XReg::X5, 0, XReg::X1);
],
0x1000 => DATA_LW,
{
XReg::X1 = 0x0000_1010;
XReg::X2 = 0x1234_5678;
},
{
XReg::X5 = 0x1234_5678;
}
);
}
// Test with unaligned base
#[test]
fn test_sw_11() {
isa_test!(
0x0000 => text![
addi(XReg::X1, XReg::X1, -3);
sw(XReg::X2, 7, XReg::X1);
lw(XReg::X5, 0, XReg::X4);
],
0x1000 => DATA_LW,
{
XReg::X1 = 0x0000_1010;
XReg::X2 = 0x5821_3098;
XReg::X4 = 0x0000_1014;
},
{
XReg::X5 = 0x5821_3098;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/bit.rs | sw-emulator/lib/cpu/src/instr/bit.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
bit.rs
Abstract:
File contains implementation of bit manipulation instructions (Zba, Zbb, Zbc, Zbs).
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32I, RvInstr32OpFunct7, RvInstr32OpImmFunct7, RvInstr32R};
use crate::xreg_file::XReg;
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvData;
/// Carry-less multiply, low part
fn clmul(a: u32, b: u32) -> u32 {
let mut output = 0;
for i in 0..32 {
if (b >> i) & 1 == 1 {
output ^= a << i;
}
}
output
}
/// Carry-less multiply, high part
fn clmulh(a: u32, b: u32) -> u32 {
let mut output = 0;
for i in 1..32 {
if (b >> i) & 1 == 1 {
output ^= a >> (32 - i);
}
}
output
}
/// Carry-less multiply, reversed
fn clmulr(a: u32, b: u32) -> u32 {
let mut output = 0;
for i in 0..32 {
if (b >> i) & 1 == 1 {
output ^= a >> (32 - i - 1);
}
}
output
}
impl<TBus: Bus> Cpu<TBus> {
/// If this matches a bit manipulation instruction, execute it and return Some(result).
/// Otherwise, return None.
pub(crate) fn exec_bit_instr_op(
&mut self,
instr: RvInstr32R,
val1: u32,
val2: u32,
) -> Option<RvData> {
// Decode the instruction
match (RvInstr32OpFunct7::from(instr.funct7()), instr.funct3()) {
// Shift 1 and Add, sh1add
(RvInstr32OpFunct7::Sh1add, 2) => Some(val1.wrapping_shl(1).wrapping_add(val2)),
// Shift 2 and Add, sh2add
(RvInstr32OpFunct7::Sh1add, 4) => Some(val1.wrapping_shl(2).wrapping_add(val2)),
// Shift 3 and Add, sh3add
(RvInstr32OpFunct7::Sh1add, 6) => Some(val1.wrapping_shl(3).wrapping_add(val2)),
// Bit Set, bset
(RvInstr32OpFunct7::Bset, 1) => Some(val1 | (1 << (val2 & 0x1f))),
// Single-Bit Invert, binv
(RvInstr32OpFunct7::Binv, 1) => Some(val1 ^ (1 << (val2 & 0x1f))),
// Bit Clear, bclr
(RvInstr32OpFunct7::Bclr, 1) => Some(val1 & !(1 << (val2 & 0x1f))),
// Bit Extract, bext
(RvInstr32OpFunct7::Bclr, 5) => Some((val1 >> (val2 & 0x1f)) & 1),
// Carry-less multiply low part, clmul
(RvInstr32OpFunct7::MinMaxClmul, 1) => Some(clmul(val1, val2)),
// Carry-less multiply high part, clmulh
(RvInstr32OpFunct7::MinMaxClmul, 3) => Some(clmulh(val1, val2)),
// Carry-less multiply reversed, clmulr
(RvInstr32OpFunct7::MinMaxClmul, 2) => Some(clmulr(val1, val2)),
// Maximum, max
(RvInstr32OpFunct7::MinMaxClmul, 6) => Some(i32::max(val1 as i32, val2 as i32) as u32),
// Maximum unsigned, maxu
(RvInstr32OpFunct7::MinMaxClmul, 7) => Some(u32::max(val1, val2)),
// Minimum, min
(RvInstr32OpFunct7::MinMaxClmul, 4) => Some(i32::min(val1 as i32, val2 as i32) as u32),
// Minimum unsigned, min
(RvInstr32OpFunct7::MinMaxClmul, 5) => Some(u32::min(val1, val2)),
// And Invert, andn
(RvInstr32OpFunct7::Andn, 7) => Some(val1 & !val2),
// Or Invert, orn
(RvInstr32OpFunct7::Orn, 6) => Some(val1 | !val2),
// Exclusive Nor, xnor
(RvInstr32OpFunct7::Xnor, 4) => Some(!(val1 ^ val2)),
// Zero-extend halfword, zext.h
(RvInstr32OpFunct7::Zext, 4) if instr.rs2() == XReg::X0 => Some(val1 & 0xffff),
// Rotate left, rol
(RvInstr32OpFunct7::Rotate, 1) => Some(val1.rotate_left(val2 & 0x1f)),
// Rotate right, ror
(RvInstr32OpFunct7::Rotate, 5) => Some(val1.rotate_right(val2 & 0x1f)),
_ => None,
}
}
pub(crate) fn exec_bit_instr_op_imm(&mut self, instr: RvInstr32I, reg: u32) -> Option<RvData> {
// Decode the instruction
let imm = instr.imm();
match (RvInstr32OpImmFunct7::from(instr.funct7()), instr.funct3()) {
// Bit Set Immediate, bseti
(RvInstr32OpImmFunct7::Orc, 1) => Some(reg | (1 << (imm & 0x1f))),
// Bitwise OR-Combine byte granule, orc.b
(RvInstr32OpImmFunct7::Orc, 5) if instr.funct5() == 0b0_0111 => {
let reg_bytes = reg.to_le_bytes();
Some(u32::from_le_bytes(core::array::from_fn(|i| {
if reg_bytes[i] != 0 {
0xff
} else {
0x00
}
})))
}
// Single-Bit Invert Immediate, bseti
(RvInstr32OpImmFunct7::Rev8, 1) => Some(reg ^ (1 << (imm & 0x1f))),
// Bit Clear Immediate, bclri
(RvInstr32OpImmFunct7::Bclr, 1) => Some(reg & !(1 << (imm & 0x1f))),
// Bit Extract Immediate, bexti
(RvInstr32OpImmFunct7::Bclr, 5) => Some((reg >> (imm & 0x1f)) & 1),
// Rotate Right Immediate, rori
(RvInstr32OpImmFunct7::Bitmanip, 5) => Some(reg.rotate_right(instr.shamt())),
// Count leading zeroes, clz
(RvInstr32OpImmFunct7::Bitmanip, 1) if instr.funct5() == 0b0_0000 => {
Some(reg.leading_zeros())
}
// Count trailing zeroes, ctz
(RvInstr32OpImmFunct7::Bitmanip, 1) if instr.funct5() == 0b0_0001 => {
Some(reg.trailing_zeros())
}
// Count set bits, cpop
(RvInstr32OpImmFunct7::Bitmanip, 1) if instr.funct5() == 0b0_0010 => {
Some(reg.count_ones())
}
// Sign-extend byte, sext.b
(RvInstr32OpImmFunct7::Bitmanip, 1) if instr.funct5() == 0b0_0100 => {
Some(reg as i8 as i32 as u32)
}
// Sign-extend halfword, sext.h
(RvInstr32OpImmFunct7::Bitmanip, 1) if instr.funct5() == 0b0_0101 => {
Some(reg as i16 as i32 as u32)
}
// Byte-reverse register
(RvInstr32OpImmFunct7::Rev8, 5) if instr.funct5() == 0b1_1000 => Some(reg.swap_bytes()),
_ => None,
}
}
}
#[cfg(test)]
#[allow(clippy::identity_op)]
#[rustfmt::skip]
mod tests {
use crate::{
test_imm_dest_bypass, test_imm_op, test_imm_src1_bypass, test_imm_src1_eq_dest, test_imm_zero_dest, test_imm_zero_src1, test_r_dest_bypass, test_r_op, test_r_src1_eq_dest, test_rr_dest_bypass, test_rr_op, test_rr_src12_bypass, test_rr_src12_eq_dest, test_rr_src1_eq_dest, test_rr_src21_bypass, test_rr_src2_eq_dest, test_rr_zerodest, test_rr_zerosrc1, test_rr_zerosrc12, test_rr_zerosrc2
};
// ---------------------------------------------------------------------------------------------
// Tests for Shift 1 Add (`sh1add`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv32uzba/sh1add.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_sh1add_2, sh1add, 0x0000_0000, 0x0000_0000, 0x0000_0000);
test_rr_op!(test_sh1add_3, sh1add, 0x0000_0003, 0x0000_0001, 0x0000_0001);
test_rr_op!(test_sh1add_4, sh1add, 0x0000_000d, 0x0000_0003, 0x0000_0007);
test_rr_op!(test_sh1add_5, sh1add, 0xffff_8000, 0x0000_0000, 0xffff_8000);
test_rr_op!(test_sh1add_6, sh1add, 0x0000_0000, 0x8000_0000, 0x0000_0000);
test_rr_op!(test_sh1add_7, sh1add, 0xffff_8000, 0x8000_0000, 0xffff_8000);
test_rr_op!(test_sh1add_8, sh1add, 0x0000_7fff, 0x0000_0000, 0x0000_7fff);
test_rr_op!(test_sh1add_9, sh1add, 0xffff_fffe, 0x7fff_ffff, 0x0000_0000);
test_rr_op!(test_sh1add_10, sh1add, 0x0000_7ffd, 0x7fff_ffff, 0x0000_7fff);
test_rr_op!(test_sh1add_11, sh1add, 0x0000_7fff, 0x8000_0000, 0x0000_7fff);
test_rr_op!(test_sh1add_12, sh1add, 0xffff_7ffe, 0x7fff_ffff, 0xffff_8000);
test_rr_op!(test_sh1add_13, sh1add, 0xffff_ffff, 0x0000_0000, 0xffff_ffff);
test_rr_op!(test_sh1add_14, sh1add, 0xffff_ffff, 0xffff_ffff, 0x0000_0001);
test_rr_op!(test_sh1add_15, sh1add, 0xffff_fffd, 0xffff_ffff, 0xffff_ffff);
test_rr_op!(test_sh1add_16, sh1add, 0x8000_0001, 0x0000_0001, 0x7fff_ffff);
test_rr_src1_eq_dest!(test_sh1add_17, sh1add, 37, 13, 11);
test_rr_src2_eq_dest!(test_sh1add_18, sh1add, 39, 14, 11);
test_rr_src12_eq_dest!(test_sh1add_19, sh1add, 39, 13);
test_rr_dest_bypass!(test_sh1add_20, 0 , sh1add, 37, 13, 11);
test_rr_dest_bypass!(test_sh1add_21, 1 , sh1add, 39, 14, 11);
test_rr_dest_bypass!(test_sh1add_22, 2 , sh1add, 41, 15, 11);
test_rr_src12_bypass!(test_sha1add_23, 0, 0, sh1add, 37, 13, 11);
test_rr_src12_bypass!(test_sha1add_24, 0, 1, sh1add, 39, 14, 11);
test_rr_src12_bypass!(test_sha1add_25, 0, 2, sh1add, 41, 15, 11);
test_rr_src12_bypass!(test_sha1add_26, 1, 0, sh1add, 37, 13, 11);
test_rr_src12_bypass!(test_sha1add_27, 1, 1, sh1add, 39, 14, 11);
test_rr_src12_bypass!(test_sha1add_28, 2, 0, sh1add, 41, 15, 11);
test_rr_src21_bypass!(test_sha1add_29, 0, 0, sh1add, 37, 13, 11);
test_rr_src21_bypass!(test_sha1add_30, 0, 1, sh1add, 39, 14, 11);
test_rr_src21_bypass!(test_sha1add_31, 0, 2, sh1add, 41, 15, 11);
test_rr_src21_bypass!(test_sha1add_32, 1, 0, sh1add, 37, 13, 11);
test_rr_src21_bypass!(test_sha1add_33, 1, 1, sh1add, 39, 14, 11);
test_rr_src21_bypass!(test_sha1add_34, 2, 0, sh1add, 41, 15, 11);
test_rr_zerosrc1!(test_sh1add_35, sh1add, 15, 15);
test_rr_zerosrc2!(test_sh1add_36, sh1add, 64, 32);
test_rr_zerosrc12!(test_sh1add_37, sh1add, 0);
test_rr_zerodest!(test_sh1add_38, sh1add, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests for Shift 2 Add (`sh2add`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv32uzba/sh2add.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_sh2add_2, sh2add, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_sh2add_3, sh2add, 0x00000005, 0x00000001, 0x00000001);
test_rr_op!(test_sh2add_4, sh2add, 0x00000013, 0x00000003, 0x00000007);
test_rr_op!(test_sh2add_5, sh2add, 0xffff8000, 0x00000000, 0xffff8000);
test_rr_op!(test_sh2add_6, sh2add, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_sh2add_7, sh2add, 0xffff8000, 0x80000000, 0xffff8000);
test_rr_op!(test_sh2add_8, sh2add, 0x00007fff, 0x00000000, 0x00007fff);
test_rr_op!(test_sh2add_9, sh2add, 0xfffffffc, 0x7fffffff, 0x00000000);
test_rr_op!(test_sh2add_10, sh2add, 0x00007ffb, 0x7fffffff, 0x00007fff);
test_rr_op!(test_sh2add_11, sh2add, 0x00007fff, 0x80000000, 0x00007fff);
test_rr_op!(test_sh2add_12, sh2add, 0xffff7ffc, 0x7fffffff, 0xffff8000);
test_rr_op!(test_sh2add_13, sh2add, 0xffffffff, 0x00000000, 0xffffffff);
test_rr_op!(test_sh2add_14, sh2add, 0xfffffffd, 0xffffffff, 0x00000001);
test_rr_op!(test_sh2add_15, sh2add, 0xfffffffb, 0xffffffff, 0xffffffff);
test_rr_op!(test_sh2add_16, sh2add, 0x80000003, 0x00000001, 0x7fffffff);
test_rr_src1_eq_dest!(test_sh2add_17, sh2add, 63, 13, 11);
test_rr_src2_eq_dest!(test_sh2add_18, sh2add, 67, 14, 11);
test_rr_src12_eq_dest!(test_sh2add_19, sh2add, 65, 13);
test_rr_dest_bypass!(test_sh2add_20, 0, sh2add, 63, 13, 11);
test_rr_dest_bypass!(test_sh2add_21, 1, sh2add, 67, 14, 11);
test_rr_dest_bypass!(test_sh2add_22, 2, sh2add, 71, 15, 11);
test_rr_src12_bypass!(test_sh2add_23, 0, 0, sh2add, 63, 13, 11);
test_rr_src12_bypass!(test_sh2add_24, 0, 1, sh2add, 67, 14, 11);
test_rr_src12_bypass!(test_sh2add_25, 0, 2, sh2add, 71, 15, 11);
test_rr_src12_bypass!(test_sh2add_26, 1, 0, sh2add, 63, 13, 11);
test_rr_src12_bypass!(test_sh2add_27, 1, 1, sh2add, 67, 14, 11);
test_rr_src12_bypass!(test_sh2add_28, 2, 0, sh2add, 71, 15, 11);
test_rr_src21_bypass!(test_sh2add_29, 0, 0, sh2add, 63, 13, 11);
test_rr_src21_bypass!(test_sh2add_30, 0, 1, sh2add, 67, 14, 11);
test_rr_src21_bypass!(test_sh2add_31, 0, 2, sh2add, 71, 15, 11);
test_rr_src21_bypass!(test_sh2add_32, 1, 0, sh2add, 63, 13, 11);
test_rr_src21_bypass!(test_sh2add_33, 1, 1, sh2add, 67, 14, 11);
test_rr_src21_bypass!(test_sh2add_34, 2, 0, sh2add, 71, 15, 11);
test_rr_zerosrc1!(test_sh2add_35, sh2add, 15, 15);
test_rr_zerosrc2!(test_sh2add_36, sh2add, 128, 32);
test_rr_zerosrc12!(test_sh2add_37, sh2add, 0);
test_rr_zerodest!(test_sh2add_38, sh2add, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests for Shift 3 Add (`sh3add`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv32uzba/sh3add.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_sh3add_2, sh3add, 0x00000000, 0x00000000, 0x00000000);
test_rr_op!(test_sh3add_3, sh3add, 0x00000009, 0x00000001, 0x00000001);
test_rr_op!(test_sh3add_4, sh3add, 0x0000001f, 0x00000003, 0x00000007);
test_rr_op!(test_sh3add_5, sh3add, 0xffff8000, 0x00000000, 0xffff8000);
test_rr_op!(test_sh3add_6, sh3add, 0x00000000, 0x80000000, 0x00000000);
test_rr_op!(test_sh3add_7, sh3add, 0xffff8000, 0x80000000, 0xffff8000);
test_rr_op!(test_sh3add_8, sh3add, 0x00007fff, 0x00000000, 0x00007fff);
test_rr_op!(test_sh3add_9, sh3add, 0xfffffff8, 0x7fffffff, 0x00000000);
test_rr_op!(test_sh3add_10, sh3add, 0x00007ff7, 0x7fffffff, 0x00007fff);
test_rr_op!(test_sh3add_11, sh3add, 0x00007fff, 0x80000000, 0x00007fff);
test_rr_op!(test_sh3add_12, sh3add, 0xffff7ff8, 0x7fffffff, 0xffff8000);
test_rr_op!(test_sh3add_13, sh3add, 0xffffffff, 0x00000000, 0xffffffff);
test_rr_op!(test_sh3add_14, sh3add, 0xfffffff9, 0xffffffff, 0x00000001);
test_rr_op!(test_sh3add_15, sh3add, 0xfffffff7, 0xffffffff, 0xffffffff);
test_rr_op!(test_sh3add_16, sh3add, 0x80000007, 0x00000001, 0x7fffffff);
test_rr_src1_eq_dest!(test_sh3add_17, sh3add, 115, 13, 11);
test_rr_src2_eq_dest!(test_sh3add_18, sh3add, 123, 14, 11);
test_rr_src12_eq_dest!(test_sh3add_19, sh3add, 117, 13);
test_rr_dest_bypass!(test_sh3add_20, 0, sh3add, 115, 13, 11);
test_rr_dest_bypass!(test_sh3add_21, 1, sh3add, 123, 14, 11);
test_rr_dest_bypass!(test_sh3add_22, 2, sh3add, 131, 15, 11);
test_rr_src12_bypass!(test_sh3add_23, 0, 0, sh3add, 115, 13, 11);
test_rr_src12_bypass!(test_sh3add_24, 0, 1, sh3add, 123, 14, 11);
test_rr_src12_bypass!(test_sh3add_25, 0, 2, sh3add, 131, 15, 11);
test_rr_src12_bypass!(test_sh3add_26, 1, 0, sh3add, 115, 13, 11);
test_rr_src12_bypass!(test_sh3add_27, 1, 1, sh3add, 123, 14, 11);
test_rr_src12_bypass!(test_sh3add_28, 2, 0, sh3add, 131, 15, 11);
test_rr_src21_bypass!(test_sh3add_29, 0, 0, sh3add, 115, 13, 11);
test_rr_src21_bypass!(test_sh3add_30, 0, 1, sh3add, 123, 14, 11);
test_rr_src21_bypass!(test_sh3add_31, 0, 2, sh3add, 131, 15, 11);
test_rr_src21_bypass!(test_sh3add_32, 1, 0, sh3add, 115, 13, 11);
test_rr_src21_bypass!(test_sh3add_33, 1, 1, sh3add, 123, 14, 11);
test_rr_src21_bypass!(test_sh3add_34, 2, 0, sh3add, 131, 15, 11);
test_rr_zerosrc1!(test_sh3add_35, sh3add, 15, 15);
test_rr_zerosrc2!(test_sh3add_36, sh3add, 256, 32);
test_rr_zerosrc12!(test_sh3add_37, sh3add, 0);
test_rr_zerodest!(test_sh3add_38, sh3add, 16, 30);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Set (`bset`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bset.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_bset_2, bset, 0xff00ff01, 0xff00ff00, 0);
test_rr_op!(test_bset_3, bset, 0x00ff00ff, 0x00ff00ff, 1);
test_rr_op!(test_bset_4, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_op!(test_bset_5, bset, 0x0ff04ff0, 0x0ff00ff0, 14);
test_rr_op!(test_bset_6, bset, 0x0ff00ff0, 0x0ff00ff0, 27);
test_rr_op!(test_bset_7, bset, 0x00000001, 0x00000001, 0);
test_rr_op!(test_bset_8, bset, 0x00000003, 0x00000001, 1);
test_rr_op!(test_bset_9, bset, 0x00000081, 0x00000001, 7);
test_rr_op!(test_bset_10, bset, 0x00004001, 0x00000001, 14);
test_rr_op!(test_bset_11, bset, 0x80000001, 0x00000001, 31);
test_rr_op!(test_bset_12, bset, 0x21212121, 0x21212121, 0);
test_rr_op!(test_bset_13, bset, 0x21212123, 0x21212121, 1);
test_rr_op!(test_bset_14, bset, 0x212121a1, 0x21212121, 7);
test_rr_op!(test_bset_15, bset, 0x21212121, 0x21212121, 13);
test_rr_op!(test_bset_16, bset, 0x84848484, 0x84848484, 31);
test_rr_op!(test_bset_17, bset, 0x21212121, 0x21212121, 0xffffffc0);
test_rr_op!(test_bset_18, bset, 0x21212123, 0x21212121, 0xffffffc1);
test_rr_op!(test_bset_19, bset, 0x212121a1, 0x21212121, 0xffffffc7);
test_rr_op!(test_bset_20, bset, 0x8484c484, 0x84848484, 0xffffffce);
test_rr_src1_eq_dest!(test_bset_22, bset, 0x00000081, 0x00000001, 7);
test_rr_src2_eq_dest!(test_bset_23, bset, 0x00005551, 0x00005551, 14);
test_rr_src12_eq_dest!(test_bset_24, bset, 11, 3);
test_rr_dest_bypass!(test_bset_25, 0, bset, 0xff00ff01, 0xff00ff00, 0);
test_rr_dest_bypass!(test_bset_26, 1, bset, 0x00ff00ff, 0x00ff00ff, 1);
test_rr_dest_bypass!(test_bset_27, 2, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bset_28, 0, 0, bset, 0xff00ff01, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bset_29, 0, 1, bset, 0x00ff00ff, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bset_30, 0, 2, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bset_31, 1, 0, bset, 0xff00ff01, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bset_32, 1, 1, bset, 0x00ff00ff, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bset_33, 2, 0, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bset_34, 0, 0, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bset_35, 0, 1, bset, 0x0ff04ff0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bset_36, 0, 2, bset, 0x0ff00ff0, 0x0ff00ff0, 27);
test_rr_src21_bypass!(test_bset_37, 1, 0, bset, 0xff00ff00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bset_38, 1, 1, bset, 0x0ff04ff0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bset_39, 2, 0, bset, 0x0ff00ff0, 0x0ff00ff0, 27);
test_rr_zerosrc1!(test_bset_40, bset, 0x00008000, 15);
test_rr_zerosrc2!(test_bset_41, bset, 33, 32);
test_rr_zerosrc12!(test_bset_42, bset, 1);
test_rr_zerodest!(test_bset_43, bset, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Clear (`bclr`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bclr.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_bclr_2, bclr, 0xff00ff00, 0xff00ff00, 0);
test_rr_op!(test_bclr_3, bclr, 0x00ff00fd, 0x00ff00ff, 1);
test_rr_op!(test_bclr_4, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_op!(test_bclr_5, bclr, 0x0ff00ff0, 0x0ff00ff0, 14);
test_rr_op!(test_bclr_6, bclr, 0x07f00ff0, 0x0ff00ff0, 27);
test_rr_op!(test_bclr_7, bclr, 0xfffffffe, 0xffffffff, 0);
test_rr_op!(test_bclr_8, bclr, 0xfffffffd, 0xffffffff, 1);
test_rr_op!(test_bclr_9, bclr, 0xffffff7f, 0xffffffff, 7);
test_rr_op!(test_bclr_10, bclr, 0xffffbfff, 0xffffffff, 14);
test_rr_op!(test_bclr_11, bclr, 0xf7ffffff, 0xffffffff, 27);
test_rr_op!(test_bclr_12, bclr, 0x21212120, 0x21212121, 0);
test_rr_op!(test_bclr_13, bclr, 0x21212121, 0x21212121, 1);
test_rr_op!(test_bclr_14, bclr, 0x21212121, 0x21212121, 7);
test_rr_op!(test_bclr_15, bclr, 0x21210121, 0x21212121, 13);
test_rr_op!(test_bclr_16, bclr, 0x04848484, 0x84848484, 31);
// Verify that shifts only use bottom five (rv32) bits
test_rr_op!(test_bclr_17, bclr, 0x21212120, 0x21212121, 0xffffffc0);
test_rr_op!(test_bclr_18, bclr, 0x21212121, 0x21212121, 0xffffffc1);
test_rr_op!(test_bclr_19, bclr, 0x21212121, 0x21212121, 0xffffffc7);
test_rr_op!(test_bclr_20, bclr, 0x84848484, 0x84848484, 0xffffffce);
test_rr_src1_eq_dest!(test_bclr_22, bclr, 0x00000001, 0x00000001, 7);
test_rr_src2_eq_dest!(test_bclr_23, bclr, 0x00001551, 0x00005551, 14);
test_rr_src12_eq_dest!(test_bclr_24, bclr, 3, 3);
test_rr_dest_bypass!(test_bclr_25, 0, bclr, 0xff00ff00, 0xff00ff00, 0);
test_rr_dest_bypass!(test_bclr_26, 1, bclr, 0x00ff00fd, 0x00ff00ff, 1);
test_rr_dest_bypass!(test_bclr_27, 2, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bclr_28, 0, 0, bclr, 0xff00ff00, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bclr_29, 0, 1, bclr, 0x00ff00fd, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bclr_30, 0, 2, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bclr_31, 1, 0, bclr, 0xff00ff00, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bclr_32, 1, 1, bclr, 0x00ff00fd, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bclr_33, 2, 0, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bclr_34, 0, 0, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bclr_35, 0, 1, bclr, 0x0ff00ff0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bclr_36, 0, 2, bclr, 0x07f00ff0, 0x0ff00ff0, 27);
test_rr_src21_bypass!(test_bclr_37, 1, 0, bclr, 0xff00fe00, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bclr_38, 1, 1, bclr, 0x0ff00ff0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bclr_39, 2, 0, bclr, 0x07f00ff0, 0x0ff00ff0, 27);
test_rr_zerosrc1!(test_bclr_40, bclr, 0, 15);
test_rr_zerosrc2!(test_bclr_41, bclr, 32, 32);
test_rr_zerosrc12!(test_bclr_42, bclr, 0);
test_rr_zerodest!(test_bclr_43, bclr, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Extract (`bext`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bext.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_bext_2, bext, 0, 0xff00ff00, 0);
test_rr_op!(test_bext_3, bext, 1, 0x00ff00ff, 1);
test_rr_op!(test_bext_4, bext, 1, 0xff00ff00, 8);
test_rr_op!(test_bext_5, bext, 0, 0x0ff00ff0, 14);
test_rr_op!(test_bext_6, bext, 1, 0x0ff00ff0, 27);
test_rr_op!(test_bext_7, bext, 1, 0xffffffff, 0);
test_rr_op!(test_bext_8, bext, 1, 0xffffffff, 1);
test_rr_op!(test_bext_9, bext, 1, 0xffffffff, 7);
test_rr_op!(test_bext_10, bext, 1, 0xffffffff, 14);
test_rr_op!(test_bext_11, bext, 1, 0xffffffff, 27);
test_rr_op!(test_bext_12, bext, 1, 0x21212121, 0);
test_rr_op!(test_bext_13, bext, 0, 0x21212121, 1);
test_rr_op!(test_bext_14, bext, 0, 0x21212121, 7);
test_rr_op!(test_bext_15, bext, 1, 0x21212121, 13);
test_rr_op!(test_bext_16, bext, 1, 0x84848484, 31);
// Verify that shifts only use bottom five bits
test_rr_op!(test_bext_17, bext, 1, 0x21212121, 0xffffffc0);
test_rr_op!(test_bext_18, bext, 0, 0x21212121, 0xffffffc1);
test_rr_op!(test_bext_19, bext, 0, 0x21212121, 0xffffffc7);
test_rr_op!(test_bext_20, bext, 0, 0x84848484, 0xffffffce);
test_rr_src1_eq_dest!(test_bext_22, bext, 0, 0x00000001, 7);
test_rr_src2_eq_dest!(test_bext_23, bext, 1, 0x00005551, 14);
test_rr_src12_eq_dest!(test_bext_24, bext, 0, 3);
test_rr_dest_bypass!(test_bext_25, 0, bext, 0, 0xff00ff00, 0);
test_rr_dest_bypass!(test_bext_26, 1, bext, 1, 0x00ff00ff, 1);
test_rr_dest_bypass!(test_bext_27, 2, bext, 1, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bext_28, 0, 0, bext, 0, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bext_29, 0, 1, bext, 1, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bext_30, 0, 2, bext, 1, 0xff00ff00, 8);
test_rr_src12_bypass!(test_bext_31, 1, 0, bext, 0, 0xff00ff00, 0);
test_rr_src12_bypass!(test_bext_32, 1, 1, bext, 1, 0x00ff00ff, 1);
test_rr_src12_bypass!(test_bext_33, 2, 0, bext, 1, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bext_34, 0, 0, bext, 1, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bext_35, 0, 1, bext, 0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bext_36, 0, 2, bext, 1, 0x0ff00ff0, 27);
test_rr_src21_bypass!(test_bext_37, 1, 0, bext, 1, 0xff00ff00, 8);
test_rr_src21_bypass!(test_bext_38, 1, 1, bext, 0, 0x0ff00ff0, 14);
test_rr_src21_bypass!(test_bext_39, 2, 0, bext, 1, 0x0ff00ff0, 27);
test_rr_zerosrc1!(test_bext_40, bext, 0, 15);
test_rr_zerosrc2!(test_bext_41, bext, 0, 32);
test_rr_zerosrc12!(test_bext_42, bext, 0);
test_rr_zerodest!(test_bext_43, bext, 1024, 2048);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Set Immediate (`bseti`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bseti.S
// ---------------------------------------------------------------------------------------------
test_imm_op!(test_bseti_2, bseti, 0xff00ff01, 0xff00ff00, 0);
test_imm_op!(test_bseti_3, bseti, 0x00ff00ff, 0x00ff00ff, 1);
test_imm_op!(test_bseti_4, bseti, 0xff00ff00, 0xff00ff00, 8);
test_imm_op!(test_bseti_5, bseti, 0x0ff04ff0, 0x0ff00ff0, 14);
test_imm_op!(test_bseti_6, bseti, 0x0ff00ff0, 0x0ff00ff0, 27);
test_imm_op!(test_bseti_7, bseti, 0x00000001, 0x00000001, 0);
test_imm_op!(test_bseti_8, bseti, 0x00000003, 0x00000001, 1);
test_imm_op!(test_bseti_9, bseti, 0x00000081, 0x00000001, 7);
test_imm_op!(test_bseti_10, bseti, 0x00004001, 0x00000001, 14);
test_imm_op!(test_bseti_11, bseti, 0x80000001, 0x00000001, 31);
test_imm_op!(test_bseti_12, bseti, 0x21212121, 0x21212121, 0);
test_imm_op!(test_bseti_13, bseti, 0x21212123, 0x21212121, 1);
test_imm_op!(test_bseti_14, bseti, 0x212121a1, 0x21212121, 7);
test_imm_op!(test_bseti_15, bseti, 0x21212121, 0x21212121, 13);
test_imm_op!(test_bseti_16, bseti, 0x84848484, 0x84848484, 31);
test_imm_src1_eq_dest!(test_bseti_17, bseti, 0x00000081, 0x00000001, 7);
test_imm_dest_bypass!(test_bseti_18, 0, bseti, 0xff00ff01, 0xff00ff00, 0);
test_imm_dest_bypass!(test_bseti_19, 1, bseti, 0x00ff00ff, 0x00ff00ff, 1);
test_imm_dest_bypass!(test_bseti_20, 2, bseti, 0xff00ff00, 0xff00ff00, 8);
test_imm_src1_bypass!(test_bseti_21, 0, bseti, 0xff00ff00, 0xff00ff00, 8);
test_imm_src1_bypass!(test_bseti_22, 1, bseti, 0x0ff04ff0, 0x0ff00ff0, 14);
test_imm_src1_bypass!(test_bseti_23, 2, bseti, 0x0ff00ff0, 0x0ff00ff0, 27);
test_imm_zero_src1!(test_bseti_24, bseti, 0x00008000, 15);
test_imm_zero_dest!(test_bseti_25, bseti, 1024, 10);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Clear Immediate (`bclri`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bclri.S
// ---------------------------------------------------------------------------------------------
test_imm_op!(test_bclri_2, bclri, 0xff00ff00, 0xff00ff00, 0);
test_imm_op!(test_bclri_3, bclri, 0x00ff00fd, 0x00ff00ff, 1);
test_imm_op!(test_bclri_4, bclri, 0xff00fe00, 0xff00ff00, 8);
test_imm_op!(test_bclri_5, bclri, 0x0ff00ff0, 0x0ff00ff0, 14);
test_imm_op!(test_bclri_6, bclri, 0x07f00ff0, 0x0ff00ff0, 27);
test_imm_op!(test_bclri_7, bclri, 0xfffffffe, 0xffffffff, 0);
test_imm_op!(test_bclri_8, bclri, 0xfffffffd, 0xffffffff, 1);
test_imm_op!(test_bclri_9, bclri, 0xffffff7f, 0xffffffff, 7);
test_imm_op!(test_bclri_10, bclri, 0xffffbfff, 0xffffffff, 14);
test_imm_op!(test_bclri_11, bclri, 0xf7ffffff, 0xffffffff, 27);
test_imm_op!(test_bclri_12, bclri, 0x21212120, 0x21212121, 0);
test_imm_op!(test_bclri_13, bclri, 0x21212121, 0x21212121, 1);
test_imm_op!(test_bclri_14, bclri, 0x21212121, 0x21212121, 7);
test_imm_op!(test_bclri_15, bclri, 0x21210121, 0x21212121, 13);
test_imm_op!(test_bclri_16, bclri, 0x04848484, 0x84848484, 31);
test_imm_src1_eq_dest!(test_bclri_17, bclri, 0x00000001, 0x00000001, 7);
test_imm_dest_bypass!(test_bclri_18, 0, bclri, 0xff00fe00, 0xff00ff00, 8);
test_imm_dest_bypass!(test_bclri_19, 1, bclri, 0x0ff00ff0, 0x0ff00ff0, 14);
test_imm_dest_bypass!(test_bclri_20, 2, bclri, 0x07f00ff0, 0x0ff00ff0, 27);
test_imm_src1_bypass!(test_bclri_21, 0, bclri, 0xff00fe00, 0xff00ff00, 8);
test_imm_src1_bypass!(test_bclri_22, 1, bclri, 0x0ff00ff0, 0x0ff00ff0, 14);
test_imm_src1_bypass!(test_bclri_23, 2, bclri, 0x07f00ff0, 0x0ff00ff0, 27);
test_imm_zero_src1!(test_bclri_24, bclri, 0, 31);
test_imm_zero_dest!(test_bclri_25, bclri, 33, 20);
// ---------------------------------------------------------------------------------------------
// Tests for Bit Extract Immediate (`bexti`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbs/bexti.S
// ---------------------------------------------------------------------------------------------
test_imm_op!(test_bexti_2, bexti, 0, 0xff00ff00, 0);
test_imm_op!(test_bexti_3, bexti, 1, 0x00ff00ff, 1);
test_imm_op!(test_bexti_4, bexti, 1, 0xff00ff00, 8);
test_imm_op!(test_bexti_5, bexti, 0, 0x0ff00ff0, 14);
test_imm_op!(test_bexti_6, bexti, 1, 0x0ff00ff0, 27);
test_imm_op!(test_bexti_7, bexti, 1, 0xffffffff, 0);
test_imm_op!(test_bexti_8, bexti, 1, 0xffffffff, 1);
test_imm_op!(test_bexti_9, bexti, 1, 0xffffffff, 7);
test_imm_op!(test_bexti_10, bexti, 1, 0xffffffff, 14);
test_imm_op!(test_bexti_11, bexti, 1, 0xffffffff, 27);
test_imm_op!(test_bexti_12, bexti, 1, 0x21212121, 0);
test_imm_op!(test_bexti_13, bexti, 0, 0x21212121, 1);
test_imm_op!(test_bexti_14, bexti, 0, 0x21212121, 7);
test_imm_op!(test_bexti_15, bexti, 1, 0x21212121, 13);
test_imm_op!(test_bexti_16, bexti, 1, 0x84848484, 31);
test_imm_src1_eq_dest!(test_bexti_17, bexti, 0, 0x00000001, 7);
test_imm_dest_bypass!(test_bexti_18, 0, bexti, 1, 0xff00ff00, 8);
test_imm_dest_bypass!(test_bexti_19, 1, bexti, 0, 0x0ff00ff0, 14);
test_imm_dest_bypass!(test_bexti_20, 2, bexti, 1, 0x0ff00ff0, 27);
test_imm_src1_bypass!(test_bexti_21, 0, bexti, 1, 0xff00ff00, 8);
test_imm_src1_bypass!(test_bexti_22, 1, bexti, 0, 0x0ff00ff0, 14);
test_imm_src1_bypass!(test_bexti_23, 2, bexti, 1, 0x0ff00ff0, 27);
test_imm_zero_src1!(test_bexti_24, bexti, 0, 31);
test_imm_zero_dest!(test_bexti_25, bexti, 33, 20);
// ---------------------------------------------------------------------------------------------
// Tests for And Invert (`andn`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64uzbb/andn.S
// ---------------------------------------------------------------------------------------------
test_rr_op!(test_andn_2, andn, 0xf000f000, 0xff00ff00, 0x0f0f0f0f);
test_rr_op!(test_andn_3, andn, 0x0f000f00, 0x0ff00ff0, 0xf0f0f0f0);
test_rr_op!(test_andn_4, andn, 0x00f000f0, 0x00ff00ff, 0x0f0f0f0f);
test_rr_op!(test_andn_5, andn, 0x000f000f, 0xf00ff00f, 0xf0f0f0f0);
test_rr_src1_eq_dest!(test_andn_6, andn, 0xf000f000, 0xff00ff00, 0x0f0f0f0f);
test_rr_src2_eq_dest!(test_andn_7, andn, 0x0f000f00, 0x0ff00ff0, 0xf0f0f0f0);
test_rr_src12_eq_dest!(test_andn_8, andn, 0x00000000, 0xff00ff00);
test_rr_dest_bypass!(test_andn_9, 0, andn, 0xf000f000, 0xff00ff00, 0x0f0f0f0f);
test_rr_dest_bypass!(test_andn_10, 1, andn, 0x0f000f00, 0x0ff00ff0, 0xf0f0f0f0);
test_rr_dest_bypass!(test_andn_11, 2, andn, 0x00f000f0, 0x00ff00ff, 0x0f0f0f0f);
test_rr_src12_bypass!(test_andn_12, 0, 0, andn, 0xf000f000, 0xff00ff00, 0x0f0f0f0f);
test_rr_src12_bypass!(test_andn_13, 0, 1, andn, 0x0f000f00, 0x0ff00ff0, 0xf0f0f0f0);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | true |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/fence.rs | sw-emulator/lib/cpu/src/instr/fence.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
fence.rs
Abstract:
File contains implementation of system instructions.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32FenceFunct3, RvInstr32I, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvException;
impl<TBus: Bus> Cpu<TBus> {
/// Execute Fence Instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_fence_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32I(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Fence);
match instr.funct3().into() {
RvInstr32FenceFunct3::Fence => {
// Do nothing
Ok(())
}
RvInstr32FenceFunct3::FenceI => {
// Do nothing
Ok(())
}
_ => Err(RvException::illegal_instr(instr.0)),
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/system.rs | sw-emulator/lib/cpu/src/instr/system.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
system.rs
Abstract:
File contains implementation of system instructions.
--*/
use crate::cpu::Cpu;
use crate::csr_file::Csr;
use crate::types::{
RvInstr32I, RvInstr32Opcode, RvInstr32SystemFunct3, RvInstr32SystemImm, RvMStatus, RvPrivMode,
};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvData, RvException};
impl<TBus: Bus> Cpu<TBus> {
/// Execute system Instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_system_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32I(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::System);
let imm = instr.uimm();
match instr.funct3().into() {
RvInstr32SystemFunct3::Priv => match imm.into() {
RvInstr32SystemImm::Wfi => {
// TODO: If S-mode is present, we need to check TW=1 and return an illegal instruction exception
// if this is called from U mode.
// According to the spec, we can simply treat WFI as NOP since we are allowed to return
// from WFI for any reason, and we don't have any power optimization in the emulator.
Ok(())
}
RvInstr32SystemImm::Ecall => Err(match self.priv_mode {
RvPrivMode::M => RvException::environment_call_machine(),
RvPrivMode::U => RvException::environment_call_user(),
_ => unreachable!(),
}),
RvInstr32SystemImm::Ebreak => Err(RvException::breakpoint(self.read_pc())),
RvInstr32SystemImm::Mret => {
if self.priv_mode == RvPrivMode::U {
return Err(RvException::illegal_instr(instr.0));
}
let mut status = RvMStatus(self.read_csr(Csr::MSTATUS)?);
let mpp = status.mpp();
status.set_mie(status.mpie());
status.set_mpie(1);
status.set_mpp(RvPrivMode::U);
self.write_csr(Csr::MSTATUS, status.0)?;
self.set_next_pc(self.read_csr(Csr::MEPC)?);
self.priv_mode = mpp;
Ok(())
}
_ => Err(RvException::illegal_instr(instr.0)),
},
RvInstr32SystemFunct3::Csrrw => {
let old_val = self.read_csr(imm)?;
let new_val = self.read_xreg(instr.rs())?;
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
RvInstr32SystemFunct3::Csrrs => {
let old_val = self.read_csr(imm)?;
let new_val = old_val | self.read_xreg(instr.rs())?;
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
RvInstr32SystemFunct3::Csrrc => {
let old_val = self.read_csr(imm)?;
let new_val = old_val & !self.read_xreg(instr.rs())?;
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
RvInstr32SystemFunct3::Csrrwi => {
let old_val = self.read_csr(imm)?;
let new_val = instr.rs() as RvData;
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
RvInstr32SystemFunct3::Csrrsi => {
let old_val = self.read_csr(imm)?;
let new_val = old_val | instr.rs() as RvData;
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
RvInstr32SystemFunct3::Csrrci => {
let old_val = self.read_csr(imm)?;
let new_val = old_val & !(instr.rs() as RvData);
self.write_csr(imm, new_val)?;
self.write_xreg(instr.rd(), old_val)
}
_ => Err(RvException::illegal_instr(instr.0)),
}
}
}
#[cfg(test)]
mod tests {
use crate::csr_file::Csr;
use crate::instr::test_encoder::tests::{
csrrc, csrrci, csrrs, csrrsi, csrrw, csrrwi, ebreak, ecall,
};
use crate::xreg_file::XReg;
use crate::{isa_test, isa_test_cpu, text};
use caliptra_emu_types::RvException;
#[test]
fn test_ecall() {
let mut cpu = isa_test_cpu!(0x0000 => text![ecall();], 0x1000 => vec![0]);
assert_eq!(
cpu.exec_instr(None).err(),
Some(RvException::environment_call_machine())
);
}
#[test]
fn test_ebreak() {
let mut cpu = isa_test_cpu!(0x0000 => text![ebreak();], 0x1000 => vec![0]);
assert_eq!(
cpu.exec_instr(None).err(),
Some(RvException::breakpoint(0x0000))
);
}
#[test]
fn test_csrrw() {
isa_test!(
0x0000 => text![
csrrw(XReg::X1, XReg::X2, Csr::MISA);
csrrw(XReg::X3, XReg::X2, Csr::MEPC);
csrrw(XReg::X5, XReg::X0, Csr::MEPC);
],
0x1000 => vec![0],
{
XReg::X2 = u32::MAX;
},
{
XReg::X1 = 0x4010_1104;
XReg::X3 = 0x0000_0000;
XReg::X5 = u32::MAX;
}
);
}
#[test]
fn test_unknown_csr() {
isa_test!(
0x0000 => text![
csrrw(XReg::X1, XReg::X2, 4095);
csrrw(XReg::X3, XReg::X0, 4095);
],
0x1000 => vec![0],
{
XReg::X2 = u32::MAX;
},
{
XReg::X1 = 0x0000_0000;
XReg::X3 = 0x0000_0000;
}
);
}
#[test]
fn test_csrrs() {
isa_test!(
0x0000 => text![
csrrs(XReg::X1, XReg::X2, Csr::MSTATUS);
csrrs(XReg::X3, XReg::X0, Csr::MSTATUS);
csrrs(XReg::X5, XReg::X0, Csr::MSTATUS);
],
0x1000 => vec![0],
{
XReg::X2 = 0x0000_1888;
},
{
XReg::X1 = 0x1800_1800;
XReg::X3 = 0x1800_1888;
XReg::X5 = 0x1800_1888;
}
);
}
#[test]
fn test_csrrc() {
isa_test!(
0x0000 => text![
csrrs(XReg::X1, XReg::X2, Csr::MSTATUS);
csrrs(XReg::X3, XReg::X0, Csr::MSTATUS);
csrrc(XReg::X5, XReg::X2, Csr::MSTATUS);
csrrs(XReg::X7, XReg::X0, Csr::MSTATUS);
],
0x1000 => vec![0],
{
XReg::X2 = 0x0000_1888;
},
{
XReg::X1 = 0x1800_1800;
XReg::X3 = 0x1800_1888;
XReg::X5 = 0x1800_1888;
XReg::X7 = 0x1800_0000;
}
);
}
#[test]
fn test_csrrwi() {
isa_test!(
0x0000 => text![
csrrwi(XReg::X1, XReg::X16, Csr::MEPC);
csrrw(XReg::X3, XReg::X0, Csr::MEPC);
],
0x1000 => vec![0],
{
},
{
XReg::X1 = 0x0000_0000;
XReg::X3 = 16;
}
);
}
#[test]
fn test_csrrsi() {
isa_test!(
0x0000 => text![
csrrsi(XReg::X1, XReg::X15, Csr::MEPC);
csrrw(XReg::X3, XReg::X0, Csr::MEPC);
],
0x1000 => vec![0],
{
},
{
XReg::X1 = 0x0000_0000;
XReg::X3 = 15;
}
);
}
#[test]
fn test_csrrci() {
isa_test!(
0x0000 => text![
csrrsi(XReg::X1, XReg::X15, Csr::MEPC);
csrrci(XReg::X3, XReg::X1, Csr::MEPC);
csrrw(XReg::X5, XReg::X0, Csr::MEPC);
],
0x1000 => vec![0],
{
},
{
XReg::X1 = 0x0000_0000;
XReg::X3 = 15;
XReg::X5 = 14;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/test_encoder.rs | sw-emulator/lib/cpu/src/instr/test_encoder.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
test_encoder.rs
Abstract:
File contains implementation of RISCV Instruction encoding.
--*/
#[cfg(test)]
pub mod tests {
use crate::types::{
RvInstr32B, RvInstr32BranchFunct3, RvInstr32I, RvInstr32J, RvInstr32LoadFunct3,
RvInstr32OpFunct3, RvInstr32OpFunct7, RvInstr32OpImmFunct3, RvInstr32OpImmFunct7,
RvInstr32Opcode, RvInstr32R, RvInstr32S, RvInstr32StoreFunct3, RvInstr32SystemFunct3,
RvInstr32SystemImm, RvInstr32U,
};
use crate::xreg_file::XReg;
macro_rules! ld_instr {
($name:ident, $funct3:ident) => {
/// Encode load instruction
pub fn $name(rd: XReg, imm: i32, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::Load);
instr.set_rd(rd);
instr.set_funct3(RvInstr32LoadFunct3::$funct3.into());
instr.set_rs(rs);
instr.set_imm(imm);
instr.0
}
};
}
macro_rules! op_imm_instr {
($name:ident, $funct3:ident) => {
/// Encode immediate instruction
pub fn $name(rd: XReg, rs: XReg, imm: i32) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_funct3(RvInstr32OpImmFunct3::$funct3.into());
instr.set_rs(rs);
instr.set_imm(imm);
instr.0
}
};
($name:ident, $funct3:ident, $funct7:ident) => {
/// Encode immediate instruction
pub fn $name(rd: XReg, rs: XReg, shamt: u32) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_funct3(RvInstr32OpImmFunct3::$funct3.into());
instr.set_rs(rs);
instr.set_shamt(shamt);
instr.set_funct7(RvInstr32OpImmFunct7::$funct7.into());
instr.0
}
};
}
macro_rules! st_instr {
($name:ident, $funct3:ident) => {
/// Encode store instruction
pub fn $name(rs2: XReg, imm: i32, rs1: XReg) -> u32 {
let mut instr = RvInstr32S(0);
instr.set_opcode(RvInstr32Opcode::Store);
instr.set_rs2(rs2);
instr.set_funct3(RvInstr32StoreFunct3::$funct3.into());
instr.set_rs1(rs1);
instr.set_imm(imm);
instr.0
}
};
}
macro_rules! op_instr {
($name:ident, $funct3:ident, $funct7:ident) => {
/// Encode register op instruction
pub fn $name(rd: XReg, rs1: XReg, rs2: XReg) -> u32 {
let mut instr = RvInstr32R(0);
instr.set_opcode(RvInstr32Opcode::Op);
instr.set_rd(rd);
instr.set_rs1(rs1);
instr.set_rs2(rs2);
instr.set_funct3(RvInstr32OpFunct3::$funct3.into());
instr.set_funct7(RvInstr32OpFunct7::$funct7.into());
instr.0
}
};
}
macro_rules! branch_instr {
($name:ident, $funct3:ident) => {
/// Encode register op instruction
pub fn $name(rs1: XReg, rs2: XReg, imm: u32) -> u32 {
let mut instr = RvInstr32B(0);
instr.set_opcode(RvInstr32Opcode::Branch);
instr.set_funct3(RvInstr32BranchFunct3::$funct3.into());
instr.set_rs1(rs1);
instr.set_rs2(rs2);
instr.set_imm(imm);
instr.0
}
};
}
macro_rules! op_system_instr {
($name:ident, $funct3:ident) => {
/// Encode immediate instruction
pub fn $name(rd: XReg, rs: XReg, imm: u32) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::System);
instr.set_rd(rd);
instr.set_funct3(RvInstr32SystemFunct3::$funct3.into());
instr.set_rs(rs);
instr.set_uimm(imm);
instr.0
}
};
($name:ident, $funct3:ident, $imm:ident) => {
/// Encode immediate instruction
pub fn $name() -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::System);
instr.set_rd(XReg::X0);
instr.set_funct3(RvInstr32SystemFunct3::$funct3.into());
instr.set_rs(XReg::X0);
instr.set_uimm(RvInstr32SystemImm::$imm.into());
instr.0
}
};
}
ld_instr!(lb, Lb);
ld_instr!(lh, Lh);
ld_instr!(lw, Lw);
ld_instr!(lbu, Lbu);
ld_instr!(lhu, Lhu);
op_imm_instr!(addi, Addi);
op_imm_instr!(slli, Sli, Slli);
op_imm_instr!(slti, Slti);
op_imm_instr!(sltiu, Sltiu);
op_imm_instr!(xori, Xori);
op_imm_instr!(srli, Sri, Srli);
op_imm_instr!(srai, Sri, Srai);
op_imm_instr!(ori, Ori);
op_imm_instr!(andi, Andi);
/// Encode No-op.rs instruction
pub fn nop() -> u32 {
addi(XReg::X0, XReg::X0, 0)
}
pub fn sign_extend(x: u32) -> u32 {
let x = x as i32;
let x = x | (-(((x) >> 11) & 1) << 11);
x as u32
}
/// Encode Add Upper Immediate to program counter (`auipc`) instruction
pub fn auipc(rd: XReg, imm: i32) -> u32 {
let mut instr = RvInstr32U(0);
instr.set_opcode(RvInstr32Opcode::Auipc);
instr.set_rd(rd);
instr.set_imm(imm);
instr.0
}
st_instr!(sb, Sb);
st_instr!(sh, Sh);
st_instr!(sw, Sw);
op_instr!(add, Zero, Add);
op_instr!(mul, Zero, Mul);
op_instr!(sub, Zero, Sub);
op_instr!(sll, One, Sll);
op_instr!(mulh, One, Mulh);
op_instr!(slt, Two, Slt);
op_instr!(mulhsu, Two, Mulhsu);
op_instr!(sltu, Three, Sltu);
op_instr!(mulhu, Three, Mulhu);
op_instr!(xor, Four, Xor);
op_instr!(div, Four, Div);
op_instr!(srl, Five, Srl);
op_instr!(divu, Five, Divu);
op_instr!(sra, Five, Sra);
op_instr!(or, Six, Or);
op_instr!(rem, Six, Rem);
op_instr!(and, Seven, And);
op_instr!(remu, Seven, Remu);
// bit manipulation extension
op_instr!(sh1add, Two, Sh1add);
op_instr!(sh2add, Four, Sh1add);
op_instr!(sh3add, Six, Sh1add);
op_instr!(bset, One, Bset);
op_instr!(binv, One, Binv);
op_instr!(bclr, One, Bclr);
op_instr!(bext, Five, Bclr);
op_instr!(andn, Seven, Sub);
op_instr!(orn, Six, Sub);
op_instr!(xnor, Four, Sub);
op_instr!(max, Six, MinMaxClmul);
op_instr!(maxu, Seven, MinMaxClmul);
op_instr!(min, Four, MinMaxClmul);
op_instr!(minu, Five, MinMaxClmul);
op_instr!(rol, One, Rotate);
op_instr!(ror, Five, Rotate);
op_instr!(clmul, One, MinMaxClmul);
op_instr!(clmulh, Three, MinMaxClmul);
op_instr!(clmulr, Two, MinMaxClmul);
op_imm_instr!(bseti, Sli, Orc);
op_imm_instr!(binvi, Sli, Rev8);
op_imm_instr!(bclri, Sli, Bclr);
op_imm_instr!(bexti, Sri, Bclr);
op_imm_instr!(rori, Sri, Bitmanip);
pub fn clz(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x600);
instr.set_funct3(1);
instr.0
}
pub fn cpop(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x602);
instr.set_funct3(1);
instr.0
}
pub fn ctz(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x601);
instr.set_funct3(1);
instr.0
}
pub fn orc_b(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x287);
instr.set_funct3(5);
instr.0
}
pub fn rev8(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x698);
instr.set_funct3(5);
instr.0
}
pub fn sext_b(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x604);
instr.set_funct3(1);
instr.0
}
pub fn sext_h(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::OpImm);
instr.set_rd(rd);
instr.set_rs(rs);
instr.set_imm(0x605);
instr.set_funct3(1);
instr.0
}
pub fn zext_h(rd: XReg, rs: XReg) -> u32 {
let mut instr = RvInstr32R(0);
instr.set_opcode(RvInstr32Opcode::Op);
instr.set_rd(rd);
instr.set_rs1(rs);
instr.set_rs2(XReg::X0);
instr.set_funct3(4);
instr.set_funct7(RvInstr32OpFunct7::Zext.into());
instr.0
}
// load immediate (first instruction)
pub fn li0(rd: XReg, imm: u32) -> u32 {
let v = (imm >> 12) + if imm & 0x800 == 0x800 { 1 } else { 0 };
lui(rd, v as i32)
}
// load immediate (second instruction)
pub fn li1(rd: XReg, imm: u32) -> u32 {
addi(rd, rd, (imm & 0xfff) as i32)
}
/// Encode Load Upper Immediate (`lui`) instruction
pub fn lui(rd: XReg, imm: i32) -> u32 {
let mut instr = RvInstr32U(0);
instr.set_opcode(RvInstr32Opcode::Lui);
instr.set_rd(rd);
instr.set_imm(imm);
instr.0
}
branch_instr!(beq, Beq);
branch_instr!(bne, Bne);
branch_instr!(blt, Blt);
branch_instr!(bge, Bge);
branch_instr!(bltu, Bltu);
branch_instr!(bgeu, Bgeu);
pub fn jalr(rd: XReg, rs1: XReg, imm: i32) -> u32 {
let mut instr = RvInstr32I(0);
instr.set_opcode(RvInstr32Opcode::Jalr);
instr.set_rd(rd);
instr.set_funct3(0);
instr.set_rs(rs1);
instr.set_imm(imm);
instr.0
}
pub fn jal(rd: XReg, imm: u32) -> u32 {
let mut instr = RvInstr32J(0);
instr.set_opcode(RvInstr32Opcode::Jal);
instr.set_rd(rd);
instr.set_imm(imm);
instr.0
}
op_system_instr!(ecall, Priv, Ecall);
op_system_instr!(ebreak, Priv, Ebreak);
op_system_instr!(csrrw, Csrrw);
op_system_instr!(csrrs, Csrrs);
op_system_instr!(csrrc, Csrrc);
op_system_instr!(csrrwi, Csrrwi);
op_system_instr!(csrrsi, Csrrsi);
op_system_instr!(csrrci, Csrrci);
#[test]
fn test_sign_extend() {
for i in 0..0x800 {
assert_eq!(i, sign_extend(i));
}
for i in 0x800..0x1000 {
assert_eq!(0xffff_f000 | i, sign_extend(i));
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/lui.rs | sw-emulator/lib/cpu/src/instr/lui.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lui.rs
Abstract:
File contains implementation of Load Upper Immediate (`lui`) instruction.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32Opcode, RvInstr32U};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvData, RvException};
impl<TBus: Bus> Cpu<TBus> {
/// Execute `lui` Instruction
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_lui_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32U(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Lui);
// Calculate the value
let val = instr.imm().wrapping_shl(12) as RvData;
// Save the contents to register
self.write_xreg(instr.rd(), val)
}
}
#[cfg(test)]
mod tests {
use crate::{isa_test, test_lui, text};
// ---------------------------------------------------------------------------------------------
// Tests For Load Upper Immediate (`lui`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lui.S
// ----------------------------------------------------------------------------------------------------------------
test_lui!(test_lui_2, 0x00000000, 0x00000, 0);
test_lui!(test_lui_3, 0xFFFFF800, 0xFFFFF, 1);
test_lui!(test_lui_4, 0x000007FF, 0x7FFFF, 20);
test_lui!(test_lui_5, 0xFFFFF800, 0x80000, 20);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/mod.rs | sw-emulator/lib/cpu/src/instr/mod.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
mod.rs
Abstract:
File contains implementation of RISCV Instructions
References:
https://riscv.org/wp-content/uploads/2019/06/riscv-spec.pdf
--*/
mod auipc;
mod bit;
mod branch;
mod compression;
mod fence;
mod jal;
mod jalr;
mod load;
mod lui;
mod op;
mod op_imm;
mod store;
mod system;
mod test_encoder;
mod test_macros;
use crate::cpu::{Cpu, InstrTracer, StepAction};
use crate::types::{RvInstr, RvInstr32, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvException, RvSize};
/// Instruction
pub enum Instr {
Compressed(u16),
General(u32),
}
impl<TBus: Bus> Cpu<TBus> {
/// Execute single instruction
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub(crate) fn exec_instr(
&mut self,
instr_tracer: Option<&mut InstrTracer>,
) -> Result<StepAction, RvException> {
// Set In Execution Mode and remove Hit
self.is_execute_instr = true;
self.watch_ptr_cfg.hit = None;
let instr = self.fetch()?;
// Code coverage here.
self.code_coverage.log_execution(self.read_pc(), &instr);
match instr {
Instr::Compressed(instr) => {
self.set_next_pc(self.read_pc().wrapping_add(2));
self.exec_instr16(instr, instr_tracer)?;
}
Instr::General(instr) => {
self.set_next_pc(self.read_pc().wrapping_add(4));
self.exec_instr32(instr, instr_tracer)?;
}
}
self.write_pc(self.next_pc());
self.is_execute_instr = false;
match self.get_watchptr_hit() {
Some(_hit) => Ok(StepAction::Break),
None => Ok(StepAction::Continue),
}
}
/// Fetch an instruction from current program counter
///
/// # Error
///
/// * `RvException` - Exception with cause `RvExceptionCause::InstrAccessFault`
/// or `RvExceptionCause::InstrAddrMisaligned`
fn fetch(&mut self) -> Result<Instr, RvException> {
let instr = self.read_instr(RvSize::HalfWord, self.read_pc())?;
match instr & 0b11 {
0..=2 => Ok(Instr::Compressed(instr as u16)),
_ => Ok(Instr::General(
self.read_instr(RvSize::Word, self.read_pc())?,
)),
}
}
/// Execute a single 16-bit instruction `instr`, tracing instructions to
/// `instr_tracer` if it exists.
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
fn exec_instr16(
&mut self,
instr: u16,
instr_tracer: Option<&mut InstrTracer>,
) -> Result<(), RvException> {
if let Some(instr_tracer) = instr_tracer {
instr_tracer(self.read_pc(), RvInstr::Instr16(instr))
}
self.exec_instr32(compression::decompress_instr(instr)?, None)
}
/// Execute single 32-bit instruction
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
fn exec_instr32(
&mut self,
instr: u32,
instr_tracer: Option<&mut InstrTracer>,
) -> Result<(), RvException> {
if let Some(instr_tracer) = instr_tracer {
instr_tracer(self.read_pc(), RvInstr::Instr32(instr))
}
match RvInstr32(instr).opcode() {
RvInstr32Opcode::Load => self.exec_load_instr(instr)?,
RvInstr32Opcode::OpImm => self.exec_op_imm_instr(instr)?,
RvInstr32Opcode::Auipc => self.exec_auipc_instr(instr)?,
RvInstr32Opcode::Store => self.exec_store_instr(instr)?,
RvInstr32Opcode::Op => self.exec_op_instr(instr)?,
RvInstr32Opcode::Lui => self.exec_lui_instr(instr)?,
RvInstr32Opcode::Branch => self.exec_branch_instr(instr)?,
RvInstr32Opcode::Jalr => self.exec_jalr_instr(instr)?,
RvInstr32Opcode::Jal => self.exec_jal_instr(instr)?,
RvInstr32Opcode::System => self.exec_system_instr(instr)?,
RvInstr32Opcode::Fence => self.exec_fence_instr(instr)?,
_ => Err(RvException::illegal_instr(instr))?,
}
Ok(())
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/jalr.rs | sw-emulator/lib/cpu/src/instr/jalr.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
jalr.rs
Abstract:
File contains implementation of Jump and Link register instructions.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32I, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::RvException;
impl<TBus: Bus> Cpu<TBus> {
/// Execute `jalr` Instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_jalr_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32I(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Jalr);
// Calculate the new program counter
let pc = self.read_xreg(instr.rs())? as i32;
let pc = pc.wrapping_add(instr.imm());
let pc = pc as u32 & !1u32;
// Calculate the return address
let lr = self.next_pc();
// Update the registers
self.set_next_pc(pc);
self.write_xreg(instr.rd(), lr)
}
}
#[cfg(test)]
mod tests {
use crate::instr::test_encoder::tests::{jalr, nop};
use crate::xreg_file::XReg;
use crate::{isa_test, text};
#[test]
fn test_jalr_2() {
isa_test!(
0x0000 => text![
jalr(XReg::X1, XReg::X2, 0x0000);
nop();
nop();
],
0x1000 => vec![0],
{
XReg::X2 = 0x0008;
},
{
XReg::X1 = 0x0004;
}
);
}
#[test]
fn test_jalr_3() {
isa_test!(
0x0000 => text![
jalr(XReg::X1, XReg::X1, 0x0000);
nop();
nop();
],
0x1000 => vec![0],
{
XReg::X1 = 0x0008;
},
{
XReg::X1 = 0x0004;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/op_imm.rs | sw-emulator/lib/cpu/src/instr/op_imm.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
op_imm.rs
Abstract:
File contains implementation of RISCV Immediate instructions.
References:
https://riscv.org/wp-content/uploads/2019/06/riscv-spec.pdf
https://github.com/d0iasm/rvemu for arithmetic operations.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32I, RvInstr32OpImmFunct3, RvInstr32OpImmFunct7, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvData, RvException};
impl<TBus: Bus> Cpu<TBus> {
/// Execute immediate instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_op_imm_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32I(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::OpImm);
// Read the content of source register
let reg = self.read_xreg(instr.rs())?;
let data = if let Some(data) = self.exec_bit_instr_op_imm(instr, reg) {
data
} else {
match instr.funct3().into() {
// Add Immediate (`addi`) Instruction
RvInstr32OpImmFunct3::Addi => reg.wrapping_add(instr.imm() as u32) as RvData,
RvInstr32OpImmFunct3::Sli => {
match instr.funct7().into() {
// Shift Left Logical Immediate (`slli`) Instruction
RvInstr32OpImmFunct7::Slli => reg.wrapping_shl(instr.shamt()) as RvData,
// Illegal Instruction
_ => Err(RvException::illegal_instr(instr.0))?,
}
}
// Set Less Than Immediate (`slti`) Instruction
RvInstr32OpImmFunct3::Slti => {
if (reg as i32) < instr.imm() {
1
} else {
0
}
}
// Set Less Than Immediate Unsigned (`sltiu`) Instruction
RvInstr32OpImmFunct3::Sltiu => {
if reg < instr.imm() as u32 {
1
} else {
0
}
}
// Xor Immediate (`xori`) Instruction
RvInstr32OpImmFunct3::Xori => reg ^ instr.imm() as u32,
// Shift Right Immediate Instruction
RvInstr32OpImmFunct3::Sri => {
match instr.funct7().into() {
// Shift Right Logical Immediate (`srli`) Instruction
RvInstr32OpImmFunct7::Srli => reg.wrapping_shr(instr.shamt()) as RvData,
// Shift Right Arithmetic Immediate (`srai`) Instruction
RvInstr32OpImmFunct7::Srai => {
(reg as i32).wrapping_shr(instr.shamt()) as RvData
}
// Illegal Instruction
_ => Err(RvException::illegal_instr(instr.0))?,
}
}
// Or Immediate (`ori`) Instruction
RvInstr32OpImmFunct3::Ori => reg | instr.imm() as u32,
// And Immediate (`ori`) Instruction
RvInstr32OpImmFunct3::Andi => reg & instr.imm() as u32,
// Illegal Instruction
_ => Err(RvException::illegal_instr(instr.0))?,
}
};
// Save the contents to register
self.write_xreg(instr.rd(), data)
}
}
#[cfg(test)]
#[allow(clippy::identity_op)]
mod tests {
use crate::{test_imm_op, test_imm_src1_eq_dest, test_imm_zero_dest, test_imm_zero_src1};
// ---------------------------------------------------------------------------------------------
// Tests for Add Immediate (`addi`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/addi.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_imm_op!(test_addi_2, addi, 0x0000_0000, 0x0000_0000, 0x000);
test_imm_op!(test_addi_3, addi, 0x0000_0002, 0x0000_0001, 0x001);
test_imm_op!(test_addi_4, addi, 0x0000_000A, 0x0000_0003, 0x007);
test_imm_op!(test_addi_5, addi, 0xFFFF_F800, 0x0000_0000, 0x800);
test_imm_op!(test_addi_6, addi, 0x8000_0000, 0x8000_0000, 0x000);
test_imm_op!(test_addi_7, addi, 0x7FFF_F800, 0x8000_0000, 0x800);
test_imm_op!(test_addi_8, addi, 0x0000_07FF, 0x0000_0000, 0x7FF);
test_imm_op!(test_addi_9, addi, 0x7FFF_FFFF, 0x7FFF_FFFF, 0x000);
test_imm_op!(test_addi_10, addi, 0x8000_07FE, 0x7FFF_FFFF, 0x7FF);
test_imm_op!(test_addi_11, addi, 0x8000_07FF, 0x8000_0000, 0x7FF);
test_imm_op!(test_addi_12, addi, 0x7FFF_F7FF, 0x7FFF_FFFF, 0x800);
test_imm_op!(test_addi_13, addi, 0xFFFF_FFFF, 0x0000_0000, 0xFFF);
test_imm_op!(test_addi_14, addi, 0x0000_0000, 0xFFFF_FFFF, 0x001);
test_imm_op!(test_addi_15, addi, 0xFFFF_FFFE, 0xFFFF_FFFF, 0xFFF);
test_imm_op!(test_addi_16, addi, 0x8000_0000, 0x7FFF_FFFF, 0x001);
test_imm_src1_eq_dest!(test_addi_17, addi, 24, 13, 11);
test_imm_zero_src1!(test_addi_24, addi, 32, 32);
test_imm_zero_dest!(test_addi_25, addi, 33, 50);
// ---------------------------------------------------------------------------------------------
// Tests for Shift Logical Left Immediate (`slli`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/slli.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_imm_op!(test_slli_2, slli, 0x0000_0001, 0x0000_0001, 0);
test_imm_op!(test_slli_3, slli, 0x0000_0002, 0x0000_0001, 1);
test_imm_op!(test_slli_4, slli, 0x0000_0080, 0x0000_0001, 7);
test_imm_op!(test_slli_5, slli, 0x0000_4000, 0x0000_0001, 14);
test_imm_op!(test_slli_6, slli, 0x8000_0000, 0x0000_0001, 31);
test_imm_op!(test_slli_7, slli, 0xFFFF_FFFF, 0xFFFF_FFFF, 0);
test_imm_op!(test_slli_8, slli, 0xFFFF_FFFE, 0xFFFF_FFFF, 1);
test_imm_op!(test_slli_9, slli, 0xFFFF_FF80, 0xFFFF_FFFF, 7);
test_imm_op!(test_slli_10, slli, 0xFFFF_C000, 0xFFFF_FFFF, 14);
test_imm_op!(test_slli_11, slli, 0x8000_0000, 0xFFFF_FFFF, 31);
test_imm_op!(test_slli_12, slli, 0x2121_2121, 0x2121_2121, 0);
test_imm_op!(test_slli_13, slli, 0x4242_4242, 0x2121_2121, 1);
test_imm_op!(test_slli_14, slli, 0x9090_9080, 0x2121_2121, 7);
test_imm_op!(test_slli_15, slli, 0x4848_4000, 0x2121_2121, 14);
test_imm_op!(test_slli_16, slli, 0x8000_0000, 0x2121_2121, 31);
// Source/Destination tests
test_imm_src1_eq_dest!(test_slli_17, slli, 0x0000_0080, 0x0000_0001, 7);
// Bypassing tests
test_imm_zero_src1!(test_slli_24, slli, 0, 31);
test_imm_zero_dest!(test_slli_25, slli, 33, 20);
// ---------------------------------------------------------------------------------------------
// Tests for Set Less Than Immediate (`slti`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/slti.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_imm_op!(test_slti_2, slti, 0, 0x0000_0000, 0x000);
test_imm_op!(test_slti_3, slti, 0, 0x0000_0001, 0x001);
test_imm_op!(test_slti_4, slti, 1, 0x0000_0003, 0x007);
test_imm_op!(test_slti_5, slti, 0, 0x0000_0007, 0x003);
test_imm_op!(test_slti_6, slti, 0, 0x0000_0000, 0x800);
test_imm_op!(test_slti_7, slti, 1, 0x8000_0000, 0x000);
test_imm_op!(test_slti_8, slti, 1, 0x8000_0000, 0x800);
test_imm_op!(test_slti_9, slti, 1, 0x0000_0000, 0x7FF);
test_imm_op!(test_slti_10, slti, 0, 0x7FFF_FFFF, 0x000);
test_imm_op!(test_slti_11, slti, 0, 0x7FFF_FFFF, 0x7FF);
test_imm_op!(test_slti_12, slti, 1, 0x8000_0000, 0x7FF);
test_imm_op!(test_slti_13, slti, 0, 0x7FFF_FFFF, 0x800);
test_imm_op!(test_slti_14, slti, 0, 0x0000_0000, 0xFFF);
test_imm_op!(test_slti_15, slti, 1, 0xFFFF_FFFF, 0x001);
test_imm_op!(test_slti_16, slti, 0, 0xFFFF_FFFF, 0xFFF);
// Source/Destination tests
test_imm_src1_eq_dest!(test_slti_17, slti, 1, 11, 13);
// Bypassing tests
test_imm_zero_src1!(test_slti_24, slti, 0, 0xFFF);
test_imm_zero_dest!(test_slti_25, slti, 0x00FF_00FF, 0xFFF);
// ---------------------------------------------------------------------------------------------
// Tests for Set Less Than Immediate Unsigned (`sltiu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/sltiu.S
// ---------------------------------------------------------------------------------------------
// Arithmetic tests
test_imm_op!(test_sltiu_2, sltiu, 0, 0x0000_0000, 0x000);
test_imm_op!(test_sltiu_3, sltiu, 0, 0x0000_0001, 0x001);
test_imm_op!(test_sltiu_4, sltiu, 1, 0x0000_0003, 0x007);
test_imm_op!(test_sltiu_5, sltiu, 0, 0x0000_0007, 0x003);
test_imm_op!(test_sltiu_6, sltiu, 1, 0x0000_0000, 0x800);
test_imm_op!(test_sltiu_7, sltiu, 0, 0x8000_0000, 0x000);
test_imm_op!(test_sltiu_8, sltiu, 1, 0x8000_0000, 0x800);
test_imm_op!(test_sltiu_9, sltiu, 1, 0x0000_0000, 0x7FF);
test_imm_op!(test_sltiu_10, sltiu, 0, 0x7FFF_FFFF, 0x000);
test_imm_op!(test_sltiu_11, sltiu, 0, 0x7FFF_FFFF, 0x7FF);
test_imm_op!(test_sltiu_12, sltiu, 0, 0x8000_0000, 0x7FF);
test_imm_op!(test_sltiu_13, sltiu, 1, 0x7FFF_FFFF, 0x800);
test_imm_op!(test_sltiu_14, sltiu, 1, 0x0000_0000, 0xFFF);
test_imm_op!(test_sltiu_15, sltiu, 0, 0xFFFF_FFFF, 0x001);
test_imm_op!(test_sltiu_16, sltiu, 0, 0xFFFF_FFFF, 0xFFF);
// Source/Destination tests
test_imm_src1_eq_dest!(test_sltiu_17, sltiu, 1, 11, 13);
// Bypassing tests
test_imm_zero_src1!(test_sltiu_24, sltiu, 1, 0xFFF);
test_imm_zero_dest!(test_sltiu_25, sltiu, 0x00FF_00FF, 0xFFF);
// ---------------------------------------------------------------------------------------------
// Tests for Xor Immediate (`xori`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/xori.S
// ---------------------------------------------------------------------------------------------
// Logical tests
test_imm_op!(test_xori_2, xori, 0xFF00_F00F, 0x00FF_0F00, 0xF0F);
test_imm_op!(test_xori_3, xori, 0x0FF0_0F00, 0x0FF0_0FF0, 0x0F0);
test_imm_op!(test_xori_4, xori, 0x00FF_0FF0, 0x00FF_08FF, 0x70F);
test_imm_op!(test_xori_5, xori, 0xF00F_F0FF, 0xF00F_F00F, 0x0F0);
// Source/Destination tests
test_imm_src1_eq_dest!(test_xori_6, xori, 0xFF00_F00F, 0xFF00_F700, 0x70F);
// Bypassing tests
test_imm_zero_src1!(test_xori_13, xori, 0x0F0, 0x0F0);
test_imm_zero_dest!(test_xori_14, xori, 0x00FF_00FF, 0x70F);
// ---------------------------------------------------------------------------------------------
// Tests for Shift Right Logical Immediate (`srli`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/srli.S
// ---------------------------------------------------------------------------------------------
// Logical tests
test_imm_op!(test_srli_2, srli, 0x8000_0000 >> 0, 0x8000_0000, 0);
test_imm_op!(test_srli_3, srli, 0x8000_0000 >> 1, 0x8000_0000, 1);
test_imm_op!(test_srli_4, srli, 0x8000_0000 >> 7, 0x8000_0000, 7);
test_imm_op!(test_srli_5, srli, 0x8000_0000 >> 14, 0x8000_0000, 14);
test_imm_op!(test_srli_6, srli, 0x8000_0001 >> 31, 0x8000_0001, 31);
test_imm_op!(test_srli_7, srli, 0xFFFF_FFFF >> 0, 0xFFFF_FFFF, 0);
test_imm_op!(test_srli_8, srli, 0xFFFF_FFFF >> 1, 0xFFFF_FFFF, 1);
test_imm_op!(test_srli_9, srli, 0xFFFF_FFFF >> 7, 0xFFFF_FFFF, 7);
test_imm_op!(test_srli_10, srli, 0xFFFF_FFFF >> 14, 0xFFFF_FFFF, 14);
test_imm_op!(test_srli_11, srli, 0xFFFF_FFFF >> 31, 0xFFFF_FFFF, 31);
test_imm_op!(test_srli_12, srli, 0x2121_2121 >> 0, 0x2121_2121, 0);
test_imm_op!(test_srli_13, srli, 0x2121_2121 >> 1, 0x2121_2121, 1);
test_imm_op!(test_srli_14, srli, 0x2121_2121 >> 7, 0x2121_2121, 7);
test_imm_op!(test_srli_15, srli, 0x2121_2121 >> 14, 0x2121_2121, 14);
test_imm_op!(test_srli_16, srli, 0x2121_2121 >> 31, 0x2121_2121, 31);
// Source/Destination tests
test_imm_src1_eq_dest!(test_srli_17, srli, 0x0100_0000, 0x8000_0000, 7);
// Bypassing tests
test_imm_zero_src1!(test_srli_24, srli, 0, 4);
test_imm_zero_dest!(test_srli_25, srli, 33, 10);
// ---------------------------------------------------------------------------------------------
// Tests for Shift Right Arithmetic Immediate (`srli`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/srai.S
// ---------------------------------------------------------------------------------------------
// Logical tests
test_imm_op!(test_srai_2, srai, 0x0000_0000, 0x0000_0000, 0);
test_imm_op!(test_srai_3, srai, 0xC000_0000, 0x8000_0000, 1);
test_imm_op!(test_srai_4, srai, 0xFF00_0000, 0x8000_0000, 7);
test_imm_op!(test_srai_5, srai, 0xFFFE_0000, 0x8000_0000, 14);
test_imm_op!(test_srai_6, srai, 0xFFFF_FFFF, 0x8000_0001, 31);
test_imm_op!(test_srai_7, srai, 0x7FFF_FFFF, 0x7FFF_FFFF, 0);
test_imm_op!(test_srai_8, srai, 0x3FFF_FFFF, 0x7FFF_FFFF, 1);
test_imm_op!(test_srai_9, srai, 0x00FF_FFFF, 0x7FFF_FFFF, 7);
test_imm_op!(test_srai_10, srai, 0x0001_FFFF, 0x7FFF_FFFF, 14);
test_imm_op!(test_srai_11, srai, 0x0000_0000, 0x7FFF_FFFF, 31);
test_imm_op!(test_srai_12, srai, 0x8181_8181, 0x8181_8181, 0);
test_imm_op!(test_srai_13, srai, 0xC0C0_C0C0, 0x8181_8181, 1);
test_imm_op!(test_srai_14, srai, 0xFF03_0303, 0x8181_8181, 7);
test_imm_op!(test_srai_15, srai, 0xFFFE_0606, 0x8181_8181, 14);
test_imm_op!(test_srai_16, srai, 0xFFFF_FFFF, 0x8181_8181, 31);
// Source/Destination tests
test_imm_src1_eq_dest!(test_srai_17, srai, 0xFF00_0000, 0x8000_0000, 7);
// Bypassing tests
test_imm_zero_src1!(test_srai_24, srai, 0, 4);
test_imm_zero_dest!(test_srai_25, srai, 33, 10);
// ---------------------------------------------------------------------------------------------
// Tests For Or Immediate (`ori`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/ori.S
// ---------------------------------------------------------------------------------------------
// Logical tests
test_imm_op!(test_ori_2, ori, 0xFFFF_FF0F, 0xFF00_FF00, 0xF0F);
test_imm_op!(test_ori_3, ori, 0x0FF0_0FF0, 0x0FF0_0FF0, 0x0F0);
test_imm_op!(test_ori_4, ori, 0x00FF_07FF, 0x00FF_00FF, 0x70F);
test_imm_op!(test_ori_5, ori, 0xF00F_F0FF, 0xF00F_F00F, 0x0F0);
// Source/Destination tests
test_imm_src1_eq_dest!(test_ori_6, ori, 0xFF00_FFF0, 0xFF00_FF00, 0x0F0);
// Bypassing tests
test_imm_zero_src1!(test_ori_7, ori, 0x0F0, 0x0F0);
test_imm_zero_dest!(test_ori_14, ori, 0x00FF_00FF, 0x70F);
// ---------------------------------------------------------------------------------------------
// Tests For And Immediate (`andi`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/andi.S
// ---------------------------------------------------------------------------------------------
// Logical tests
test_imm_op!(test_andi_2, andi, 0xFF00FF00, 0xFF00FF00, 0xF0F);
test_imm_op!(test_andi_3, andi, 0x000000F0, 0x0FF00FF0, 0x0F0);
test_imm_op!(test_andi_4, andi, 0x0000000F, 0x00FF00FF, 0x70F);
test_imm_op!(test_andi_5, andi, 0x00000000, 0xF00FF00F, 0x0F0);
// Source/Destination tests
test_imm_src1_eq_dest!(test_andi_6, andi, 0x00000000, 0xFF00FF00, 0x0F0);
// Bypassing tests
test_imm_zero_src1!(test_andi_13, andi, 0, 0x0F0);
test_imm_zero_dest!(test_andi_14, andi, 0x00FF00FF, 0x70F);
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/compression.rs | sw-emulator/lib/cpu/src/instr/compression.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
compression.rs
Abstract:
File contains code related to compressed RISC-V instructions.
--*/
use crate::{
types::{
RvInstr32B, RvInstr32BranchFunct3, RvInstr32I, RvInstr32J, RvInstr32LoadFunct3,
RvInstr32OpFunct10, RvInstr32OpImmFunct3, RvInstr32OpImmFunct7, RvInstr32Opcode,
RvInstr32R, RvInstr32S, RvInstr32StoreFunct3, RvInstr32U,
},
xreg_file::XReg,
};
use caliptra_emu_types::RvException;
const OP_MASK_5: u16 = 0xe003;
const OP_MASK_6: u16 = 0xf003;
const OP_MASK_7: u16 = 0xec03;
const OP_MASK_9: u16 = 0xfc63;
macro_rules! static_assert {
($expression:expr) => {
const _: () = assert!($expression);
};
}
/// Decodes a 16-bit RV32IMC compressed instruction `instr` into a 32-bit RV32IM instruction.
///
/// # Errors
///
/// Returns error with [`RvExceptionCause::IllegalInstr`] if the instruction could be not be decoded.
pub fn decompress_instr(instr: u16) -> Result<u32, RvException> {
match instr & OP_MASK_5 {
rv16::CJ::OP_CODE => {
static_assert!(rv16::CJ::OP_MASK == OP_MASK_5);
let instr = rv16::CJ(instr);
let mut result = RvInstr32J(0);
result.set_opcode(RvInstr32Opcode::Jal);
result.set_imm(i32::from(instr.imm()) as u32);
result.set_rd(XReg::X0);
return Ok(result.0);
}
rv16::CJal::OP_CODE => {
static_assert!(rv16::CJal::OP_MASK == OP_MASK_5);
let instr = rv16::CJal(instr);
let mut result = RvInstr32J(0);
result.set_opcode(RvInstr32Opcode::Jal);
result.set_imm(i32::from(instr.imm()) as u32);
result.set_rd(XReg::X1);
return Ok(result.0);
}
rv16::CLw::OP_CODE => {
static_assert!(rv16::CLw::OP_MASK == OP_MASK_5);
let instr = rv16::CLw(instr);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::Load);
result.set_funct3(RvInstr32LoadFunct3::Lw.into());
result.set_imm(instr.uimm().into());
result.set_rs(instr.rs1());
result.set_rd(instr.rd());
return Ok(result.0);
}
rv16::CSw::OP_CODE => {
static_assert!(rv16::CSw::OP_MASK == OP_MASK_5);
let instr = rv16::CSw(instr);
let mut result = RvInstr32S(0);
result.set_opcode(RvInstr32Opcode::Store);
result.set_funct3(RvInstr32StoreFunct3::Sw.into());
result.set_imm(instr.uimm().into());
result.set_rs1(instr.rs1());
result.set_rs2(instr.rs2());
return Ok(result.0);
}
rv16::CLwsp::OP_CODE => {
static_assert!(rv16::CLwsp::OP_MASK == OP_MASK_5);
let instr = rv16::CLwsp(instr);
if instr.rd() != XReg::X0 {
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::Load);
result.set_funct3(RvInstr32LoadFunct3::Lw.into());
result.set_uimm(instr.uimm().into());
result.set_rs(XReg::X2);
result.set_rd(instr.rd());
return Ok(result.0);
}
}
rv16::CSwsp::OP_CODE => {
static_assert!(rv16::CSwsp::OP_MASK == OP_MASK_5);
let instr = rv16::CSwsp(instr);
let mut result = RvInstr32S(0);
result.set_opcode(RvInstr32Opcode::Store);
result.set_funct3(RvInstr32StoreFunct3::Sw.into());
result.set_imm(instr.uimm().into());
result.set_rs1(XReg::X2);
result.set_rs2(instr.rs2());
return Ok(result.0);
}
rv16::CAddi::OP_CODE => {
static_assert!(rv16::CAddi::OP_MASK == OP_MASK_5);
let instr = rv16::CAddi(instr);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Addi.into());
result.set_imm(instr.nzimm().into());
result.set_rs(instr.rs1rd());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
rv16::CAddi4spn::OP_CODE => {
static_assert!(rv16::CAddi4spn::OP_MASK == OP_MASK_5);
let instr = rv16::CAddi4spn(instr);
if instr.nzuimm() != 0 {
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Addi.into());
result.set_imm(instr.nzuimm().into());
result.set_rs(XReg::X2);
result.set_rd(instr.rd());
return Ok(result.0);
}
}
rv16::CLi::OP_CODE => {
static_assert!(rv16::CLui::OP_MASK == OP_MASK_5);
let instr = rv16::CLi(instr);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Addi.into());
result.set_imm(instr.nzimm());
result.set_rs(XReg::X0);
result.set_rd(instr.rd());
return Ok(result.0);
}
rv16::CLui::OP_CODE => {
static_assert!(rv16::CLui::OP_MASK == OP_MASK_5);
let instr = rv16::CLui(instr);
if instr.nzimm() != 0 {
if instr.rd() == XReg::X2 {
static_assert!(rv16::CAddi16sp::OP_MASK == OP_MASK_5);
static_assert!(rv16::CAddi16sp::OP_CODE == rv16::CLui::OP_CODE);
let instr = rv16::CAddi16sp(instr.0);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Addi.into());
result.set_imm(instr.nzimm());
result.set_rs(XReg::X2);
result.set_rd(XReg::X2);
return Ok(result.0);
} else {
let mut result = RvInstr32U(0);
result.set_opcode(RvInstr32Opcode::Lui);
result.set_imm(instr.nzimm() >> 12);
result.set_rd(instr.rd());
return Ok(result.0);
}
}
}
rv16::CBeqz::OP_CODE => {
static_assert!(rv16::CBeqz::OP_MASK == OP_MASK_5);
let instr = rv16::CBeqz(instr);
let mut result = RvInstr32B(0);
result.set_opcode(RvInstr32Opcode::Branch);
result.set_funct3(RvInstr32BranchFunct3::Beq.into());
result.set_imm(i32::from(instr.offset()) as u32);
result.set_rs1(instr.rs1());
result.set_rs2(XReg::X0);
return Ok(result.0);
}
rv16::CBnez::OP_CODE => {
static_assert!(rv16::CBnez::OP_MASK == OP_MASK_5);
let instr = rv16::CBnez(instr);
let mut result = RvInstr32B(0);
result.set_opcode(RvInstr32Opcode::Branch);
result.set_funct3(RvInstr32BranchFunct3::Bne.into());
result.set_imm(i32::from(instr.offset()) as u32);
result.set_rs1(instr.rs1());
result.set_rs2(XReg::X0);
return Ok(result.0);
}
rv16::CSlli::OP_CODE => {
static_assert!(rv16::CSlli::OP_MASK == OP_MASK_5);
let instr = rv16::CSlli(instr);
let mut result = RvInstr32I(0);
// For RV32C, code points with shamt[5] == 1 are reserved
if instr.shamt() & 0x20 == 0 {
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Sli.into());
result.set_uimm(instr.shamt().into());
result.set_rs(instr.rs1rd());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
}
_ => {}
}
match instr & OP_MASK_6 {
rv16::CMv::OP_CODE => {
static_assert!(rv16::CMv::OP_MASK == OP_MASK_6);
let instr = rv16::CMv(instr);
if instr.rs2() == XReg::X0 {
let instr = rv16::CJr(instr.0);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::Jalr);
result.set_funct3(0);
result.set_imm(0);
result.set_rs(instr.rs1());
result.set_rd(XReg::X0);
return Ok(result.0);
} else {
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::Add);
result.set_rs1(XReg::X0);
result.set_rs2(instr.rs2());
result.set_rd(instr.rd());
return Ok(result.0);
}
}
rv16::CAdd::OP_CODE => {
static_assert!(rv16::CAdd::OP_MASK == OP_MASK_6);
let instr = rv16::CAdd(instr);
if instr.rs1rd() == XReg::X0 && instr.rs2() == XReg::X0 {
// EBREAK
return Ok(0x100073);
}
if instr.rs2() == XReg::X0 {
let instr = rv16::CJalr(instr.0);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::Jalr);
result.set_funct3(0);
result.set_imm(0);
result.set_rs(instr.rs1());
result.set_rd(XReg::X1);
return Ok(result.0);
} else {
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::Add);
result.set_rs1(instr.rs1rd());
result.set_rs2(instr.rs2());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
}
_ => {}
}
match instr & OP_MASK_7 {
rv16::CSrli::OP_CODE => {
static_assert!(rv16::CSrli::OP_MASK == OP_MASK_7);
let instr = rv16::CSrli(instr);
// For RV32C, code points with shamt[5] == 1 are reserved
if instr.shamt() & 0x20 == 0 {
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct7(RvInstr32OpImmFunct7::Srli.into());
result.set_funct3(RvInstr32OpImmFunct3::Sri.into());
result.set_shamt(instr.shamt());
result.set_rs(instr.rs1rd());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
}
rv16::CSrai::OP_CODE => {
static_assert!(rv16::CSrai::OP_MASK == OP_MASK_7);
let instr = rv16::CSrai(instr);
// For RV32C, code points with shamt[5] == 1 are reserved
if instr.shamt() & 0x20 == 0 {
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct7(RvInstr32OpImmFunct7::Srai.into());
result.set_funct3(RvInstr32OpImmFunct3::Sri.into());
result.set_shamt(instr.shamt());
result.set_rs(instr.rs1rd());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
}
rv16::CAndi::OP_CODE => {
static_assert!(rv16::CAndi::OP_MASK == OP_MASK_7);
let instr = rv16::CAndi(instr);
let mut result = RvInstr32I(0);
result.set_opcode(RvInstr32Opcode::OpImm);
result.set_funct3(RvInstr32OpImmFunct3::Andi.into());
result.set_imm(instr.imm().into());
result.set_rs(instr.rs1rd());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
_ => {}
}
match instr & OP_MASK_9 {
rv16::CAnd::OP_CODE => {
static_assert!(rv16::CAnd::OP_MASK == OP_MASK_9);
let instr = rv16::CAnd(instr);
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::And);
result.set_rs1(instr.rs1rd());
result.set_rs2(instr.rs2());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
rv16::COr::OP_CODE => {
static_assert!(rv16::COr::OP_MASK == OP_MASK_9);
let instr = rv16::COr(instr);
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::Or);
result.set_rs1(instr.rs1rd());
result.set_rs2(instr.rs2());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
rv16::CXor::OP_CODE => {
static_assert!(rv16::CXor::OP_MASK == OP_MASK_9);
let instr = rv16::CXor(instr);
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::Xor);
result.set_rs1(instr.rs1rd());
result.set_rs2(instr.rs2());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
rv16::CSub::OP_CODE => {
static_assert!(rv16::CSub::OP_MASK == OP_MASK_9);
let instr = rv16::CSub(instr);
let mut result = RvInstr32R(0);
result.set_opcode(RvInstr32Opcode::Op);
result.set_funct10(RvInstr32OpFunct10::Sub);
result.set_rs1(instr.rs1rd());
result.set_rs2(instr.rs2());
result.set_rd(instr.rs1rd());
return Ok(result.0);
}
_ => {}
}
Err(RvException::illegal_instr(u32::from(instr)))
}
mod rv16 {
use crate::xreg_file::XReg;
use bitfield::{bitfield, BitRangeMut};
fn bit_range(val: u16, msb: usize, lsb: usize) -> u16 {
bitfield::BitRange::bit_range(&val, msb, lsb)
}
fn sign_extend(val: u16, msb: u16) -> i16 {
let sh = 15 - msb;
((val << sh) as i16) >> sh
}
fn sign_extend_i32(val: u32, msb: u32) -> i32 {
let sh = 31 - msb;
((val << sh) as i32) >> sh
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.LWSP instruction
pub struct CLwsp(u16);
/// Destination Register
pub from into XReg, rd, set_rd: 11, 7;
}
impl CLwsp {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x4002;
pub fn uimm(&self) -> u16 {
let mut result = 0;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 2, bit_range(self.0, 6, 4));
result.set_bit_range(7, 6, bit_range(self.0, 3, 2));
result
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.SWSP instruction
pub struct CSwsp(u16);
/// Source Register
pub from into XReg, rs2, set_rs2: 6, 2;
}
impl CSwsp {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0xc002;
pub fn uimm(&self) -> u16 {
let mut result = 0;
result.set_bit_range(5, 2, bit_range(self.0, 12, 9));
result.set_bit_range(7, 6, bit_range(self.0, 8, 7));
result
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.LW instruction
pub struct CLw(u16);
}
impl CLw {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x4000;
pub fn rs1(&self) -> XReg {
XReg::from(bit_range(self.0, 9, 7) + 8)
}
pub fn rd(&self) -> XReg {
XReg::from(bit_range(self.0, 4, 2) + 8)
}
pub fn uimm(&self) -> u16 {
let mut result = 0;
result.set_bit_range(5, 3, bit_range(self.0, 12, 10));
result.set_bit_range(2, 2, bit_range(self.0, 6, 6));
result.set_bit_range(6, 6, bit_range(self.0, 5, 5));
result
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.SW instruction
pub struct CSw(u16);
}
impl CSw {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0xc000;
pub fn rs1(&self) -> XReg {
XReg::from(bit_range(self.0, 9, 7) + 8)
}
pub fn rs2(&self) -> XReg {
XReg::from(bit_range(self.0, 4, 2) + 8)
}
pub fn uimm(&self) -> u16 {
let mut result = 0;
result.set_bit_range(5, 3, bit_range(self.0, 12, 10));
result.set_bit_range(2, 2, bit_range(self.0, 6, 6));
result.set_bit_range(6, 6, bit_range(self.0, 5, 5));
result
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.J instruction
pub struct CJ(u16);
}
impl CJ {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0xa001;
pub fn imm(&self) -> i16 {
let mut result = 0u16;
result.set_bit_range(11, 11, bit_range(self.0, 12, 12));
result.set_bit_range(4, 4, bit_range(self.0, 11, 11));
result.set_bit_range(9, 8, bit_range(self.0, 10, 9));
result.set_bit_range(10, 10, bit_range(self.0, 8, 8));
result.set_bit_range(6, 6, bit_range(self.0, 7, 7));
result.set_bit_range(7, 7, bit_range(self.0, 6, 6));
result.set_bit_range(3, 1, bit_range(self.0, 5, 3));
result.set_bit_range(5, 5, bit_range(self.0, 2, 2));
sign_extend(result, 11)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.JAL instruction
pub struct CJal(u16);
}
impl CJal {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x2001;
pub fn imm(&self) -> i16 {
CJ(self.0).imm()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.ADDI instruction
pub struct CAddi(u16);
}
impl CAddi {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x0001;
pub fn nzimm(&self) -> i16 {
let mut result = 0u16;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 0, bit_range(self.0, 6, 2));
sign_extend(result, 5)
}
pub fn rs1rd(&self) -> XReg {
XReg::from(bit_range(self.0, 11, 7))
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.ADDI4SPN instruction
pub struct CAddi4spn(u16);
}
impl CAddi4spn {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x0000;
pub fn nzuimm(&self) -> u16 {
let mut result = 0u16;
result.set_bit_range(5, 4, bit_range(self.0, 12, 11));
result.set_bit_range(9, 6, bit_range(self.0, 10, 7));
result.set_bit_range(2, 2, bit_range(self.0, 6, 6));
result.set_bit_range(3, 3, bit_range(self.0, 5, 5));
result
}
pub fn rd(&self) -> XReg {
XReg::from(bit_range(self.0, 4, 2) + 8)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.ADDI16SP instruction
pub struct CAddi16sp(u16);
}
impl CAddi16sp {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
#[allow(dead_code)]
pub const OP_CODE: u16 = 0x6001;
pub fn nzimm(&self) -> i32 {
let mut result = 0u32;
result.set_bit_range(9, 9, bit_range(self.0, 12, 12));
result.set_bit_range(4, 4, bit_range(self.0, 6, 6));
result.set_bit_range(6, 6, bit_range(self.0, 5, 5));
result.set_bit_range(8, 7, bit_range(self.0, 4, 3));
result.set_bit_range(5, 5, bit_range(self.0, 2, 2));
sign_extend_i32(result, 9)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.LI instruction
pub struct CLi(u16);
}
impl CLi {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x4001;
pub fn nzimm(&self) -> i32 {
let mut result = 0u32;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 0, bit_range(self.0, 6, 2));
sign_extend_i32(result, 5)
}
pub fn rd(&self) -> XReg {
XReg::from(bit_range(self.0, 11, 7))
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.LUI instruction
pub struct CLui(u16);
}
impl CLui {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x6001;
pub fn nzimm(&self) -> i32 {
let mut d = 0u32;
d.set_bit_range(5, 5, bit_range(self.0, 12, 12));
d.set_bit_range(4, 0, bit_range(self.0, 6, 2));
let mut result = 0u32;
result.set_bit_range(17, 17, bit_range(self.0, 12, 12));
result.set_bit_range(16, 12, bit_range(self.0, 6, 2));
sign_extend_i32(result, 17)
}
pub fn rd(&self) -> XReg {
XReg::from(bit_range(self.0, 11, 7))
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.BEQZ instruction
pub struct CBeqz(u16);
}
impl CBeqz {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0xc001;
pub fn offset(&self) -> i16 {
let mut result = 0u16;
result.set_bit_range(8, 8, bit_range(self.0, 12, 12));
result.set_bit_range(4, 3, bit_range(self.0, 11, 10));
result.set_bit_range(7, 6, bit_range(self.0, 6, 5));
result.set_bit_range(2, 1, bit_range(self.0, 4, 3));
result.set_bit_range(5, 5, bit_range(self.0, 2, 2));
sign_extend(result, 8)
}
pub fn rs1(&self) -> XReg {
XReg::from(bit_range(self.0, 9, 7) + 8)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.BNEZ instruction
pub struct CBnez(u16);
}
impl CBnez {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0xe001;
pub fn offset(&self) -> i16 {
CBeqz(self.0).offset()
}
pub fn rs1(&self) -> XReg {
CBeqz(self.0).rs1()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.BNEZ instruction
pub struct CSlli(u16);
}
impl CSlli {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xe003;
pub const OP_CODE: u16 = 0x0002;
pub fn shamt(&self) -> u16 {
let mut result = 0u16;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 0, bit_range(self.0, 6, 2));
result
}
pub fn rs1rd(&self) -> XReg {
XReg::from(bit_range(self.0, 11, 7))
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.MV instruction
pub struct CMv(u16);
pub from into XReg, rd, set_rd: 11, 7;
pub from into XReg, rs2, set_rs2: 6, 2;
}
impl CMv {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xf003;
pub const OP_CODE: u16 = 0x8002;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.ADD instruction
pub struct CAdd(u16);
pub from into XReg, rs1rd, set_rs1rd: 11, 7;
pub from into XReg, rs2, set_rs2: 6, 2;
}
impl CAdd {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xf003;
pub const OP_CODE: u16 = 0x9002;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.JALR instruction
pub struct CJalr(u16);
pub from into XReg, rs1, set_rs1: 11, 7;
pub from into XReg, rs2, set_rs2: 6, 2;
}
impl CJalr {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xf07f;
#[allow(dead_code)]
pub const OP_CODE: u16 = 0x9002;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.JR instruction
pub struct CJr(u16);
pub from into XReg, rs1, set_rs1: 11, 7;
pub from into XReg, rs2, set_rs2: 6, 2;
}
impl CJr {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xf07f;
#[allow(dead_code)]
pub const OP_CODE: u16 = 0x8002;
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.SRLI instruction
pub struct CSrli(u16);
}
impl CSrli {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xec03;
pub const OP_CODE: u16 = 0x8001;
pub fn shamt(&self) -> u32 {
let mut result = 0;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 0, bit_range(self.0, 6, 2));
result
}
pub fn rs1rd(&self) -> XReg {
XReg::from(bit_range(self.0, 9, 7) + 8)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.SRAI instruction
pub struct CSrai(u16);
}
impl CSrai {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xec03;
pub const OP_CODE: u16 = 0x8401;
pub fn shamt(&self) -> u32 {
CSrli(self.0).shamt()
}
pub fn rs1rd(&self) -> XReg {
CSrli(self.0).rs1rd()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.ANDI instruction
pub struct CAndi(u16);
}
impl CAndi {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xec03;
pub const OP_CODE: u16 = 0x8801;
pub fn imm(&self) -> i16 {
let mut result = 0;
result.set_bit_range(5, 5, bit_range(self.0, 12, 12));
result.set_bit_range(4, 0, bit_range(self.0, 6, 2));
sign_extend(result, 5)
}
pub fn rs1rd(&self) -> XReg {
CSrli(self.0).rs1rd()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.AND instruction
pub struct CAnd(u16);
}
impl CAnd {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xfc63;
pub const OP_CODE: u16 = 0x8c61;
pub fn rs1rd(&self) -> XReg {
XReg::from(bit_range(self.0, 9, 7) + 8)
}
pub fn rs2(&self) -> XReg {
XReg::from(bit_range(self.0, 4, 2) + 8)
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.OR instruction
pub struct COr(u16);
}
impl COr {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xfc63;
pub const OP_CODE: u16 = 0x8c41;
pub fn rs1rd(&self) -> XReg {
CAnd(self.0).rs1rd()
}
pub fn rs2(&self) -> XReg {
CAnd(self.0).rs2()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.XOR instruction
pub struct CXor(u16);
}
impl CXor {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xfc63;
pub const OP_CODE: u16 = 0x8c21;
pub fn rs1rd(&self) -> XReg {
CAnd(self.0).rs1rd()
}
pub fn rs2(&self) -> XReg {
CAnd(self.0).rs2()
}
}
bitfield! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// RISCV C.SUB instruction
pub struct CSub(u16);
}
impl CSub {
#[allow(dead_code)]
pub const OP_MASK: u16 = 0xfc63;
pub const OP_CODE: u16 = 0x8c01;
pub fn rs1rd(&self) -> XReg {
CAnd(self.0).rs1rd()
}
pub fn rs2(&self) -> XReg {
CAnd(self.0).rs2()
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/cpu/src/instr/load.rs | sw-emulator/lib/cpu/src/instr/load.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
load.rs
Abstract:
File contains implementation of RISCV Load Instructions.
--*/
use crate::cpu::Cpu;
use crate::types::{RvInstr32I, RvInstr32LoadFunct3, RvInstr32Opcode};
use caliptra_emu_bus::Bus;
use caliptra_emu_types::{RvAddr, RvData, RvException, RvSize};
impl<TBus: Bus> Cpu<TBus> {
/// Execute load instructions
///
/// # Arguments
///
/// * `instr_tracer` - Instruction tracer
///
/// # Error
///
/// * `RvException` - Exception encountered during instruction execution
pub fn exec_load_instr(&mut self, instr: u32) -> Result<(), RvException> {
// Decode the instruction
let instr = RvInstr32I(instr);
assert_eq!(instr.opcode(), RvInstr32Opcode::Load);
// Calculate the address to load the data from
let addr = (self.read_xreg(instr.rs())? as RvAddr).wrapping_add(instr.imm() as RvAddr);
// Read the data
let data = match instr.funct3().into() {
// Load Byte ('lb') Instruction
RvInstr32LoadFunct3::Lb => self.read_bus(RvSize::Byte, addr)? as i8 as i32 as RvData,
// Load Half Word ('lh') Instruction
RvInstr32LoadFunct3::Lh => {
self.read_bus(RvSize::HalfWord, addr)? as i16 as i32 as RvData
}
// Load Word ('lw') Instruction
RvInstr32LoadFunct3::Lw => self.read_bus(RvSize::Word, addr)? as i32 as RvData,
// Load Byte Unsigned ('lbu') Instruction
RvInstr32LoadFunct3::Lbu => self.read_bus(RvSize::Byte, addr)?,
// Load Half Word Unsigned ('lhu') Instruction
RvInstr32LoadFunct3::Lhu => self.read_bus(RvSize::HalfWord, addr)?,
// Illegal Instruction
_ => Err(RvException::illegal_instr(instr.0))?,
};
// Save the contents to register
self.write_xreg(instr.rd(), data)
}
}
#[cfg(test)]
mod tests {
use crate::instr::test_encoder::tests::{lb, lbu, lh, lhu, lw};
use crate::xreg_file::XReg;
use crate::{data, db, dh, dw, isa_test, test_ld_op, text};
use lazy_static::lazy_static;
// ---------------------------------------------------------------------------------------------
// Tests for Load Byte (`lb`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lb.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LB: Vec<u8> = data![db!(0xFF); db!(0x00); db!(0xF0); db!(0x0F);];
}
// Basic Tests
test_ld_op!(test_lb_2, lb, 0xFFFF_FFFF, 0, 0x1000, DATA_LB);
test_ld_op!(test_lb_3, lb, 0x0000_0000, 1, 0x1000, DATA_LB);
test_ld_op!(test_lb_4, lb, 0xFFFF_FFF0, 2, 0x1000, DATA_LB);
test_ld_op!(test_lb_5, lb, 0x0000_000F, 3, 0x1000, DATA_LB);
// Test with negative offset
test_ld_op!(test_lb_6, lb, 0xFFFF_FFFF, -3, 0x1003, DATA_LB);
test_ld_op!(test_lb_7, lb, 0x0000_0000, -2, 0x1003, DATA_LB);
test_ld_op!(test_lb_8, lb, 0xFFFF_FFF0, -1, 0x1003, DATA_LB);
test_ld_op!(test_lb_9, lb, 0x0000_000F, -0, 0x1003, DATA_LB);
// Test with negative base
#[test]
fn test_lb_10() {
isa_test!(
0x0000 => text![
lb(XReg::X5, 32, XReg::X1);
],
0x1000 => DATA_LB,
{
XReg::X1 = 0x1000 - 32;
},
{
XReg::X5 = 0xFFFF_FFFF;
}
);
}
// Test with unaligned base
#[test]
fn test_lb_11() {
isa_test!(
0x0000 => text![
lb(XReg::X5, 7, XReg::X1);
],
0x1000 => DATA_LB,
{
XReg::X1 = 0x1000 - 6;
},
{
XReg::X5 = 0x0000_0000;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests for Load Half Word (`lh`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lh.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LH: Vec<u8> = data![dh!(0x00FF); dh!(0xFF00); dh!(0x0FF0); dh!(0xF00F);];
}
// Basic Tests
test_ld_op!(test_lh_2, lh, 0x0000_00FF, 0, 0x1000, DATA_LH);
test_ld_op!(test_lh_3, lh, 0xFFFF_FF00, 2, 0x1000, DATA_LH);
test_ld_op!(test_lh_4, lh, 0x0000_0FF0, 4, 0x1000, DATA_LH);
test_ld_op!(test_lh_5, lh, 0xFFFF_F00F, 6, 0x1000, DATA_LH);
// Test negative offset test
test_ld_op!(test_lh_6, lh, 0x0000_00FF, -6, 0x1006, DATA_LH);
test_ld_op!(test_lh_7, lh, 0xFFFF_FF00, -4, 0x1006, DATA_LH);
test_ld_op!(test_lh_8, lh, 0x0000_0FF0, -2, 0x1006, DATA_LH);
test_ld_op!(test_lh_9, lh, 0xFFFF_F00F, -0, 0x1006, DATA_LH);
// Test with negative base
#[test]
fn test_lh_10() {
isa_test!(
0x0000 => text![
lh(XReg::X5, 32, XReg::X1);
],
0x1000 => DATA_LH,
{
XReg::X1 = 0x1000 - 32;
},
{
XReg::X5 = 0x0000_00FF;
}
);
}
// Test with unaligned base
#[test]
fn test_lh_11() {
isa_test!(
0x0000 => text![
lh(XReg::X5, 7, XReg::X1);
],
0x1000 => DATA_LH,
{
XReg::X1 = 0x1000 - 5;
},
{
XReg::X5 = 0xFFFF_FF00;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests for Load Word (`lw`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lw.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LW: Vec<u8> =
data![dw!(0x00FF_00FF); dw!(0xFF00_FF00); dw!(0x0FF0_0FF0); dw!(0xF00F_F00F);];
}
// Basic Tests
test_ld_op!(test_lw_2, lw, 0x00FF_00FF, 0, 0x1000, DATA_LW);
test_ld_op!(test_lw_3, lw, 0xFF00_FF00, 4, 0x1000, DATA_LW);
test_ld_op!(test_lw_4, lw, 0x0FF0_0FF0, 8, 0x1000, DATA_LW);
test_ld_op!(test_lw_5, lw, 0xF00F_F00F, 12, 0x1000, DATA_LW);
// Tests with negative offset
test_ld_op!(test_lw_6, lw, 0x00FF_00FF, -12, 0x100C, DATA_LW);
test_ld_op!(test_lw_7, lw, 0xFF00_FF00, -8, 0x100C, DATA_LW);
test_ld_op!(test_lw_8, lw, 0x0FF0_0FF0, -4, 0x100C, DATA_LW);
test_ld_op!(test_lw_9, lw, 0xF00F_F00F, -0, 0x100C, DATA_LW);
// Test with negative base
#[test]
fn test_lw_10() {
isa_test!(
0x0000 => text![
lw(XReg::X5, 32, XReg::X1);
],
0x1000 => DATA_LW,
{
XReg::X1 = 0x1000 - 32;
},
{
XReg::X5 = 0x00FF_00FF;
}
);
}
// Test with unaligned base
#[test]
fn test_lw_11() {
isa_test!(
0x0000 => text![
lw(XReg::X5, 7, XReg::X1);
],
0x1000 => DATA_LW,
{
XReg::X1 = 0x1000 - 3;
},
{
XReg::X5 = 0xFF00_FF00;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests for Load Byte Unsigned(`lbu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lbu.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LBU: Vec<u8> = data![db!(0xFF); db!(0x00); db!(0xF0); db!(0x0F);];
}
// Basic Tests
test_ld_op!(test_lbu_2, lbu, 0x0000_00FF, 0, 0x1000, DATA_LBU);
test_ld_op!(test_lbu_3, lbu, 0x0000_0000, 1, 0x1000, DATA_LBU);
test_ld_op!(test_lbu_4, lbu, 0x0000_00F0, 2, 0x1000, DATA_LBU);
test_ld_op!(test_lbu_5, lbu, 0x0000_000F, 3, 0x1000, DATA_LBU);
// Tests with negative offset
test_ld_op!(test_lbu_6, lbu, 0x0000_00FF, -3, 0x1003, DATA_LBU);
test_ld_op!(test_lbu_7, lbu, 0x0000_0000, -2, 0x1003, DATA_LBU);
test_ld_op!(test_lbu_8, lbu, 0x0000_00F0, -1, 0x1003, DATA_LBU);
test_ld_op!(test_lbu_9, lbu, 0x0000_000F, -0, 0x1003, DATA_LBU);
// Test with negative base
#[test]
fn test_lbu_10() {
isa_test!(
0x0000 => text![
lbu(XReg::X5, 32, XReg::X1);
],
0x1000 => DATA_LBU,
{
XReg::X1 = 0x1000 - 32;
},
{
XReg::X5 = 0x0000_00FF;
}
);
}
// Test with unaligned base
#[test]
fn test_lbu_11() {
isa_test!(
0x0000 => text![
lbu(XReg::X5, 7, XReg::X1);
],
0x1000 => DATA_LBU,
{
XReg::X1 = 0x1000 - 6;
},
{
XReg::X5 = 0x0000_0000;
}
);
}
// ---------------------------------------------------------------------------------------------
// Tests for Load Half Word Unsigned (`lhu`) Instruction
//
// Test suite based on riscv-tests
// https://github.com/riscv-software-src/riscv-tests/blob/master/isa/rv64ui/lhu.S
// ---------------------------------------------------------------------------------------------
lazy_static! {
static ref DATA_LHU: Vec<u8> = data![dh!(0x00FF); dh!(0xFF00); dh!(0x0FF0); dh!(0xF00F);];
}
// Basic Tests
test_ld_op!(test_lhu_2, lhu, 0x0000_00FF, 0, 0x1000, DATA_LHU);
test_ld_op!(test_lhu_3, lhu, 0x0000_FF00, 2, 0x1000, DATA_LHU);
test_ld_op!(test_lhu_4, lhu, 0x0000_0FF0, 4, 0x1000, DATA_LHU);
test_ld_op!(test_lhu_5, lhu, 0x0000_F00F, 6, 0x1000, DATA_LHU);
// Test negative offset test
test_ld_op!(test_lhu_6, lhu, 0x0000_00FF, -6, 0x1006, DATA_LHU);
test_ld_op!(test_lhu_7, lhu, 0x0000_FF00, -4, 0x1006, DATA_LHU);
test_ld_op!(test_lhu_8, lhu, 0x0000_0FF0, -2, 0x1006, DATA_LHU);
test_ld_op!(test_lhu_9, lhu, 0x0000_F00F, -0, 0x1006, DATA_LHU);
// Test with negative base
#[test]
fn test_lhu_10() {
isa_test!(
0x0000 => text![
lhu(XReg::X5, 32, XReg::X1);
],
0x1000 => DATA_LHU,
{
XReg::X1 = 0x1000 - 32;
},
{
XReg::X5 = 0x0000_00FF;
}
);
}
// Test with unaligned base
#[test]
fn test_lhu_11() {
isa_test!(
0x0000 => text![
lhu(XReg::X5, 7, XReg::X1);
],
0x1000 => DATA_LHU,
{
XReg::X1 = 0x1000 - 5;
},
{
XReg::X5 = 0x0000_FF00;
}
);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/types/src/exception.rs | sw-emulator/lib/types/src/exception.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
exception.rs
Abstract:
File contains the implementation for RISCV exceptions
--*/
use crate::emu_enum;
emu_enum! {
/// RISCV Exception Cause
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
pub RvExceptionCause;
u32;
{
/// Instruction address misaligned exception
InstrAddrMisaligned = 0,
/// Instruction access exception
InstrAccessFault = 1,
/// Illegal instruction exception
IllegalInstr = 2,
/// Breakpoint
Breakpoint = 3,
/// Load address misaligned exception
LoadAddrMisaligned = 4,
/// Load access fault exception
LoadAccessFault = 5,
/// Store address misaligned exception
StoreAddrMisaligned = 6,
/// Store access fault exception
StoreAccessFault = 7,
/// Environment Call (User)
EnvironmentCallUser = 8,
/// Environment Call (Machine)
EnvironmentCallMachine = 11,
/// Illegal Register exception
IllegalRegister = 24,
};
Invalid
}
/// RISCV Exception
#[derive(Debug, Eq, PartialEq)]
pub struct RvException {
/// Exception cause
cause: RvExceptionCause,
/// Info
info: u32,
}
impl RvException {
/// Create a new instruction address misaligned exception
pub fn instr_addr_misaligned(addr: u32) -> Self {
RvException::new(RvExceptionCause::InstrAddrMisaligned, addr)
}
/// Create a new instruction access fault exception
pub fn instr_access_fault(addr: u32) -> Self {
RvException::new(RvExceptionCause::InstrAccessFault, addr)
}
/// Create a new illegal instruction exception
pub fn illegal_instr(instr: u32) -> Self {
RvException::new(RvExceptionCause::IllegalInstr, instr)
}
/// Create a new breakpoint exception
pub fn breakpoint(instr: u32) -> Self {
RvException::new(RvExceptionCause::Breakpoint, instr)
}
/// Create a new load address misaligned exception
pub fn load_addr_misaligned(addr: u32) -> Self {
RvException::new(RvExceptionCause::LoadAddrMisaligned, addr)
}
/// Create a new load access fault exception
pub fn load_access_fault(addr: u32) -> Self {
RvException::new(RvExceptionCause::LoadAccessFault, addr)
}
/// Create a new store address misaligned exception
pub fn store_addr_misaligned(addr: u32) -> Self {
RvException::new(RvExceptionCause::StoreAddrMisaligned, addr)
}
/// Create a new store access fault exception
pub fn store_access_fault(addr: u32) -> Self {
RvException::new(RvExceptionCause::StoreAccessFault, addr)
}
/// Create a new illegal register exception
pub fn illegal_register() -> Self {
RvException::new(RvExceptionCause::IllegalRegister, 0)
}
/// Create a new environment call from U mode exception
pub fn environment_call_user() -> Self {
RvException::new(RvExceptionCause::EnvironmentCallUser, 0)
}
/// Create a new environment call from M mode exception
pub fn environment_call_machine() -> Self {
RvException::new(RvExceptionCause::EnvironmentCallMachine, 0)
}
/// Returns the exception cause
pub fn cause(&self) -> RvExceptionCause {
self.cause
}
/// Returns the exception info
pub fn info(&self) -> u32 {
self.info
}
/// Create new exception
///
/// # Arguments
///
/// * `cause` - Exception cause
/// * `info` - Information associated with exception
fn new(cause: RvExceptionCause, info: u32) -> Self {
Self { cause, info }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_instr_addr_misaligned() {
let e = RvException::instr_addr_misaligned(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::InstrAddrMisaligned);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_instr_access_fault() {
let e = RvException::instr_access_fault(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::InstrAccessFault);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_illegal_instr() {
let e = RvException::illegal_instr(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::IllegalInstr);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_breakpoint() {
let e = RvException::breakpoint(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::Breakpoint);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_load_addr_misaligned() {
let e = RvException::load_addr_misaligned(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::LoadAddrMisaligned);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_load_access_fault() {
let e = RvException::load_access_fault(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::LoadAccessFault);
}
#[test]
fn test_store_addr_misaligned() {
let e = RvException::store_addr_misaligned(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::StoreAddrMisaligned);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_store_access_fault() {
let e = RvException::store_access_fault(u32::MAX);
assert_eq!(e.cause(), RvExceptionCause::StoreAccessFault);
assert_eq!(e.info(), u32::MAX);
}
#[test]
fn test_illegal_register() {
let e = RvException::illegal_register();
assert_eq!(e.cause(), RvExceptionCause::IllegalRegister);
assert_eq!(e.info(), 0);
}
#[test]
fn test_environment_call_user() {
let e = RvException::environment_call_user();
assert_eq!(e.cause(), RvExceptionCause::EnvironmentCallUser);
assert_eq!(e.info(), 0);
}
#[test]
fn test_environment_call_machine() {
let e = RvException::environment_call_machine();
assert_eq!(e.cause(), RvExceptionCause::EnvironmentCallMachine);
assert_eq!(e.info(), 0);
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/types/src/lib.rs | sw-emulator/lib/types/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Emulator Types library.
--*/
#![cfg_attr(not(test), no_std)]
mod exception;
mod macros;
pub use crate::exception::{RvException, RvExceptionCause};
/// RISCV Data width
pub type RvData = u32;
/// RISCV Address width
pub type RvAddr = u32;
/// RISCV Interrupt Request
pub type RvIrq = u16;
emu_enum!(
/// RISCV IO Operation size
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub RvSize;
usize;
{
Byte = 1,
HalfWord = 2,
Word = 4,
};
Invalid
);
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/types/src/macros.rs | sw-emulator/lib/types/src/macros.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
macros.rs
Abstract:
Macros used by the project
--*/
#[macro_export]
macro_rules! emu_enum {
(
$(#[$($enum_attrs:tt)*])*
$vis:vis $enum_name:ident;
$type:ty;
{
$(
$(#[$($attrs:tt)*])*
$name:ident = $value:literal,
)*
};
$invalid:ident
) => {
$(#[$($enum_attrs)*])*
$vis enum $enum_name {
$(
$(#[$($attrs)*])*
$name = $value,
)*
$invalid
}
impl From<$enum_name> for $type {
fn from(val: $enum_name) -> $type {
match val {
$($enum_name::$name => $value,)*
$enum_name::$invalid => panic!(),
}
}
}
impl From<$type> for $enum_name {
fn from(val: $type) -> $enum_name{
match val {
$($value => $enum_name::$name,)*
_ => $enum_name::$invalid,
}
}
}
};
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/rom.rs | sw-emulator/lib/bus/src/rom.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
rom.rs
Abstract:
File contains implementation of ROM
--*/
use crate::mem::Mem;
use crate::{Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
/// Read Only Memory Device
pub struct Rom {
/// Read Only Data
data: Mem,
}
impl Rom {
/// Create new ROM
///
/// # Arguments
///
/// * `name` - Name of the device
/// * `addr` - Address of the ROM in the address map
/// * `data` - Data to be stored in the ROM
pub fn new(data: Vec<u8>) -> Self {
Self {
data: Mem::new(data),
}
}
/// Size of the memory in bytes
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> RvAddr {
self.data.len() as RvAddr
}
/// Immutable reference to data
pub fn data(&self) -> &[u8] {
self.data.data()
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8] {
self.data.data_mut()
}
}
impl Bus for Rom {
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
/// * `addr` - Address to read from
///
/// # Error
///
/// * `BusException` - Exception with cause `BusExceptionCause::LoadAccessFault`
/// or `BusExceptionCause::LoadAddrMisaligned`
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match self.data.read(size, addr) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `addr` - Address to write
/// * `data` - Data to write
///
/// # Error
///
/// * `BusException` - Exception with cause `BusExceptionCause::StoreAccessFault`
/// or `BusExceptionCause::StoreAddrMisaligned`
fn write(&mut self, _size: RvSize, _addr: RvAddr, _value: RvData) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let _rom = Rom::new(vec![1, 2, 3, 4]);
}
#[test]
fn test_mmap_size() {
let rom = Rom::new(vec![1, 2, 3, 4]);
assert_eq!(rom.len(), 4)
}
#[test]
fn test_read() {
let mut rom = Rom::new(vec![1, 2, 3, 4]);
assert_eq!(rom.read(RvSize::Byte, 0).ok(), Some(1));
assert_eq!(rom.read(RvSize::HalfWord, 0).ok(), Some(1 | (2 << 8)));
assert_eq!(
rom.read(RvSize::Word, 0).ok(),
Some(1 | (2 << 8) | (3 << 16) | (4 << 24))
);
}
#[test]
fn test_read_error() {
let mut rom = Rom::new(vec![1, 2, 3, 4]);
assert_eq!(
rom.read(RvSize::Byte, rom.len()).err(),
Some(BusError::LoadAccessFault),
)
}
#[test]
fn test_write() {
let mut rom = Rom::new(vec![1, 2, 3, 4]);
assert_eq!(
rom.write(RvSize::Byte, 0, u32::MAX).err(),
Some(BusError::StoreAccessFault),
)
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/event.rs | sw-emulator/lib/bus/src/event.rs | // Licensed under the Apache-2.0 license.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
pub src: Device,
pub dest: Device,
pub event: EventData,
}
impl Event {
pub fn new(src: Device, dest: Device, event: EventData) -> Self {
Self { src, dest, event }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Device {
CaliptraCore,
MCU,
BMC,
TestSram,
ExternalTestSram,
RecoveryIntf,
McuMbox0Sram,
McuMbox1Sram,
External(&'static str),
}
#[derive(Clone, Debug, PartialEq)]
pub enum EventData {
WireRequest {
name: &'static str,
},
WireValue {
name: &'static str,
value: u32,
},
MemoryRead {
start_addr: u32,
len: u32,
},
MemoryReadResponse {
start_addr: u32,
data: Vec<u8>,
},
MemoryWrite {
start_addr: u32,
data: Vec<u8>,
},
RecoveryBlockReadRequest {
source_addr: u8,
target_addr: u8,
command_code: RecoveryCommandCode,
},
RecoveryBlockReadResponse {
source_addr: u8,
target_addr: u8,
command_code: RecoveryCommandCode,
payload: Vec<u8>,
},
RecoveryBlockWrite {
source_addr: u8,
target_addr: u8,
command_code: RecoveryCommandCode,
payload: Vec<u8>,
},
RecoveryImageAvailable {
image_id: u8,
image: Vec<u8>,
},
RecoveryFifoStatusRequest,
RecoveryFifoStatusResponse {
status: u32,
},
I3CBlock {
source_addr: u8,
dest_addr: u8,
ibi: u8,
descriptor: [u8; 8],
data: Vec<u8>,
},
MciInterrupt {
asserted: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RecoveryCommandCode {
ProtCap,
DeviceId,
DeviceStatus,
DeviceReset,
RecoveryCtrl,
RecoveryStatus,
HwStatus,
IndirectCtrl,
IndirectStatus,
IndirectData,
Vendor,
IndirectFifoCtrl,
IndirectFifoStatus,
IndirectFifoData,
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/register.rs | sw-emulator/lib/bus/src/register.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
register.rs
Abstract:
File contains implementation of various register types used by peripherals
--*/
use crate::mem::Mem;
use crate::{Bus, BusError};
use caliptra_emu_types::{RvAddr, RvData, RvSize};
use tock_registers::interfaces::{Readable, Writeable};
use tock_registers::registers::InMemoryRegister;
use tock_registers::{LocalRegisterCopy, RegisterLongName, UIntLike};
pub trait Register {
/// Size of the register in bytes.
const SIZE: usize;
/// Read data of specified size from given address
///
/// # Arguments
///
/// * `size` - Size of the read
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::LoadAccessFault` or `BusError::LoadAddrMisaligned`
fn read(&self, size: RvSize) -> Result<RvData, BusError>;
/// Write data of specified size to given address
///
/// # Arguments
///
/// * `size` - Size of the write
/// * `val` - Data to write
///
/// # Error
///
/// * `BusError` - Exception with cause `BusError::StoreAccessFault` or `BusError::StoreAddrMisaligned`
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError>;
}
/// Rv Data Conversion Trait
trait RvDataConverter<T: UIntLike> {
/// Convert `RvData` to type `T`
///
/// # Arguments
///
/// * `val` - Data to convert
///
/// # Returns
///
/// * `T` - The converted value
fn from(val: RvData) -> T;
/// Convert `T` to type `RvData`
///
/// # Arguments
///
/// * `val` - Data to convert
///
/// # Returns
///
/// * `RvData` - The converted value
fn to(val: T) -> RvData;
}
impl RvDataConverter<u8> for u8 {
/// Convert `RvData` to type `u8`
fn from(val: RvData) -> u8 {
(val & u8::MAX as RvData) as u8
}
/// Convert `u8` to type `RvData`
fn to(val: u8) -> RvData {
val as RvData
}
}
impl RvDataConverter<u16> for u16 {
/// Convert `RvData` to type `u16`
fn from(val: RvData) -> u16 {
(val & u16::MAX as RvData) as u16
}
/// Convert `u16` to type `RvData`
fn to(val: u16) -> RvData {
val as RvData
}
}
impl RvDataConverter<u32> for u32 {
/// Convert `RvData` to type `u32`
fn from(val: RvData) -> u32 {
val
}
/// Convert `u32` to type `RvData`
fn to(val: u32) -> RvData {
val
}
}
impl Register for u8 {
const SIZE: usize = std::mem::size_of::<Self>();
/// Read data of specified size from given address
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
match size {
RvSize::Byte => Ok(u8::to(*self)),
_ => Err(BusError::LoadAccessFault),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
match size {
RvSize::Byte => {
*self = val as u8;
Ok(())
}
_ => Err(BusError::StoreAccessFault),
}
}
}
impl Register for u16 {
const SIZE: usize = std::mem::size_of::<Self>();
/// Read data of specified size from given address
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
match size {
RvSize::HalfWord => Ok(u16::to(*self)),
_ => Err(BusError::LoadAccessFault),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
match size {
RvSize::HalfWord => {
*self = val as u16;
Ok(())
}
_ => Err(BusError::StoreAccessFault),
}
}
}
impl Register for u32 {
const SIZE: usize = std::mem::size_of::<Self>();
/// Read data of specified size from given address
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
match size {
RvSize::Word => Ok(u32::to(*self)),
_ => Err(BusError::LoadAccessFault),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
match size {
RvSize::Word => {
*self = val;
Ok(())
}
_ => Err(BusError::StoreAccessFault),
}
}
}
impl<T: UIntLike + Register, R: RegisterLongName> Register for LocalRegisterCopy<T, R> {
const SIZE: usize = T::SIZE;
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
Register::read(&self.get(), size)
}
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
let mut tmp = T::zero();
Register::write(&mut tmp, size, val)?;
self.set(tmp);
Ok(())
}
}
/// Read Write Register
pub struct ReadWriteRegister<T: UIntLike, R: RegisterLongName = ()> {
/// Register
pub reg: InMemoryRegister<T, R>,
}
impl<T: UIntLike, R: RegisterLongName> ReadWriteRegister<T, R> {
/// Create an instance of Read Write Register
pub fn new(val: T) -> Self {
Self {
reg: InMemoryRegister::new(val),
}
}
}
impl<T: UIntLike + RvDataConverter<T>, R: RegisterLongName> Register for ReadWriteRegister<T, R> {
const SIZE: usize = std::mem::size_of::<T>();
/// Read data of specified size from given address
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
if std::mem::size_of::<T>() != size.into() {
Err(BusError::LoadAccessFault)?
}
Ok(T::to(self.reg.get()))
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
if std::mem::size_of::<T>() != size.into() {
Err(BusError::StoreAccessFault)?
}
self.reg.set(T::from(val));
Ok(())
}
}
/// Read Only Register
pub struct ReadOnlyRegister<T: UIntLike, R: RegisterLongName = ()> {
/// Register
pub reg: InMemoryRegister<T, R>,
}
impl<T: UIntLike, R: RegisterLongName> ReadOnlyRegister<T, R> {
/// Create an instance of Read Only Register
pub fn new(val: T) -> Self {
Self {
reg: InMemoryRegister::new(val),
}
}
}
impl<T: UIntLike + RvDataConverter<T>, R: RegisterLongName> Register for ReadOnlyRegister<T, R>
where
RvData: From<T>,
{
const SIZE: usize = std::mem::size_of::<T>();
/// Read data of specified size from given address
fn read(&self, size: RvSize) -> Result<RvData, BusError> {
if std::mem::size_of::<T>() != size.into() {
Err(BusError::LoadAccessFault)?
}
Ok(T::to(self.reg.get()))
}
/// Write data of specified size to given address
fn write(&mut self, _size: RvSize, _val: RvData) -> Result<(), BusError> {
// Silently ignore writes to read-only registers
Ok(())
}
}
impl<T: UIntLike, R: RegisterLongName> From<T> for ReadWriteRegister<T, R> {
fn from(value: T) -> Self {
Self::new(value)
}
}
/// Write Only Register
pub struct WriteOnlyRegister<T: UIntLike, R: RegisterLongName = ()> {
pub reg: InMemoryRegister<T, R>,
}
impl<T: UIntLike, R: RegisterLongName> WriteOnlyRegister<T, R> {
/// Create an instance of Write Only Register
pub fn new(val: T) -> Self {
Self {
reg: InMemoryRegister::new(val),
}
}
}
impl<T: UIntLike + RvDataConverter<T>, R: RegisterLongName> Register for WriteOnlyRegister<T, R>
where
RvData: From<T>,
{
const SIZE: usize = std::mem::size_of::<T>();
/// Read data of specified size from given address
fn read(&self, _size: RvSize) -> Result<RvData, BusError> {
Err(BusError::LoadAccessFault)?
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, val: RvData) -> Result<(), BusError> {
if std::mem::size_of::<T>() != size.into() {
Err(BusError::StoreAccessFault)?
}
self.reg.set(T::from(val));
Ok(())
}
}
/// Fixed sized Read Write Memory
pub struct ReadWriteMemory<const N: usize> {
data: Mem,
}
impl<const N: usize> ReadWriteMemory<N> {
/// Create an instance of Read Write Memory
pub fn new() -> Self {
Self {
data: Mem::new(vec![0u8; N]),
}
}
/// Create an instance of Read Only Memory with data
pub fn new_with_data(data: [u8; N]) -> Self {
Self {
data: Mem::new(Vec::from(data)),
}
}
/// Size of the memory in bytes
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> RvAddr {
self.data.len() as RvAddr
}
/// Immutable reference to data
pub fn data(&self) -> &[u8; N] {
let ptr = self.data.data().as_ptr() as *const [u8; N];
unsafe { &*ptr }
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8; N] {
let ptr = self.data.data_mut().as_mut_ptr() as *mut [u8; N];
unsafe { &mut *ptr }
}
}
impl<const N: usize> Bus for ReadWriteMemory<N> {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match self.data.read(size, addr) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match self.data.write(size, addr, val) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
}
impl<const N: usize> Default for ReadWriteMemory<N> {
fn default() -> Self {
Self::new()
}
}
/// Fixed sized Read Only Memory
pub struct ReadOnlyMemory<const N: usize> {
data: Mem,
}
impl<const N: usize> ReadOnlyMemory<N> {
/// Create an instance of Read Only Memory
pub fn new() -> Self {
Self {
data: Mem::new(vec![0u8; N]),
}
}
/// Create an instance of Read Only Memory with data
pub fn new_with_data(data: [u8; N]) -> Self {
Self {
data: Mem::new(Vec::from(data)),
}
}
/// Size of the memory in bytes
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> RvAddr {
self.data.len() as RvAddr
}
/// Immutable reference to data
pub fn data(&self) -> &[u8; N] {
let ptr = self.data.data().as_ptr() as *const [u8; N];
unsafe { &*ptr }
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8; N] {
let ptr = self.data.data_mut().as_mut_ptr() as *mut [u8; N];
unsafe { &mut *ptr }
}
}
impl<const N: usize> Bus for ReadOnlyMemory<N> {
/// Read data of specified size from given address
fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, BusError> {
match self.data.read(size, addr) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
/// Write data of specified size to given address
fn write(&mut self, _size: RvSize, _addr: RvAddr, _val: RvData) -> Result<(), BusError> {
Err(BusError::StoreAccessFault)
}
}
impl<const N: usize> Default for ReadOnlyMemory<N> {
fn default() -> Self {
Self::new()
}
}
/// Fixed sized Write Only Memory
pub struct WriteOnlyMemory<const N: usize> {
data: Mem,
}
impl<const N: usize> WriteOnlyMemory<N> {
/// Create an instance of Write Only Memory
pub fn new() -> Self {
Self {
data: Mem::new(vec![0u8; N]),
}
}
/// Size of the memory in bytes
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> RvAddr {
self.data.len() as RvAddr
}
/// Immutable reference to data
pub fn data(&self) -> &[u8; N] {
let ptr = self.data.data().as_ptr() as *const [u8; N];
unsafe { &*ptr }
}
/// Mutable reference to data
pub fn data_mut(&mut self) -> &mut [u8; N] {
let ptr = self.data.data_mut().as_mut_ptr() as *mut [u8; N];
unsafe { &mut *ptr }
}
}
impl<const N: usize> Bus for WriteOnlyMemory<N> {
/// Read data of specified size from given address
fn read(&mut self, _size: RvSize, _addr: RvAddr) -> Result<RvData, BusError> {
Err(BusError::LoadAccessFault)
}
/// Write data of specified size to given address
fn write(&mut self, size: RvSize, addr: RvAddr, val: RvData) -> Result<(), BusError> {
match self.data.write(size, addr, val) {
Ok(data) => Ok(data),
Err(error) => Err(error.into()),
}
}
}
impl<const N: usize> Default for WriteOnlyMemory<N> {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_u8_read_write_reg() {
let mut reg = ReadWriteRegister::<u8>::new(0);
assert_eq!(reg.read(RvSize::Byte).ok(), Some(0));
assert_eq!(reg.write(RvSize::Byte, u32::MAX).ok(), Some(()));
assert_eq!(reg.read(RvSize::Byte).ok(), Some(u8::MAX as RvData));
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::HalfWord, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::Word, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::HalfWord, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_u16_read_write_reg() {
let mut reg = ReadWriteRegister::<u16>::new(0);
assert_eq!(reg.read(RvSize::HalfWord).ok(), Some(0));
assert_eq!(
reg.write(RvSize::HalfWord, u32::MAX as RvData).ok(),
Some(())
);
assert_eq!(reg.read(RvSize::HalfWord).ok(), Some(u16::MAX as RvData));
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::Byte, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::Word, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_u32_read_write_reg() {
let mut reg = ReadWriteRegister::<u32>::new(0);
assert_eq!(reg.read(RvSize::Word).ok(), Some(0));
assert_eq!(reg.write(RvSize::Word, u32::MAX).ok(), Some(()));
assert_eq!(reg.read(RvSize::Word).ok(), Some(u32::MAX));
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::Byte, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::HalfWord, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_u8_readonly_reg() {
let mut reg = ReadOnlyRegister::<u8>::new(u8::MAX);
assert_eq!(reg.read(RvSize::Byte).ok(), Some(u8::MAX as RvData));
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
// Writes to read-only registers should succeed but be ignored
assert_eq!(reg.write(RvSize::Byte, 0x00).ok(), Some(()));
assert_eq!(reg.read(RvSize::Byte).ok(), Some(u8::MAX as RvData)); // Value unchanged
assert_eq!(reg.write(RvSize::HalfWord, 0x00).ok(), Some(()));
assert_eq!(reg.write(RvSize::Word, 0x00).ok(), Some(()));
}
#[test]
fn test_u16_readonly_reg() {
let mut reg = ReadOnlyRegister::<u16>::new(u16::MAX);
assert_eq!(reg.read(RvSize::HalfWord).ok(), Some(u16::MAX as RvData));
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
// Writes to read-only registers should succeed but be ignored
assert_eq!(reg.write(RvSize::Byte, 0x00).ok(), Some(()));
assert_eq!(reg.write(RvSize::HalfWord, 0x00).ok(), Some(()));
assert_eq!(reg.read(RvSize::HalfWord).ok(), Some(u16::MAX as RvData)); // Value unchanged
assert_eq!(reg.write(RvSize::Word, 0x00).ok(), Some(()));
}
#[test]
fn test_u32_readonly_reg() {
let mut reg = ReadOnlyRegister::<u32>::new(u32::MAX);
assert_eq!(reg.read(RvSize::Word).ok(), Some(u32::MAX));
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
// Writes to read-only registers should succeed but be ignored
assert_eq!(reg.write(RvSize::Byte, 0x00).ok(), Some(()));
assert_eq!(reg.write(RvSize::HalfWord, 0x00).ok(), Some(()));
assert_eq!(reg.write(RvSize::Word, 0x00).ok(), Some(()));
assert_eq!(reg.read(RvSize::Word).ok(), Some(u32::MAX)); // Value unchanged
}
#[test]
fn test_u8_writeonly_reg() {
let mut reg = WriteOnlyRegister::<u8>::new(0);
assert_eq!(reg.write(RvSize::Byte, u32::MAX).ok(), Some(()));
assert_eq!(reg.reg.get(), u8::MAX);
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::HalfWord, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::Word, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_u16_writeonly_reg() {
let mut reg = WriteOnlyRegister::<u16>::new(0);
assert_eq!(reg.write(RvSize::HalfWord, u32::MAX).ok(), Some(()));
assert_eq!(reg.reg.get(), u16::MAX);
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::Byte, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::Word, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_u32_writeonly_reg() {
let mut reg = WriteOnlyRegister::<u32>::new(0);
assert_eq!(reg.write(RvSize::Word, u32::MAX).ok(), Some(()));
assert_eq!(reg.reg.get(), u32::MAX);
assert_eq!(
reg.read(RvSize::Byte).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::HalfWord).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.read(RvSize::Word).err(),
Some(BusError::LoadAccessFault)
);
assert_eq!(
reg.write(RvSize::Byte, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
reg.write(RvSize::HalfWord, 0xFF).err(),
Some(BusError::StoreAccessFault)
);
}
#[test]
fn test_read_write_mem() {
const N: usize = 32;
let mut mem = ReadWriteMemory::<N>::new();
for i in 0..N {
assert_eq!(
mem.write(RvSize::Byte, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(
mem.read(RvSize::Byte, i as RvAddr).ok(),
Some(u8::MAX as RvData)
);
}
for i in (0..N).step_by(2) {
assert_eq!(
mem.write(RvSize::HalfWord, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(
mem.read(RvSize::HalfWord, i as RvAddr).ok(),
Some(u16::MAX as RvData)
);
}
for i in (0..N).step_by(4) {
assert_eq!(
mem.write(RvSize::Word, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(mem.read(RvSize::Word, i as RvAddr).ok(), Some(u32::MAX));
}
}
#[test]
fn test_read_only_mem() {
const N: usize = 32;
let mut mem = ReadOnlyMemory::<N>::new_with_data([0xFFu8; N]);
for i in 0..N {
assert_eq!(
mem.write(RvSize::Byte, i as RvAddr, u32::MAX).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
mem.read(RvSize::Byte, i as RvAddr).ok(),
Some(u8::MAX as RvData)
);
}
for i in (0..N).step_by(2) {
assert_eq!(
mem.write(RvSize::HalfWord, i as RvAddr, u32::MAX).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(
mem.read(RvSize::HalfWord, i as RvAddr).ok(),
Some(u16::MAX as RvData)
);
}
for i in (0..N).step_by(4) {
assert_eq!(
mem.write(RvSize::Word, i as RvAddr, u32::MAX).err(),
Some(BusError::StoreAccessFault)
);
assert_eq!(mem.read(RvSize::Word, i as RvAddr).ok(), Some(u32::MAX));
}
}
#[test]
fn test_write_only_mem() {
const N: usize = 32;
let mut mem = WriteOnlyMemory::<N>::new();
for i in 0..N {
assert_eq!(
mem.write(RvSize::Byte, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(mem.data()[i], u8::MAX);
assert_eq!(
mem.read(RvSize::Byte, i as RvAddr).err(),
Some(BusError::LoadAccessFault)
);
}
for i in (0..N).step_by(2) {
assert_eq!(
mem.write(RvSize::HalfWord, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(mem.data()[i..i + 2], [u8::MAX; 2]);
assert_eq!(
mem.read(RvSize::Byte, i as RvAddr).err(),
Some(BusError::LoadAccessFault)
)
}
for i in (0..N).step_by(4) {
assert_eq!(
mem.write(RvSize::Word, i as RvAddr, u32::MAX).ok(),
Some(())
);
assert_eq!(mem.data()[i..i + 4], [u8::MAX; 4]);
assert_eq!(
mem.read(RvSize::Byte, i as RvAddr).err(),
Some(BusError::LoadAccessFault)
)
}
}
}
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
chipsalliance/caliptra-sw | https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/sw-emulator/lib/bus/src/lib.rs | sw-emulator/lib/bus/src/lib.rs | /*++
Licensed under the Apache-2.0 license.
File Name:
lib.rs
Abstract:
File contains exports for for Caliptra Emulator Bus library.
--*/
mod bus;
mod clock;
mod dynamic_bus;
mod event;
mod mem;
mod mmio;
mod ram;
mod register;
mod register_array;
mod rom;
pub mod testing;
pub use crate::bus::{Bus, BusError};
pub use crate::clock::{ActionHandle, Clock, Timer, TimerAction};
pub use crate::dynamic_bus::DynamicBus;
pub use crate::event::{Device, Event, EventData, RecoveryCommandCode};
pub use crate::mmio::BusMmio;
pub use crate::ram::{AlignedRam, Ram};
pub use crate::register::{
ReadOnlyMemory, ReadOnlyRegister, ReadWriteMemory, ReadWriteRegister, Register,
WriteOnlyMemory, WriteOnlyRegister,
};
pub use crate::register_array::{ReadWriteRegisterArray, RegisterArray};
pub use crate::rom::Rom;
| rust | Apache-2.0 | d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c | 2026-01-04T20:21:36.839730Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.