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
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/complex_one_color.rs
examples/2d/complex_one_color.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "2d_complex_one_color".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("asteroid_field.svg"); commands.spawn((Camera2d, Msaa::Sample4)); commands.spawn(( Svg2d(svg), Origin::Center, Transform { scale: Vec3::new(2.0, 2.0, 1.0), ..Default::default() }, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/two_colors.rs
examples/2d/two_colors.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "2d_two_colors".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("neutron_star.svg"); commands.spawn(Camera2d); commands.spawn((Svg2d(svg), Origin::Center)); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/multiple_translation.rs
examples/2d/multiple_translation.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "2d_multiple_translation".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .add_systems(Update, svg_movement) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("asteroid_field.svg"); commands.spawn(Camera2d); commands.spawn(( Svg2d(svg), Origin::Center, Transform { translation: Vec3::new(100.0, 0.0, 0.0), scale: Vec3::new(2.0, 2.0, 1.0), ..Default::default() }, Direction::Up, )); let svg = asset_server.load("neutron_star.svg"); commands.spawn((Svg2d(svg), Origin::Center, Direction::Up)); } #[derive(Component)] enum Direction { Up, Down, } fn svg_movement( time: Res<Time>, mut svg_position: Query<(&mut Direction, &mut Transform), With<Svg2d>>, ) { for (mut direction, mut transform) in &mut svg_position { match *direction { Direction::Up => transform.translation.y += 150. * time.delta_secs(), Direction::Down => transform.translation.y -= 150. * time.delta_secs(), } if transform.translation.y > 200. { *direction = Direction::Down; } else if transform.translation.y < -200. { *direction = Direction::Up; } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/twinkle.rs
examples/2d/twinkle.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "2d_twinkle".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("twinkle.svg"); commands.spawn(Camera2d); commands.spawn((Svg2d(svg), Origin::Center)); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/common/lib.rs
examples/common/lib.rs
use bevy::color::palettes::css::{GOLD, GREEN}; use bevy::input::mouse::{MouseScrollUnit, MouseWheel}; use bevy::text::TextSpanAccess; use bevy::{ diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin}, prelude::*, }; use bevy_svg::prelude::*; /// Provides some common functionallity for all examples. /// Like toggling visibility and through origin. pub struct CommonPlugin; impl Plugin for CommonPlugin { fn build(&self, app: &mut App) { app.add_plugins(FrameTimeDiagnosticsPlugin::default()) .add_systems( Startup, (setup_legend, setup_fps_counter, setup_origin_text), ) .add_systems( Update, ( keyboard_input_system, fps_text_update_system, origin_text_update_system, camera_zoom_system, camera_pan_system, ), ); } } fn setup_legend(mut commands: Commands, asset_server: Res<AssetServer>) { let font_bold = asset_server.load("fonts/FiraSans-Bold.ttf"); let font_medium = asset_server.load("fonts/FiraMono-Medium.ttf"); commands .spawn(( Text::default(), TextColor::WHITE, TextFont::from_font_size(20.0).with_font(font_medium), Node { position_type: PositionType::Absolute, top: Val::Px(5.0), right: Val::Px(15.0), ..default() }, )) .with_children(|commands| { commands.spawn(( TextSpan::new("Key Info"), TextFont::from_font_size(30.0).with_font(font_bold.clone()), )); commands.spawn(( TextSpan::new("\nF"), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn(TextSpan::new(" - Toggle Frame Diagnostics")); commands.spawn(( TextSpan::new("\nO"), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn(TextSpan::new(" - Cycle through Origins")); commands.spawn(( TextSpan::new("\nV"), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn(TextSpan::new(" - Toggle visibility")); }); } #[derive(Component)] pub struct DontChange; /// This system toggles SVG visibility when 'V' is pressed and toggles through /// origin when 'O' is pressed. fn keyboard_input_system( keyboard_input: Res<ButtonInput<KeyCode>>, mut svg_query: Query< (&mut Origin, &mut Visibility), (Or<(With<Svg2d>, With<Svg3d>)>, Without<DontChange>), >, mut ui_query: Query< &mut Visibility, ( With<Text>, Or<(With<FpsTextRoot>, With<OriginTextRoot>)>, Without<Svg2d>, Without<Svg3d>, ), >, ) { if keyboard_input.just_pressed(KeyCode::KeyV) { for (_, mut visible) in svg_query.iter_mut() { *visible = match *visible { Visibility::Hidden => Visibility::Inherited, Visibility::Visible | Visibility::Inherited => Visibility::Hidden, }; } } else if keyboard_input.just_pressed(KeyCode::KeyO) { for (mut origin, _) in svg_query.iter_mut() { *origin = match origin.as_ref() { Origin::BottomLeft => Origin::BottomRight, Origin::BottomRight => Origin::TopRight, Origin::Center => Origin::BottomLeft, Origin::TopLeft => Origin::Center, Origin::TopRight => Origin::TopLeft, Origin::Custom(coord) => Origin::Custom(*coord), } } } else if keyboard_input.just_pressed(KeyCode::KeyF) { for mut visible in &mut ui_query { *visible = match *visible { Visibility::Hidden => Visibility::Inherited, Visibility::Visible | Visibility::Inherited => Visibility::Hidden, }; } } } #[derive(Component)] struct FpsText; #[derive(Component)] struct FpsMinText; #[derive(Component)] struct FpsMaxText; #[derive(Component)] struct FrameTimeText; #[derive(Component)] struct FpsTextRoot; #[derive(Resource)] struct FpsValues { min: f64, max: f64, } impl Default for FpsValues { fn default() -> Self { Self { min: 10000.0, max: 0.0, } } } fn setup_fps_counter(mut commands: Commands, asset_server: Res<AssetServer>) { let font_bold = asset_server.load("fonts/FiraSans-Bold.ttf"); let font_medium = asset_server.load("fonts/FiraMono-Medium.ttf"); commands .spawn(( Text::default(), TextColor::WHITE, TextFont::from_font_size(20.0).with_font(font_medium), Node { position_type: PositionType::Absolute, top: Val::Px(5.0), left: Val::Px(15.0), ..default() }, FpsTextRoot, )) .with_children(|commands| { commands.spawn(( TextSpan::new("FPS: "), TextFont::from_font_size(30.0).with_font(font_bold.clone()), )); commands.spawn(( TextSpan::default(), TextFont::from_font_size(30.0), TextColor::from(GOLD), FpsText, )); commands.spawn(( TextSpan::new("\n(min: "), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn((TextSpan::default(), TextColor::from(GOLD), FpsMinText)); commands.spawn(( TextSpan::new(" - max: "), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn((TextSpan::default(), TextColor::from(GOLD), FpsMaxText)); commands.spawn(( TextSpan::new(")"), TextFont::from_font_size(20.0).with_font(font_bold.clone()), )); commands.spawn(( TextSpan::new("\nms/frame: "), TextFont::from_font_size(30.0).with_font(font_bold.clone()), )); commands.spawn(( TextSpan::default(), TextFont::from_font_size(30.0), TextColor::from(GREEN), FrameTimeText, )); }); } fn fps_text_update_system( diagnostics: Res<DiagnosticsStore>, mut fps_values: Local<FpsValues>, mut query: ParamSet<( Query<&mut TextSpan, With<FpsText>>, Query<&mut TextSpan, With<FpsMinText>>, Query<&mut TextSpan, With<FpsMaxText>>, Query<&mut TextSpan, With<FrameTimeText>>, )>, ) { if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) { if let Some(fps_smoothed) = fps.smoothed() { if let Ok(mut text) = query.p0().single_mut() { *text.write_span() = format!("{fps_smoothed:.2}"); } fps_values.min = fps_values.min.min(fps_smoothed); if let Ok(mut text) = query.p1().single_mut() { *text.write_span() = format!("{:.2}", fps_values.min); } fps_values.max = fps_values.max.max(fps_smoothed); if let Ok(mut text) = query.p2().single_mut() { *text.write_span() = format!("{:.2}", fps_values.max); } } } if let Some(frame_time) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME) { if let Some(frame_time_smoothed) = frame_time.smoothed() { if let Ok(mut text) = query.p3().single_mut() { *text.write_span() = format!("{frame_time_smoothed:.2}"); } } } } #[derive(Component)] struct OriginText; #[derive(Component)] struct OriginTextRoot; fn setup_origin_text(mut commands: Commands, asset_server: Res<AssetServer>) { let font_bold = asset_server.load("fonts/FiraSans-Bold.ttf"); let font_medium = asset_server.load("fonts/FiraMono-Medium.ttf"); commands .spawn(( Text::default(), TextColor::WHITE, TextFont::from_font_size(20.0).with_font(font_medium), Node { position_type: PositionType::Absolute, bottom: Val::Px(5.0), left: Val::Px(15.0), ..default() }, OriginTextRoot, )) .with_children(|commands| { commands.spawn(( TextSpan::new("Origin: "), TextFont::from_font_size(20.0).with_font(font_bold), )); commands.spawn((TextSpan::default(), TextColor::from(GOLD), OriginText)); }); } fn origin_text_update_system( mut text_query: Query<&mut TextSpan, With<OriginText>>, query: Query<&Origin>, ) { for mut text in &mut text_query { if let Some(origin) = query.iter().next() { *text.write_span() = format!("{origin:?}"); } } } pub fn camera_zoom_system( mut evr_scroll: MessageReader<MouseWheel>, mut camera: Query<(Option<Mut<Projection>>, Mut<Transform>), With<Camera>>, ) { for ev in evr_scroll.read() { for (projection, mut transform) in camera.iter_mut() { let amount = match ev.unit { MouseScrollUnit::Line => ev.y, MouseScrollUnit::Pixel => ev.y, }; if let Some(mut projection) = projection { if let Projection::Orthographic(ref mut projection) = *projection { projection.scale -= if projection.scale <= 1.0 { amount * 0.05 } else { amount }; projection.scale = projection.scale.clamp(0.01, 10.0); } } else { transform.translation.z -= amount; } } } } pub fn camera_pan_system( input: Res<ButtonInput<KeyCode>>, mut camera: Query<Mut<Transform>, With<Camera>>, ) { for mut transform in camera.iter_mut() { if input.pressed(KeyCode::KeyW) { transform.translation.y += 1.0; } if input.pressed(KeyCode::KeyS) { transform.translation.y -= 1.0; } if input.pressed(KeyCode::KeyA) { transform.translation.x -= 1.0; } if input.pressed(KeyCode::KeyD) { transform.translation.x += 1.0; } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/nth_naive.rs
src/bin/nth_naive.rs
// It's now hardcoded how many numbers fibonacci_array() calculates const FIBONACCI_NUMS: usize = 100; // Inspect the resulting assembly using: // cargo asm --rust --bin nth_naive nth_fibonacci #[inline(never)] // so that we can easily view the assembly fn nth_fibonacci(n: usize, fibonacci: &[u64]) -> u64 { fibonacci[n] } fn fibonacci_vec() -> Vec<u64> { let length = FIBONACCI_NUMS; let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute the result let arg = std::env::args().nth(1).expect("Please specify the number to look up"); let index: usize = arg.parse().expect("Lookup index is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(); // actually call the function we care about let result = nth_fibonacci(index, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_split.rs
src/bin/comparison_split.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin comparison_split elements_are_equal #[inline(never)] // so that we can easily view the assembly fn elements_are_equal(slice1: &[u64], slice2: &[u64], index: usize) -> bool { // This is now a standalone function, and there is no constraint on // how it can be called! Bounds checks are back! slice1[index] == slice2[index] } fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { // Cut off one slice up to the length of the other, // so that the compiler knows the lengths are the same let fibonacci = &fibonacci[..input.len()]; for i in 0..input.len() { if elements_are_equal(input, fibonacci, i) { return false; } } true } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_clever.rs
src/bin/comparison_clever.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin comparison_clever is_fibonacci #[inline(never)] // so that we can easily view the assembly fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { // Cut off one slice up to the length of the other, // so that the compiler knows the lengths are the same // before we enter the hot loop let fibonacci = &fibonacci[..input.len()]; for i in 0..input.len() { if input[i] != fibonacci[i] { // No bounds checks in the loop now! return false; } } true } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_iterator.rs
src/bin/comparison_iterator.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin comparison_iterator is_fibonacci #[inline(never)] // so that we can easily view the assembly fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { // this is an iterator; it completely avoids bounds checks input.iter().zip(fibonacci.iter()).all(|(i, f)| i == f) } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/fibvec_iterator.rs
src/bin/fibvec_iterator.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin fibvec_iterator fibonacci_vec #[inline(never)] // so that we can easily view the assembly fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; // this is an iterator; it completely avoids bounds checks for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify length"); let length: usize = arg.parse().expect("That's not a number!"); // actually call the function we care about let fibonacci = fibonacci_vec(length); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", fibonacci.last()); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/fibvec_naive_indexing.rs
src/bin/fibvec_naive_indexing.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin fibvec_naive_indexing fibonacci_vec #[inline(never)] // so that we can easily view the assembly fn fibonacci_vec(length: usize) -> Vec<u64> { // Allocate the full length up front to avoid costly reallocations. // Also, `vec![0; length]` just requests zeroed memory from the OS, // so we don't have to spend time filling the Vec with zeroes - // the OS usually has some zeroed memory on hand let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { for i in 2..length { fib[i] = fib[i-1] + fib[i-2]; // indexing in a loop! Oh no! } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify length"); let length: usize = arg.parse().expect("That's not a number!"); // actually call the function we care about let fibonacci = fibonacci_vec(length); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", fibonacci.last()); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/fibvec_clever_indexing_alt.rs
src/bin/fibvec_clever_indexing_alt.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin fibvec_clever_indexing_alt fibonacci_vec #[inline(never)] // so that we can easily view the assembly fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; { // Unlike a `Vec`, a slice is not resizable let fib = fib.as_mut_slice(); if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; // The compiler now knows that `fib` is fixed-size // and we are iterating exactly up to its length for i in 2..fib.len() { // Uses the same structure as the iterator version, // but using indexing instead. No bounds checks. let current = grandparent + parent; fib[i] = current; grandparent = parent; parent = current; } } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify length"); let length: usize = arg.parse().expect("That's not a number!"); // actually call the function we care about let fibonacci = fibonacci_vec(length); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", fibonacci.last()); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/nth_branchless.rs
src/bin/nth_branchless.rs
// It's now hardcoded how many numbers fibonacci_array() calculates const FIBONACCI_NUMS: usize = 100; // Inspect the resulting assembly using: // cargo asm --rust --bin nth_branchless nth_fibonacci #[inline(never)] // so that we can easily view the assembly fn nth_fibonacci(n: usize, fibonacci: &[u64]) -> u64 { // Instead of panicking, return a bogus value. // This this gets optimized into a conditional move // instead of a branch instruction, which is // slower than a branch if the value is always in bounds // because the branch is perfectly predictable, // but faster if you query values both in and out of bounds // because it avoids costly branch misprediction. *fibonacci.get(n).unwrap_or(&0) } fn fibonacci_vec() -> Vec<u64> { let length = FIBONACCI_NUMS; let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute the result let arg = std::env::args().nth(1).expect("Please specify the number to look up"); let index: usize = arg.parse().expect("Lookup index is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(); // actually call the function we care about let result = nth_fibonacci(index, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/fibvec_clever_indexing.rs
src/bin/fibvec_clever_indexing.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin fibvec_clever_indexing fibonacci_vec #[inline(never)] // so that we can easily view the assembly fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; { // Unlike a `Vec`, a slice is not resizable let fib = fib.as_mut_slice(); if length > 1 { fib[1] = 1; } if length > 2 { // The compiler now knows that `fib` is fixed-size // and we are iterating exactly up to its length for i in 2..fib.len() { fib[i] = fib[i-1] + fib[i-2]; // no more bounds checks! } } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify length"); let length: usize = arg.parse().expect("That's not a number!"); // actually call the function we care about let fibonacci = fibonacci_vec(length); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", fibonacci.last()); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_split_inline.rs
src/bin/comparison_split_inline.rs
// #[inline(always)] copies the code of the function into the caller and optimizes them together #[inline(always)] // used to be #[inline(never)] fn elements_are_equal(slice1: &[u64], slice2: &[u64], index: usize) -> bool { // we can no longer view the assembly here because of #[inline(always)] // but we can look at the result of inlining it in is_fibonacci() slice1[index] == slice2[index] } // Inspect the resulting assembly using: // cargo asm --rust --bin comparison_split_inline is_fibonacci #[inline(never)] // so that we can easily view the assembly fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { // Cut off one slice up to the length of the other, // so that the compiler knows the lengths are the same let fibonacci = &fibonacci[..input.len()]; for i in 0..input.len() { // No bounds checks here! if elements_are_equal(input, fibonacci, i) { return false; } } true } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/nth_errorless_heap.rs
src/bin/nth_errorless_heap.rs
// It's now hardcoded how many numbers fibonacci_array() calculates const FIBONACCI_NUMS: usize = 100; // round that number up to a power of two // to make our custom bounds checks really cheap const LOOKUP_TABLE_SIZE: usize = FIBONACCI_NUMS.next_power_of_two(); // Inspect the resulting assembly using: // cargo asm --rust --bin nth_errorless_heap nth_fibonacci #[inline(never)] // so that we can easily view the assembly fn nth_fibonacci(n: usize, fibonacci: &[u64; LOOKUP_TABLE_SIZE]) -> u64 { // we're going to blithely ignore any errors further on // to squeeze out every last bit of performance, // but that's no excuse not to sanity-check in tests debug_assert!(n < FIBONACCI_NUMS); // remainder operator % is expensive in the general case, // but for a constant equal to power of two optimizes into // a bitwise AND, which is very cheap. // However, // out-of-bounds accesses now return garbage instead of panicking! fibonacci[n % LOOKUP_TABLE_SIZE] } fn fibonacci_vec() -> Box<[u64; LOOKUP_TABLE_SIZE]> { let length = FIBONACCI_NUMS; // hardcoded let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } // Pad the Vec with zeroes to the next power of two fib.resize(LOOKUP_TABLE_SIZE, 0); // Convert the Vec to an owned slice, its size is now unchanging let fib_slice: Box<[u64]> = fib.into_boxed_slice(); // Coerce the slice to a fixed-size type, this encodes the size in the type system let fib_fixed_slice: Box<[u64; LOOKUP_TABLE_SIZE]> = fib_slice.try_into().unwrap(); fib_fixed_slice } pub fn main() { // read the length at runtime so that the compiler can't just precompute the result let arg = std::env::args().nth(1).expect("Please specify the number to look up"); let index: usize = arg.parse().expect("Lookup index is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(); // actually call the function we care about let result = nth_fibonacci(index, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/nth_errorless_stack.rs
src/bin/nth_errorless_stack.rs
// It's now hardcoded how many numbers fibonacci_array() calculates const FIBONACCI_NUMS: usize = 100; // round that number up to a power of two // to make our custom bounds checks really cheap const LOOKUP_TABLE_SIZE: usize = FIBONACCI_NUMS.next_power_of_two(); // Inspect the resulting assembly using: // cargo asm --rust --bin nth_errorless_stack nth_fibonacci #[inline(never)] // so that we can easily view the assembly fn nth_fibonacci(n: usize, fibonacci: &[u64; LOOKUP_TABLE_SIZE]) -> u64 { // we're going to blithely ignore any errors further on // to squeeze out every last bit of performance, // but that's no excuse not to sanity-check in tests debug_assert!(n < FIBONACCI_NUMS); // remainder operator % is expensive in the general case, // but for a constant equal to power of two optimizes into // a bitwise AND, which is very cheap. // However: // out-of-bounds accesses now return garbage instead of panicking! fibonacci[n % LOOKUP_TABLE_SIZE] } fn fibonacci_array() -> [u64; LOOKUP_TABLE_SIZE] { let length = FIBONACCI_NUMS; // The array is allocated on the stack. // The syntax happens to be more terse // than when doing the same on the heap, // but this will overflow the stack // given very large lookup table sizes. let mut fib = [0; LOOKUP_TABLE_SIZE]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..FIBONACCI_NUMS] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute the result let arg = std::env::args().nth(1).expect("Please specify the number to look up"); let index: usize = arg.parse().expect("Lookup index is not a number!"); // generate the lookup table let fibonacci = fibonacci_array(); // actually call the function we care about let result = nth_fibonacci(index, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_realistic.rs
src/bin/comparison_realistic.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin comparison_realistic is_fibonacci #[inline(never)] // so that we can easily view the assembly fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { input == &fibonacci[..input.len()] } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
Shnatsel/bounds-check-cookbook
https://github.com/Shnatsel/bounds-check-cookbook/blob/212de6936f11e785e407b57a3d0ef669e88af60a/src/bin/comparison_naive.rs
src/bin/comparison_naive.rs
// Inspect the resulting assembly using: // cargo asm --rust --bin comparison_naive is_fibonacci #[inline(never)] // so that we can easily view the assembly fn is_fibonacci(input: &[u64], fibonacci: &[u64]) -> bool { for i in 0..input.len() { if input[i] != fibonacci[i] { // two bounds checks! return false; } } true } fn fibonacci_vec(length: usize) -> Vec<u64> { let mut fib = vec![0; length]; if length > 1 { fib[1] = 1; } if length > 2 { let mut grandparent = 0; let mut parent = 1; for val in &mut fib[2..] { let current = grandparent + parent; *val = current; grandparent = parent; parent = current; } } fib } pub fn main() { // read the length at runtime so that the compiler can't just precompute Fibonacci let arg = std::env::args().nth(1).expect("Please specify precomputed length"); let length: usize = arg.parse().expect("Precomputed length is not a number!"); let arg = std::env::args().nth(2).expect("Please specify test length"); let test_len: usize = arg.parse().expect("Test length is not a number!"); // generate the lookup table let fibonacci = fibonacci_vec(length); // generate the array we're going to test - whether it's Fibonacci or not let input = fibonacci_vec(test_len); // actually call the function we care about let result = is_fibonacci(&input, &fibonacci); // and print the result so that the compiler doesn't remove it as dead code println!("{:?}", result); }
rust
MIT
212de6936f11e785e407b57a3d0ef669e88af60a
2026-01-04T20:23:18.406397Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/der_helper.rs
x509/src/der_helper.rs
/*++ Licensed under the Apache-2.0 license. File Name: der_helper.rs Abstract: Helpers for encoding DER unsigned integers --*/ /// DER Integer Tag const DER_INTEGER_TAG: u8 = 0x02; #[inline(never)] fn trim_leading_zeros(val: &[u8]) -> &[u8] { // Count the leading zeros for i in 0..val.len() { if val[i] != 0 { return &val[i..]; } } // If everything is 0, then we need len 1, and 0 as value &val[0..1] // single 0 } #[inline(never)] fn encode_length(val: &[u8]) -> usize { for i in 0..val.len() { if val[i] != 0 { return val.len() - i + (val[i] >> 7) as usize; } } 1 } /// Compute len of DER encoding of an unsinged integer #[inline(never)] pub fn der_uint_len(val: &[u8]) -> usize { let encode_length = encode_length(val); let len_field_size = match encode_length { 0..=127 => 1, 128.. => trim_leading_zeros(&encode_length.to_be_bytes()).len(), }; // Tag + len + int 1 + len_field_size + encode_length } /// Encode a DER length #[inline(never)] pub fn der_encode_len(len: usize, buf: &mut [u8]) -> Option<usize> { match len { 1..=127 => { *buf.get_mut(0)? = len as u8; Some(1) } 128.. => { let encode_len_be_bytes = len.to_be_bytes(); let len_in_be_bytes = trim_leading_zeros(&encode_len_be_bytes); let len = len_in_be_bytes.len(); *buf.get_mut(0)? = 0x80 | (len as u8); buf.get_mut(1..)? .get_mut(..len)? .copy_from_slice(len_in_be_bytes); Some(len + 1) } _ => None?, } } /// DER Encode unsigned integer #[inline(never)] pub fn der_encode_uint(val: &[u8], buf: &mut [u8]) -> Option<usize> { let mut pos = 0; *buf.get_mut(pos)? = DER_INTEGER_TAG; pos += 1; let sub_val = trim_leading_zeros(val); let encode_len = encode_length(val); pos += der_encode_len(encode_len, buf.get_mut(pos..)?)?; if *sub_val.first()? > 127 { *buf.get_mut(pos)? = 0; pos += 1; } buf.get_mut(pos..)? .get_mut(..sub_val.len())? .copy_from_slice(sub_val); pos += sub_val.len(); Some(pos) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/rt_alias_cert_ecc_384.rs
x509/src/rt_alias_cert_ecc_384.rs
/*++ Licensed under the Apache-2.0 license. File Name: rt_alias_cert.rs Abstract: ECC384 RT Alias Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/rt_alias_cert_tbs_ecc_384.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/rt_alias_cert_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::ecdsa::EcdsaSig; use openssl::sha::Sha384; use openssl::x509::X509; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert_signing() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let params = RtAliasCertTbsEcc384Params { serial_number: &[0xABu8; RtAliasCertTbsEcc384Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; RtAliasCertTbsEcc384Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; RtAliasCertTbsEcc384Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; RtAliasCertTbsEcc384Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), ueid: &[0xAB; RtAliasCertTbsEcc384Params::UEID_LEN], subject_key_id: &TryInto::<[u8; RtAliasCertTbsEcc384Params::SUBJECT_KEY_ID_LEN]>::try_into( subject_key.sha1(), ) .unwrap(), authority_key_id: &TryInto::<[u8; RtAliasCertTbsEcc384Params::SUBJECT_KEY_ID_LEN]>::try_into( issuer_key.sha1(), ) .unwrap(), tcb_info_fw_svn: &[0xE3], tcb_info_rt_tci: &[0xEFu8; RtAliasCertTbsEcc384Params::TCB_INFO_RT_TCI_LEN], not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = RtAliasCertTbsEcc384::new(&params); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(cert.tbs(), RtAliasCertTbsEcc384::TBS_TEMPLATE); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::PUBLIC_KEY_OFFSET ..RtAliasCertTbsEcc384::PUBLIC_KEY_OFFSET + RtAliasCertTbsEcc384::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::SUBJECT_SN_OFFSET ..RtAliasCertTbsEcc384::SUBJECT_SN_OFFSET + RtAliasCertTbsEcc384::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::ISSUER_SN_OFFSET ..RtAliasCertTbsEcc384::ISSUER_SN_OFFSET + RtAliasCertTbsEcc384::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::UEID_OFFSET ..RtAliasCertTbsEcc384::UEID_OFFSET + RtAliasCertTbsEcc384::UEID_LEN], params.ueid, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::SUBJECT_KEY_ID_OFFSET ..RtAliasCertTbsEcc384::SUBJECT_KEY_ID_OFFSET + RtAliasCertTbsEcc384::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET ..RtAliasCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET + RtAliasCertTbsEcc384::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::TCB_INFO_FW_SVN_OFFSET ..RtAliasCertTbsEcc384::TCB_INFO_FW_SVN_OFFSET + RtAliasCertTbsEcc384::TCB_INFO_FW_SVN_LEN], params.tcb_info_fw_svn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsEcc384::TCB_INFO_RT_TCI_OFFSET ..RtAliasCertTbsEcc384::TCB_INFO_RT_TCI_OFFSET + RtAliasCertTbsEcc384::TCB_INFO_RT_TCI_LEN], params.tcb_info_rt_tci, ); let ecdsa_sig = crate::Ecdsa384Signature { r: TryInto::<[u8; 48]>::try_into(sig.r().to_vec_padded(48).unwrap()).unwrap(), s: TryInto::<[u8; 48]>::try_into(sig.s().to_vec_padded(48).unwrap()).unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] #[cfg(feature = "generate_templates")] fn test_rt_alias_template() { let manual_template = std::fs::read(std::path::Path::new("./build/rt_alias_cert_tbs_ecc_384.rs")).unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/rt_alias_cert_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated RT Alias Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/rt_alias_cert_mldsa_87.rs
x509/src/rt_alias_cert_mldsa_87.rs
/*++ Licensed under the Apache-2.0 license. File Name: rt_alias_cert.rs Abstract: ML-DSA87 RT Alias Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/rt_alias_cert_tbs_ml_dsa_87.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/rt_alias_cert_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert_signing() { let subject_key = MlDsa87AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let params = RtAliasCertTbsMlDsa87Params { serial_number: &[0xABu8; RtAliasCertTbsMlDsa87Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; RtAliasCertTbsMlDsa87Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; RtAliasCertTbsMlDsa87Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; RtAliasCertTbsMlDsa87Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), ueid: &[0xAB; RtAliasCertTbsMlDsa87Params::UEID_LEN], subject_key_id: &TryInto::<[u8; RtAliasCertTbsMlDsa87Params::SUBJECT_KEY_ID_LEN]>::try_into( subject_key.sha1(), ) .unwrap(), authority_key_id: &TryInto::<[u8; RtAliasCertTbsMlDsa87Params::SUBJECT_KEY_ID_LEN]>::try_into( issuer_key.sha1(), ) .unwrap(), tcb_info_fw_svn: &[0xE3], tcb_info_rt_tci: &[0xEFu8; RtAliasCertTbsMlDsa87Params::TCB_INFO_RT_TCI_LEN], not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = RtAliasCertTbsMlDsa87::new(&params); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(cert.tbs(), RtAliasCertTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::PUBLIC_KEY_OFFSET ..RtAliasCertTbsMlDsa87::PUBLIC_KEY_OFFSET + RtAliasCertTbsMlDsa87::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::SUBJECT_SN_OFFSET ..RtAliasCertTbsMlDsa87::SUBJECT_SN_OFFSET + RtAliasCertTbsMlDsa87::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::ISSUER_SN_OFFSET ..RtAliasCertTbsMlDsa87::ISSUER_SN_OFFSET + RtAliasCertTbsMlDsa87::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::UEID_OFFSET ..RtAliasCertTbsMlDsa87::UEID_OFFSET + RtAliasCertTbsMlDsa87::UEID_LEN], params.ueid, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET ..RtAliasCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET + RtAliasCertTbsMlDsa87::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET ..RtAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET + RtAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_OFFSET ..RtAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_OFFSET + RtAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_LEN], params.tcb_info_fw_svn, ); assert_eq!( &cert.tbs()[RtAliasCertTbsMlDsa87::TCB_INFO_RT_TCI_OFFSET ..RtAliasCertTbsMlDsa87::TCB_INFO_RT_TCI_OFFSET + RtAliasCertTbsMlDsa87::TCB_INFO_RT_TCI_LEN], params.tcb_info_rt_tci, ); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] #[cfg(feature = "generate_templates")] fn test_rt_alias_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/rt_alias_cert_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/rt_alias_cert_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated RT Alias Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/idevid_csr_mldsa_87.rs
x509/src/idevid_csr_mldsa_87.rs
/*++ Licensed under the Apache-2.0 license. File Name: idevid_csr.rs Abstract: Initial Device ID Certificate Signing Request related code. --*/ #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/init_dev_id_csr_tbs_ml_dsa_87.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/init_dev_id_csr_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509Req; use x509_parser::cri_attributes::ParsedCriAttribute; use x509_parser::extensions::ParsedExtension; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::prelude::{FromDer, X509CertificationRequest}; use super::*; use crate::test_util::tests::*; use crate::{MlDsa87CsrBuilder, MlDsa87Signature}; const TEST_UEID: &[u8] = &[0xAB; InitDevIdCsrTbsMlDsa87::UEID_LEN]; fn make_test_csr(subject_key: &MlDsa87AsymKey) -> InitDevIdCsrTbsMlDsa87 { let params = InitDevIdCsrTbsMlDsa87Params { public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key.hex_str().into_bytes().try_into().unwrap(), ueid: &TEST_UEID.try_into().unwrap(), }; InitDevIdCsrTbsMlDsa87::new(&params) } #[test] fn test_csr_signing() { let key = MlDsa87AsymKey::default(); let mldsa_key = key.priv_key(); let csr = make_test_csr(&key); let sig = csr .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(csr.tbs(), InitDevIdCsrTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &csr.tbs()[InitDevIdCsrTbsMlDsa87::PUBLIC_KEY_OFFSET ..InitDevIdCsrTbsMlDsa87::PUBLIC_KEY_OFFSET + InitDevIdCsrTbsMlDsa87::PUBLIC_KEY_LEN], key.pub_key(), ); assert_eq!( &csr.tbs()[InitDevIdCsrTbsMlDsa87::SUBJECT_SN_OFFSET ..InitDevIdCsrTbsMlDsa87::SUBJECT_SN_OFFSET + InitDevIdCsrTbsMlDsa87::SUBJECT_SN_LEN], key.hex_str().into_bytes(), ); assert_eq!( &csr.tbs()[InitDevIdCsrTbsMlDsa87::UEID_OFFSET ..InitDevIdCsrTbsMlDsa87::UEID_OFFSET + InitDevIdCsrTbsMlDsa87::UEID_LEN], TEST_UEID, ); let mldsa_sig = MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CsrBuilder::new(csr.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let req: X509Req = X509Req::from_der(&buf).unwrap(); assert!(req.verify(&req.public_key().unwrap()).unwrap()); assert!(req.verify(key.priv_key()).unwrap()); } #[test] fn test_extensions() { let key = MlDsa87AsymKey::default(); let mldsa_key = key.priv_key(); let csr = make_test_csr(&key); let sig = csr .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); let mldsa_sig = MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = MlDsa87CsrBuilder::new(csr.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let (_, parsed_csr) = X509CertificationRequest::from_der(&buf).unwrap(); let requested_extensions = parsed_csr .certification_request_info .iter_attributes() .find_map(|attr| { if let ParsedCriAttribute::ExtensionRequest(requested) = attr.parsed_attribute() { Some(&requested.extensions) } else { None } }) .unwrap(); // BasicConstraints let bc_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::BasicConstraints(_))) .unwrap(); let ParsedExtension::BasicConstraints(bc) = bc_ext.parsed_extension() else { panic!("Extension is not BasicConstraints"); }; assert!(bc_ext.critical); assert!(bc.ca); // KeyUsage let ku_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::KeyUsage(_))) .unwrap(); assert!(ku_ext.critical); // UEID let ueid_ext = requested_extensions .iter() .find(|ext| { if let ParsedExtension::UnsupportedExtension { oid } = ext.parsed_extension() { oid == &oid!(2.23.133 .5 .4 .4) } else { false } }) .unwrap(); assert!(!ueid_ext.critical); } #[test] #[cfg(feature = "generate_templates")] fn test_idevid_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/init_dev_id_csr_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/init_dev_id_csr_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!("Auto-generated IDevID CSR template is not equal to the manual template.") } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/ldevid_cert_mldsa_87.rs
x509/src/ldevid_cert_mldsa_87.rs
/*++ Licensed under the Apache-2.0 license. File Name: ldevid_cert.rs Abstract: Local Device ID Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/local_dev_id_cert_tbs_ml_dsa_87.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/local_dev_id_cert_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; const TEST_UEID: &[u8] = &[0xAB; LocalDevIdCertTbsMlDsa87Params::UEID_LEN]; fn make_test_cert( subject_key: &MlDsa87AsymKey, issuer_key: &MlDsa87AsymKey, ) -> LocalDevIdCertTbsMlDsa87 { let params = LocalDevIdCertTbsMlDsa87Params { serial_number: &[0xABu8; LocalDevIdCertTbsMlDsa87Params::SERIAL_NUMBER_LEN], public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), issuer_sn: &issuer_key.hex_str().into_bytes().try_into().unwrap(), ueid: &TEST_UEID.try_into().unwrap(), subject_key_id: &subject_key.sha1(), authority_key_id: &issuer_key.sha1(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; LocalDevIdCertTbsMlDsa87::new(&params) } #[test] fn test_cert_signing() { let subject_key = MlDsa87AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(cert.tbs(), LocalDevIdCertTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::PUBLIC_KEY_OFFSET ..LocalDevIdCertTbsMlDsa87::PUBLIC_KEY_OFFSET + LocalDevIdCertTbsMlDsa87::PUBLIC_KEY_LEN], subject_key.pub_key(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::SUBJECT_SN_OFFSET ..LocalDevIdCertTbsMlDsa87::SUBJECT_SN_OFFSET + LocalDevIdCertTbsMlDsa87::SUBJECT_SN_LEN], subject_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::ISSUER_SN_OFFSET ..LocalDevIdCertTbsMlDsa87::ISSUER_SN_OFFSET + LocalDevIdCertTbsMlDsa87::ISSUER_SN_LEN], issuer_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::UEID_OFFSET ..LocalDevIdCertTbsMlDsa87::UEID_OFFSET + LocalDevIdCertTbsMlDsa87::UEID_LEN], TEST_UEID, ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET ..LocalDevIdCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET + LocalDevIdCertTbsMlDsa87::SUBJECT_KEY_ID_LEN], subject_key.sha1(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET ..LocalDevIdCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET + LocalDevIdCertTbsMlDsa87::AUTHORITY_KEY_ID_LEN], issuer_key.sha1(), ); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] fn test_extensions() { let subject_key = MlDsa87AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); // Basic checks on standard extensions let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(basic_constraints.value.ca); let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); // Check that TCG extensions are marked critical let ext_map = parsed_cert.extensions_map().unwrap(); const UEID_OID: Oid = oid!(2.23.133 .5 .4 .4); assert!(!ext_map[&UEID_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ldevid_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/local_dev_id_cert_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/local_dev_id_cert_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated LDevID Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/lib.rs
x509/src/lib.rs
/*++ Licensed under the Apache-2.0 license. File Name: lib.rs Abstract: Main entry point for Caliptra X509 related functionality --*/ #![cfg_attr(not(feature = "std"), no_std)] mod cert_bldr; mod der_helper; mod fmc_alias_cert_ecc_384; mod fmc_alias_cert_mldsa_87; mod fmc_alias_csr_ecc_384; mod idevid_csr_ecc_384; mod idevid_csr_mldsa_87; mod ldevid_cert_ecc_384; mod ldevid_cert_mldsa_87; mod ocp_lock_hpke_certs; mod rt_alias_cert_ecc_384; mod rt_alias_cert_mldsa_87; mod test_util; pub use cert_bldr::{ Ecdsa384CertBuilder, Ecdsa384CsrBuilder, Ecdsa384Signature, MlDsa87CertBuilder, MlDsa87CsrBuilder, MlDsa87Signature, }; pub use der_helper::{der_encode_len, der_encode_uint, der_uint_len}; pub use fmc_alias_cert_ecc_384::{FmcAliasCertTbsEcc384, FmcAliasCertTbsEcc384Params}; pub use fmc_alias_cert_mldsa_87::{FmcAliasCertTbsMlDsa87, FmcAliasCertTbsMlDsa87Params}; pub use fmc_alias_csr_ecc_384::{ FmcAliasCsrTbsEcc384, FmcAliasCsrTbsEcc384Params, FmcAliasTbsMlDsa87, FmcAliasTbsMlDsa87Params, }; pub use idevid_csr_ecc_384::{InitDevIdCsrTbsEcc384, InitDevIdCsrTbsEcc384Params}; pub use idevid_csr_mldsa_87::{InitDevIdCsrTbsMlDsa87, InitDevIdCsrTbsMlDsa87Params}; pub use ldevid_cert_ecc_384::{LocalDevIdCertTbsEcc384, LocalDevIdCertTbsEcc384Params}; pub use ldevid_cert_mldsa_87::{LocalDevIdCertTbsMlDsa87, LocalDevIdCertTbsMlDsa87Params}; pub use rt_alias_cert_ecc_384::{RtAliasCertTbsEcc384, RtAliasCertTbsEcc384Params}; pub use rt_alias_cert_mldsa_87::{RtAliasCertTbsMlDsa87, RtAliasCertTbsMlDsa87Params}; pub use ocp_lock_hpke_certs::{ ecdh_384_ecc_348::{OcpLockEcdh384CertTbsEcc384, OcpLockEcdh384CertTbsEcc384Params}, ecdh_384_mldsa_87::{OcpLockEcdh384CertTbsMlDsa87, OcpLockEcdh384CertTbsMlDsa87Params}, ml_kem_ecc_348::{OcpLockMlKemCertTbsEcc384, OcpLockMlKemCertTbsEcc384Params}, ml_kem_mldsa_87::{OcpLockMlKemCertTbsMlDsa87, OcpLockMlKemCertTbsMlDsa87Params}, }; use zeroize::Zeroize; pub const NOT_BEFORE: &str = "20230101000000Z"; pub const NOT_AFTER: &str = "99991231235959Z"; #[derive(Debug, Zeroize)] pub struct NotBefore { pub value: [u8; 15], } impl Default for NotBefore { fn default() -> Self { let mut nb: NotBefore = NotBefore { value: [0u8; 15] }; nb.value.copy_from_slice(NOT_BEFORE.as_bytes()); nb } } #[derive(Debug, Zeroize)] pub struct NotAfter { pub value: [u8; 15], } impl Default for NotAfter { fn default() -> Self { let mut nf: NotAfter = NotAfter { value: [0u8; 15] }; nf.value.copy_from_slice(NOT_AFTER.as_bytes()); nf } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/idevid_csr_ecc_384.rs
x509/src/idevid_csr_ecc_384.rs
/*++ Licensed under the Apache-2.0 license. File Name: idevid_csr.rs Abstract: ECC384 Initial Device ID Certificate Signing Request related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/init_dev_id_csr_tbs_ecc_384.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/init_dev_id_csr_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::sha::Sha384; use openssl::{ecdsa::EcdsaSig, x509::X509Req}; use x509_parser::cri_attributes::ParsedCriAttribute; use x509_parser::extensions::ParsedExtension; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::prelude::{FromDer, X509CertificationRequest}; use super::*; use crate::test_util::tests::*; use crate::{Ecdsa384CsrBuilder, Ecdsa384Signature}; const TEST_UEID: &[u8] = &[0xAB; InitDevIdCsrTbsEcc384::UEID_LEN]; fn make_test_csr(subject_key: &Ecc384AsymKey) -> InitDevIdCsrTbsEcc384 { let params = InitDevIdCsrTbsEcc384Params { public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key.hex_str().into_bytes().try_into().unwrap(), ueid: &TEST_UEID.try_into().unwrap(), }; InitDevIdCsrTbsEcc384::new(&params) } #[test] fn test_csr_signing() { let key = Ecc384AsymKey::default(); let ec_key = key.priv_key().ec_key().unwrap(); let csr = make_test_csr(&key); let sig: EcdsaSig = csr .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(csr.tbs(), InitDevIdCsrTbsEcc384::TBS_TEMPLATE); assert_eq!( &csr.tbs()[InitDevIdCsrTbsEcc384::PUBLIC_KEY_OFFSET ..InitDevIdCsrTbsEcc384::PUBLIC_KEY_OFFSET + InitDevIdCsrTbsEcc384::PUBLIC_KEY_LEN], key.pub_key(), ); assert_eq!( &csr.tbs()[InitDevIdCsrTbsEcc384::SUBJECT_SN_OFFSET ..InitDevIdCsrTbsEcc384::SUBJECT_SN_OFFSET + InitDevIdCsrTbsEcc384::SUBJECT_SN_LEN], key.hex_str().into_bytes(), ); assert_eq!( &csr.tbs()[InitDevIdCsrTbsEcc384::UEID_OFFSET ..InitDevIdCsrTbsEcc384::UEID_OFFSET + InitDevIdCsrTbsEcc384::UEID_LEN], TEST_UEID, ); let ecdsa_sig = crate::Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = crate::Ecdsa384CsrBuilder::new(csr.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let req: X509Req = X509Req::from_der(&buf).unwrap(); assert!(req.verify(&req.public_key().unwrap()).unwrap()); assert!(req.verify(key.priv_key()).unwrap()); } #[test] fn test_extensions() { let key = Ecc384AsymKey::default(); let ec_key = key.priv_key().ec_key().unwrap(); let csr = make_test_csr(&key); let sig: EcdsaSig = csr .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); let ecdsa_sig = Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = Ecdsa384CsrBuilder::new(csr.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let (_, parsed_csr) = X509CertificationRequest::from_der(&buf).unwrap(); let requested_extensions = parsed_csr .certification_request_info .iter_attributes() .find_map(|attr| { if let ParsedCriAttribute::ExtensionRequest(requested) = attr.parsed_attribute() { Some(&requested.extensions) } else { None } }) .unwrap(); // BasicConstraints let bc_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::BasicConstraints(_))) .unwrap(); let ParsedExtension::BasicConstraints(bc) = bc_ext.parsed_extension() else { panic!("Extension is not BasicConstraints"); }; assert!(bc_ext.critical); assert!(bc.ca); // KeyUsage let ku_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::KeyUsage(_))) .unwrap(); assert!(ku_ext.critical); // UEID let ueid_ext = requested_extensions .iter() .find(|ext| { if let ParsedExtension::UnsupportedExtension { oid } = ext.parsed_extension() { oid == &oid!(2.23.133 .5 .4 .4) } else { false } }) .unwrap(); assert!(!ueid_ext.critical); } #[test] #[cfg(feature = "generate_templates")] fn test_idevid_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/init_dev_id_csr_tbs_ecc_384.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/init_dev_id_csr_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!("Auto-generated IDevID CSR template is not equal to the manual template.") } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/fmc_alias_cert_ecc_384.rs
x509/src/fmc_alias_cert_ecc_384.rs
/*++ Licensed under the Apache-2.0 license. File Name: fmc_alias_cert_ecc_384.rs Abstract: ECC384 FMC Alias Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/fmc_alias_cert_tbs_ecc_384.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/fmc_alias_cert_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use super::*; use crate::test_util::tests::*; use crate::{Ecdsa384CertBuilder, Ecdsa384Signature, NotAfter, NotBefore}; use openssl::ecdsa::EcdsaSig; use openssl::sha::Sha384; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; const TEST_DEVICE_INFO_HASH: &[u8] = &[0xCDu8; FmcAliasCertTbsEcc384Params::TCB_INFO_DEVICE_INFO_HASH_LEN]; const TEST_FMC_HASH: &[u8] = &[0xEFu8; FmcAliasCertTbsEcc384Params::TCB_INFO_FMC_TCI_LEN]; const TEST_UEID: &[u8] = &[0xABu8; FmcAliasCertTbsEcc384Params::UEID_LEN]; const TEST_TCB_INFO_FLAGS: &[u8] = &[0xB0, 0xB1, 0xB2, 0xB3]; const TEST_TCB_INFO_FW_SVN: &[u8] = &[0xB7]; const TEST_TCB_INFO_FW_SVN_FUSES: &[u8] = &[0xB8]; fn make_test_cert( subject_key: &Ecc384AsymKey, issuer_key: &Ecc384AsymKey, ) -> FmcAliasCertTbsEcc384 { let params = FmcAliasCertTbsEcc384Params { serial_number: &[0xABu8; FmcAliasCertTbsEcc384Params::SERIAL_NUMBER_LEN], public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), issuer_sn: &issuer_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), ueid: TEST_UEID.try_into().unwrap(), subject_key_id: &subject_key.sha1(), authority_key_id: &issuer_key.sha1(), tcb_info_flags: TEST_TCB_INFO_FLAGS.try_into().unwrap(), tcb_info_device_info_hash: &TEST_DEVICE_INFO_HASH.try_into().unwrap(), tcb_info_fmc_tci: &TEST_FMC_HASH.try_into().unwrap(), tcb_info_fw_svn: &TEST_TCB_INFO_FW_SVN.try_into().unwrap(), tcb_info_fw_svn_fuses: &TEST_TCB_INFO_FW_SVN_FUSES.try_into().unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; FmcAliasCertTbsEcc384::new(&params) } #[test] fn test_cert_signing() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let cert = make_test_cert(&subject_key, &issuer_key); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(cert.tbs(), FmcAliasCertTbsEcc384::TBS_TEMPLATE); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::PUBLIC_KEY_OFFSET ..FmcAliasCertTbsEcc384::PUBLIC_KEY_OFFSET + FmcAliasCertTbsEcc384::PUBLIC_KEY_LEN], subject_key.pub_key(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::SUBJECT_SN_OFFSET ..FmcAliasCertTbsEcc384::SUBJECT_SN_OFFSET + FmcAliasCertTbsEcc384::SUBJECT_SN_LEN], subject_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::ISSUER_SN_OFFSET ..FmcAliasCertTbsEcc384::ISSUER_SN_OFFSET + FmcAliasCertTbsEcc384::ISSUER_SN_LEN], issuer_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::UEID_OFFSET ..FmcAliasCertTbsEcc384::UEID_OFFSET + FmcAliasCertTbsEcc384::UEID_LEN], TEST_UEID, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::SUBJECT_KEY_ID_OFFSET ..FmcAliasCertTbsEcc384::SUBJECT_KEY_ID_OFFSET + FmcAliasCertTbsEcc384::SUBJECT_KEY_ID_LEN], subject_key.sha1(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET ..FmcAliasCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET + FmcAliasCertTbsEcc384::AUTHORITY_KEY_ID_LEN], issuer_key.sha1(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::TCB_INFO_FLAGS_OFFSET ..FmcAliasCertTbsEcc384::TCB_INFO_FLAGS_OFFSET + FmcAliasCertTbsEcc384::TCB_INFO_FLAGS_LEN], TEST_TCB_INFO_FLAGS, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_OFFSET ..FmcAliasCertTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_OFFSET + FmcAliasCertTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_LEN], TEST_DEVICE_INFO_HASH, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::TCB_INFO_FMC_TCI_OFFSET ..FmcAliasCertTbsEcc384::TCB_INFO_FMC_TCI_OFFSET + FmcAliasCertTbsEcc384::TCB_INFO_FMC_TCI_LEN], TEST_FMC_HASH, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_OFFSET ..FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_OFFSET + FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_LEN], TEST_TCB_INFO_FW_SVN, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_FUSES_OFFSET ..FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_FUSES_OFFSET + FmcAliasCertTbsEcc384::TCB_INFO_FW_SVN_FUSES_LEN], TEST_TCB_INFO_FW_SVN_FUSES, ); let ecdsa_sig = crate::Ecdsa384Signature { r: TryInto::<[u8; 48]>::try_into(sig.r().to_vec_padded(48).unwrap()).unwrap(), s: TryInto::<[u8; 48]>::try_into(sig.s().to_vec_padded(48).unwrap()).unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] fn test_extensions() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let cert = make_test_cert(&subject_key, &issuer_key); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); let ecdsa_sig = Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); // Basic checks on standard extensions let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(basic_constraints.value.ca); let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); // Check that TCG extensions are present let ext_map = parsed_cert.extensions_map().unwrap(); const UEID_OID: Oid = oid!(2.23.133 .5 .4 .4); assert!(!ext_map[&UEID_OID].critical); const MULTI_TCB_INFO_OID: Oid = oid!(2.23.133 .5 .4 .5); assert!(!ext_map[&MULTI_TCB_INFO_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_fmc_alias_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/fmc_alias_cert_tbs_ecc_384.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/fmc_alias_cert_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated FMC Alias Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/test_util.rs
x509/src/test_util.rs
/*++ Licensed under the Apache-2.0 license. File Name: test_util.rs Abstract: Test Utilities --*/ #[cfg(all(test, target_family = "unix"))] pub mod tests { use openssl::{ bn::BigNumContext, ec::{EcGroup, EcKey, PointConversionForm}, nid::Nid, pkey::{PKey, Private, Public}, pkey_ml_dsa::{PKeyMlDsaBuilder, PKeyMlDsaParams, Variant as MlDsaVariant}, pkey_ml_kem::{PKeyMlKemBuilder, PKeyMlKemParams, Variant as MlKemVariant}, sha::{Sha1, Sha256}, }; use rand::Rng; pub struct Ecc384AsymKey { priv_key: PKey<Private>, pub_key: Vec<u8>, } impl Ecc384AsymKey { pub fn priv_key(&self) -> &PKey<Private> { &self.priv_key } pub fn pub_key(&self) -> &[u8] { &self.pub_key } pub fn sha256(&self) -> [u8; 32] { let mut sha = Sha256::new(); sha.update(self.pub_key()); sha.finish() } pub fn sha1(&self) -> [u8; 20] { let mut sha = Sha1::new(); sha.update(self.pub_key()); sha.finish() } pub fn hex_str(&self) -> String { hex::encode(self.sha256()).to_uppercase() } } impl Default for Ecc384AsymKey { fn default() -> Self { let ecc_group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let priv_key = EcKey::generate(&ecc_group).unwrap(); let mut bn_ctx = BigNumContext::new().unwrap(); let pub_key = priv_key .public_key() .to_bytes(&ecc_group, PointConversionForm::UNCOMPRESSED, &mut bn_ctx) .unwrap(); Self { priv_key: PKey::from_ec_key(priv_key).unwrap(), pub_key, } } } pub struct MlDsa87AsymKey { priv_key: PKey<Private>, pub_key: Vec<u8>, } impl MlDsa87AsymKey { pub fn priv_key(&self) -> &PKey<Private> { &self.priv_key } pub fn pub_key(&self) -> &[u8] { &self.pub_key } pub fn sha256(&self) -> [u8; 32] { let mut sha = Sha256::new(); sha.update(self.pub_key()); sha.finish() } pub fn sha1(&self) -> [u8; 20] { let mut sha = Sha1::new(); sha.update(self.pub_key()); sha.finish() } pub fn hex_str(&self) -> String { hex::encode(self.sha256()).to_uppercase() } } impl Default for MlDsa87AsymKey { fn default() -> Self { let mut random_bytes: [u8; 32] = [0; 32]; let mut rng = rand::thread_rng(); rng.fill(&mut random_bytes); let pk_builder = PKeyMlDsaBuilder::<Private>::from_seed(MlDsaVariant::MlDsa87, &random_bytes) .unwrap(); let private_key = pk_builder.build().unwrap(); let public_params = PKeyMlDsaParams::<Public>::from_pkey(&private_key).unwrap(); let public_key = public_params.public_key().unwrap(); Self { priv_key: private_key, pub_key: public_key.to_vec(), } } } pub struct MlKem1024AsymKey { // Key is never used to sign a certificate. #[allow(dead_code)] priv_key: PKey<Private>, pub_key: Vec<u8>, } impl MlKem1024AsymKey { // Key is never used to sign a certificate. #[allow(dead_code)] pub fn priv_key(&self) -> &PKey<Private> { &self.priv_key } pub fn pub_key(&self) -> &[u8] { &self.pub_key } pub fn sha256(&self) -> [u8; 32] { let mut sha = Sha256::new(); sha.update(self.pub_key()); sha.finish() } pub fn sha1(&self) -> [u8; 20] { let mut sha = Sha1::new(); sha.update(self.pub_key()); sha.finish() } pub fn hex_str(&self) -> String { hex::encode(self.sha256()).to_uppercase() } } impl Default for MlKem1024AsymKey { fn default() -> Self { let mut random_bytes: [u8; 64] = [0; 64]; let mut rng = rand::thread_rng(); rng.fill(&mut random_bytes); let pk_builder = PKeyMlKemBuilder::<Private>::from_seed(MlKemVariant::MlKem1024, &random_bytes) .unwrap(); let private_key = pk_builder.build().unwrap(); let public_params = PKeyMlKemParams::<Public>::from_pkey(&private_key).unwrap(); let public_key = public_params.public_key().unwrap(); Self { priv_key: private_key, pub_key: public_key.to_vec(), } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/ldevid_cert_ecc_384.rs
x509/src/ldevid_cert_ecc_384.rs
/*++ Licensed under the Apache-2.0 license. File Name: ldevid_cert.rs Abstract: ECC384 Local Device ID Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/local_dev_id_cert_tbs_ecc_384.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/local_dev_id_cert_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::ecdsa::EcdsaSig; use openssl::sha::Sha384; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; const TEST_UEID: &[u8] = &[0xAB; LocalDevIdCertTbsEcc384Params::UEID_LEN]; fn make_test_cert( subject_key: &Ecc384AsymKey, issuer_key: &Ecc384AsymKey, ) -> LocalDevIdCertTbsEcc384 { let params = LocalDevIdCertTbsEcc384Params { serial_number: &[0xABu8; LocalDevIdCertTbsEcc384Params::SERIAL_NUMBER_LEN], public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), issuer_sn: &issuer_key.hex_str().into_bytes().try_into().unwrap(), ueid: &TEST_UEID.try_into().unwrap(), subject_key_id: &subject_key.sha1(), authority_key_id: &issuer_key.sha1(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; LocalDevIdCertTbsEcc384::new(&params) } #[test] fn test_cert_signing() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(cert.tbs(), LocalDevIdCertTbsEcc384::TBS_TEMPLATE); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::PUBLIC_KEY_OFFSET ..LocalDevIdCertTbsEcc384::PUBLIC_KEY_OFFSET + LocalDevIdCertTbsEcc384::PUBLIC_KEY_LEN], subject_key.pub_key(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::SUBJECT_SN_OFFSET ..LocalDevIdCertTbsEcc384::SUBJECT_SN_OFFSET + LocalDevIdCertTbsEcc384::SUBJECT_SN_LEN], subject_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::ISSUER_SN_OFFSET ..LocalDevIdCertTbsEcc384::ISSUER_SN_OFFSET + LocalDevIdCertTbsEcc384::ISSUER_SN_LEN], issuer_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::UEID_OFFSET ..LocalDevIdCertTbsEcc384::UEID_OFFSET + LocalDevIdCertTbsEcc384::UEID_LEN], TEST_UEID, ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::SUBJECT_KEY_ID_OFFSET ..LocalDevIdCertTbsEcc384::SUBJECT_KEY_ID_OFFSET + LocalDevIdCertTbsEcc384::SUBJECT_KEY_ID_LEN], subject_key.sha1(), ); assert_eq!( &cert.tbs()[LocalDevIdCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET ..LocalDevIdCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET + LocalDevIdCertTbsEcc384::AUTHORITY_KEY_ID_LEN], issuer_key.sha1(), ); let ecdsa_sig = crate::Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] fn test_extensions() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); let ecdsa_sig = crate::Ecdsa384Signature { r: TryInto::<[u8; 48]>::try_into(sig.r().to_vec_padded(48).unwrap()).unwrap(), s: TryInto::<[u8; 48]>::try_into(sig.s().to_vec_padded(48).unwrap()).unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); // Basic checks on standard extensions let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(basic_constraints.value.ca); let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); // Check that TCG extensions are marked critical let ext_map = parsed_cert.extensions_map().unwrap(); const UEID_OID: Oid = oid!(2.23.133 .5 .4 .4); assert!(!ext_map[&UEID_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ldevid_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/local_dev_id_cert_tbs_ecc_384.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/local_dev_id_cert_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated LDevID Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/fmc_alias_csr_ecc_384.rs
x509/src/fmc_alias_csr_ecc_384.rs
/*++ Licensed under the Apache-2.0 license. File Name: fmc_alis_csr.rs Abstract: FMC Alias CSR Certificate Signing Request related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/fmc_alias_csr_tbs_ecc_384.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/fmc_alias_csr_tbs_ecc_384.rs"} #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/fmc_alias_tbs_ml_dsa_87.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/fmc_alias_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::sha::Sha384; use openssl::{ecdsa::EcdsaSig, x509::X509Req}; use x509_parser::cri_attributes::ParsedCriAttribute; use x509_parser::extensions::ParsedExtension; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::prelude::{FromDer, X509CertificationRequest}; use super::*; use crate::test_util::tests::*; use crate::{Ecdsa384CsrBuilder, Ecdsa384Signature}; const TEST_UEID: &[u8] = &[0xAB; FmcAliasCsrTbsEcc384::UEID_LEN]; const TEST_DEVICE_INFO_HASH: &[u8] = &[0xCDu8; FmcAliasCsrTbsEcc384Params::TCB_INFO_DEVICE_INFO_HASH_LEN]; const TEST_FMC_HASH: &[u8] = &[0xEFu8; FmcAliasCsrTbsEcc384Params::TCB_INFO_FMC_TCI_LEN]; const TEST_TCB_INFO_FLAGS: &[u8] = &[0xB0, 0xB1, 0xB2, 0xB3]; const TEST_TCB_INFO_FMC_SVN: &[u8] = &[0xB7]; const TEST_TCB_INFO_FMC_SVN_FUSES: &[u8] = &[0xB8]; fn make_test_csr(subject_key: &Ecc384AsymKey) -> FmcAliasCsrTbsEcc384 { let params = FmcAliasCsrTbsEcc384Params { public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key.hex_str().into_bytes().try_into().unwrap(), ueid: &TEST_UEID.try_into().unwrap(), tcb_info_flags: TEST_TCB_INFO_FLAGS.try_into().unwrap(), tcb_info_device_info_hash: &TEST_DEVICE_INFO_HASH.try_into().unwrap(), tcb_info_fmc_tci: &TEST_FMC_HASH.try_into().unwrap(), tcb_info_fmc_svn: &TEST_TCB_INFO_FMC_SVN.try_into().unwrap(), tcb_info_fmc_svn_fuses: &TEST_TCB_INFO_FMC_SVN_FUSES.try_into().unwrap(), }; FmcAliasCsrTbsEcc384::new(&params) } #[test] fn test_csr_signing() { let key = Ecc384AsymKey::default(); let ec_key = key.priv_key().ec_key().unwrap(); let csr = make_test_csr(&key); let sig: EcdsaSig = csr .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(csr.tbs(), FmcAliasCsrTbsEcc384::TBS_TEMPLATE); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::PUBLIC_KEY_OFFSET ..FmcAliasCsrTbsEcc384::PUBLIC_KEY_OFFSET + FmcAliasCsrTbsEcc384::PUBLIC_KEY_LEN], key.pub_key(), ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::SUBJECT_SN_OFFSET ..FmcAliasCsrTbsEcc384::SUBJECT_SN_OFFSET + FmcAliasCsrTbsEcc384::SUBJECT_SN_LEN], key.hex_str().into_bytes(), ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::UEID_OFFSET ..FmcAliasCsrTbsEcc384::UEID_OFFSET + FmcAliasCsrTbsEcc384::UEID_LEN], TEST_UEID, ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_OFFSET ..FmcAliasCsrTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_OFFSET + FmcAliasCsrTbsEcc384::TCB_INFO_DEVICE_INFO_HASH_LEN], TEST_DEVICE_INFO_HASH, ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::TCB_INFO_FMC_TCI_OFFSET ..FmcAliasCsrTbsEcc384::TCB_INFO_FMC_TCI_OFFSET + FmcAliasCsrTbsEcc384::TCB_INFO_FMC_TCI_LEN], TEST_FMC_HASH, ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::TCB_INFO_FLAGS_OFFSET ..FmcAliasCsrTbsEcc384::TCB_INFO_FLAGS_OFFSET + FmcAliasCsrTbsEcc384::TCB_INFO_FLAGS_LEN], TEST_TCB_INFO_FLAGS, ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_OFFSET ..FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_OFFSET + FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_LEN], TEST_TCB_INFO_FMC_SVN, ); assert_eq!( &csr.tbs()[FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_FUSES_OFFSET ..FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_FUSES_OFFSET + FmcAliasCsrTbsEcc384::TCB_INFO_FMC_SVN_FUSES_LEN], TEST_TCB_INFO_FMC_SVN_FUSES, ); let ecdsa_sig = crate::Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = crate::Ecdsa384CsrBuilder::new(csr.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let req: X509Req = X509Req::from_der(&buf).unwrap(); assert!(req.verify(&req.public_key().unwrap()).unwrap()); assert!(req.verify(key.priv_key()).unwrap()); } #[test] fn test_extensions() { let key = Ecc384AsymKey::default(); let ec_key = key.priv_key().ec_key().unwrap(); let csr = make_test_csr(&key); let sig: EcdsaSig = csr .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); let ecdsa_sig = Ecdsa384Signature { r: sig.r().to_vec_padded(48).unwrap().try_into().unwrap(), s: sig.s().to_vec_padded(48).unwrap().try_into().unwrap(), }; let builder = Ecdsa384CsrBuilder::new(csr.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let (_, parsed_csr) = X509CertificationRequest::from_der(&buf).unwrap(); let requested_extensions = parsed_csr .certification_request_info .iter_attributes() .find_map(|attr| { if let ParsedCriAttribute::ExtensionRequest(requested) = attr.parsed_attribute() { Some(&requested.extensions) } else { None } }) .unwrap(); // BasicConstraints let bc_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::BasicConstraints(_))) .unwrap(); let ParsedExtension::BasicConstraints(bc) = bc_ext.parsed_extension() else { panic!("Extension is not BasicConstraints"); }; assert!(bc_ext.critical); assert!(bc.ca); // KeyUsage let ku_ext = requested_extensions .iter() .find(|ext| matches!(ext.parsed_extension(), ParsedExtension::KeyUsage(_))) .unwrap(); assert!(ku_ext.critical); // UEID let ueid_ext = requested_extensions .iter() .find(|ext| { if let ParsedExtension::UnsupportedExtension { oid } = ext.parsed_extension() { oid == &oid!(2.23.133 .5 .4 .4) } else { false } }) .unwrap(); assert!(!ueid_ext.critical); // TCB info let multi_tcb_info = requested_extensions .iter() .find(|ext| { if let ParsedExtension::UnsupportedExtension { oid } = ext.parsed_extension() { oid == &oid!(2.23.133 .5 .4 .5) } else { false } }) .unwrap(); assert!(!multi_tcb_info.critical); } #[test] #[cfg(feature = "generate_templates")] fn test_fmc_alias_csr_template() { let manual_template = std::fs::read(std::path::Path::new("./build/fmc_alias_cert_tbs.rs")).unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/fmc_alias_cert_tbs.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!("Auto-generated FMC Alias CSR template is not equal to the manual template.") } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/cert_bldr.rs
x509/src/cert_bldr.rs
/*++ Licensed under the Apache-2.0 license. File Name: cert_bldr.rs Abstract: X509 API to construct Certificate or Certificate Signing Request from "To Be Signed" blob and ECDSA-384 Signature. --*/ use crate::{der_encode_len, der_encode_uint, der_uint_len}; /// DER Bit String Tag const DER_BIT_STR_TAG: u8 = 0x03; /// DER Sequence Tag const DER_SEQ_TAG: u8 = 0x30; /// Trait for signature types pub trait Signature<const MAX_DER_SIZE: usize> { /// Convert the signature to DER format fn to_der(&self, buf: &mut [u8; MAX_DER_SIZE]) -> Option<usize>; /// DER Encoded Sequence with signature algorithm OID fn oid_der() -> &'static [u8]; } /// ECDSA-384 Signature #[derive(Debug)] pub struct Ecdsa384Signature { /// Signature R-Coordinate pub r: [u8; Self::ECDSA_COORD_LEN], /// Signature S-Coordinate pub s: [u8; Self::ECDSA_COORD_LEN], } impl Default for Ecdsa384Signature { fn default() -> Self { Self { r: [0; Self::ECDSA_COORD_LEN], s: [0; Self::ECDSA_COORD_LEN], } } } impl Ecdsa384Signature { /// ECDSA Coordinate length pub const ECDSA_COORD_LEN: usize = 48; } impl Signature<108> for Ecdsa384Signature { fn to_der(&self, buf: &mut [u8; 108]) -> Option<usize> { // Encode Signature R Coordinate let r_uint_len = der_uint_len(&self.r); // Encode Signature S Coordinate let s_uint_len = der_uint_len(&self.s); // // Signature DER Sequence encoding // // sig_seq_len = TAG (1 byte) + LEN (1 byte) + r_uint_len + s_uint_len // let sig_seq_len = 2 + r_uint_len + s_uint_len; let mut pos = 0; // Encode Signature DER Bit String *buf.get_mut(pos)? = DER_BIT_STR_TAG; pos += 1; *buf.get_mut(pos)? = (1 + sig_seq_len) as u8; pos += 1; *buf.get_mut(pos)? = 0x0; pos += 1; // Encode Signature DER Sequence *buf.get_mut(pos)? = DER_SEQ_TAG; pos += 1; *buf.get_mut(pos)? = (r_uint_len + s_uint_len) as u8; pos += 1; // Encode R-Coordinate pos += der_encode_uint(&self.r, buf.get_mut(pos..)?)?; // Encode S-Coordinate pos += der_encode_uint(&self.s, buf.get_mut(pos..)?)?; Some(pos) } fn oid_der() -> &'static [u8] { &[ 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03, ] } } /// Ml-Dsa87 Signature pub struct MlDsa87Signature { pub sig: [u8; 4627], } impl Default for MlDsa87Signature { /// Returns the "default value" for a type. fn default() -> Self { Self { sig: [0; 4627] } } } impl Signature<4641> for MlDsa87Signature { fn to_der(&self, buf: &mut [u8; 4641]) -> Option<usize> { // // Signature DER Sequence encoding // let sig_seq_len = self.sig.len(); let mut pos = 0; // Encode Signature DER Bit String *buf.get_mut(pos)? = DER_BIT_STR_TAG; pos += 1; pos += der_encode_len(1 + sig_seq_len, buf.get_mut(pos..)?)?; *buf.get_mut(pos)? = 0x0; pos += 1; buf.get_mut(pos..pos + self.sig.len())? .copy_from_slice(&self.sig); pos += sig_seq_len; Some(pos) } fn oid_der() -> &'static [u8] { &[ 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13, ] } } /// Generic Certificate Builder #[derive(Debug)] pub struct CertBuilder<'a, S: Signature<MAX_DER_SIZE>, const MAX_DER_SIZE: usize> { /// DER encoded To be signed portion tbs: &'a [u8], /// Signature of the To be signed portion sig: &'a S, /// Length of the signed Cert/CSR len: usize, } impl<'a, S: Signature<MAX_DER_SIZE>, const MAX_DER_SIZE: usize> CertBuilder<'a, S, MAX_DER_SIZE> { /// Create an instance of `CertBuilder` /// /// # Arguments /// /// * `tbs` - DER encoded To be signed portion /// * `sig` - Signature of the To be signed portion pub fn new(tbs: &'a [u8], sig: &'a S) -> Option<Self> { let mut sig_buf = [0u8; MAX_DER_SIZE]; let sig_len = sig.to_der(&mut sig_buf)?; let len = Self::compute_len(tbs.len(), sig_len, S::oid_der().len())?; Some(Self { tbs, sig, len }) } /// Build the Certificate or Certificate Signing Request /// /// # Arguments /// /// * `buf` - Buffer to construct the certificate in pub fn build(&self, buf: &mut [u8]) -> Option<usize> { if buf.len() < self.len { return None; } let mut pos = 0; // Copy Tag *buf.get_mut(pos)? = DER_SEQ_TAG; pos += 1; // Copy Length let mut sig_buf = [0u8; MAX_DER_SIZE]; let sig_len = self.sig.to_der(&mut sig_buf)?; let len = self.tbs.len() + S::oid_der().len() + sig_len; if buf.len() < len + 4 { return None; } pos += der_encode_len(len, buf.get_mut(pos..)?)?; // Copy Value // Copy TBS DER buf.get_mut(pos..pos + self.tbs.len())? .copy_from_slice(self.tbs); pos += self.tbs.len(); // Copy OID DER buf.get_mut(pos..pos + S::oid_der().len())? .copy_from_slice(S::oid_der()); pos += S::oid_der().len(); // Copy Signature DER buf.get_mut(pos..pos + sig_len)? .copy_from_slice(sig_buf.get(..sig_len)?); pos += sig_len; Some(pos) } /// Return the length of Certificate or Certificate Signing Request #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.len } // Compute length of the X509 certificate or cert signing request fn compute_len(tbs_len: usize, sig_der_len: usize, oid_len: usize) -> Option<usize> { let len = tbs_len + oid_len + sig_der_len; // Max Cert or CSR size is 0xffff bytes let len_bytes = match len { 0..=0x7f => 1_usize, 0x80..=0xff => 2, 0x100..=0xffff => 3, _ => None?, }; // // Length of the CSR or Certificate // // Certificate is encoded as DER Sequence // TAG (1 byte) + LEN (len_bytes bytes) + len (Length of the sequence contents) Some(1 + len_bytes + len) } } // Type alias for ECDSA-384 Certificate Builder pub type Ecdsa384CertBuilder<'a> = CertBuilder<'a, Ecdsa384Signature, 108>; pub type Ecdsa384CsrBuilder<'a> = Ecdsa384CertBuilder<'a>; // Type alias for Ml-Dsa87 Certificate Builder pub type MlDsa87CertBuilder<'a> = CertBuilder<'a, MlDsa87Signature, 4641>; pub type MlDsa87CsrBuilder<'a> = MlDsa87CertBuilder<'a>;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/fmc_alias_cert_mldsa_87.rs
x509/src/fmc_alias_cert_mldsa_87.rs
/*++ Licensed under the Apache-2.0 license. File Name: fmc_alias_cert.rs Abstract: ML-DSA87 FMC Alias Certificate related code. --*/ // Note: All the necessary code is auto generated #[cfg(feature = "generate_templates")] include!(concat!(env!("OUT_DIR"), "/fmc_alias_cert_tbs_ml_dsa_87.rs")); #[cfg(not(feature = "generate_templates"))] include! {"../build/fmc_alias_cert_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{MlDsa87CertBuilder, MlDsa87Signature, NotAfter, NotBefore}; const TEST_DEVICE_INFO_HASH: &[u8] = &[0xCDu8; FmcAliasCertTbsMlDsa87Params::TCB_INFO_DEVICE_INFO_HASH_LEN]; const TEST_FMC_HASH: &[u8] = &[0xEFu8; FmcAliasCertTbsMlDsa87Params::TCB_INFO_FMC_TCI_LEN]; const TEST_UEID: &[u8] = &[0xABu8; FmcAliasCertTbsMlDsa87Params::UEID_LEN]; const TEST_TCB_INFO_FLAGS: &[u8] = &[0xB0, 0xB1, 0xB2, 0xB3]; const TEST_TCB_INFO_FW_SVN: &[u8] = &[0xB7]; const TEST_TCB_INFO_FW_SVN_FUSES: &[u8] = &[0xB8]; fn make_test_cert( subject_key: &MlDsa87AsymKey, issuer_key: &MlDsa87AsymKey, ) -> FmcAliasCertTbsMlDsa87 { let params = FmcAliasCertTbsMlDsa87Params { serial_number: &[0xABu8; FmcAliasCertTbsMlDsa87Params::SERIAL_NUMBER_LEN], public_key: &subject_key.pub_key().try_into().unwrap(), subject_sn: &subject_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), issuer_sn: &issuer_key .hex_str() .into_bytes() .as_slice() .try_into() .unwrap(), ueid: TEST_UEID.try_into().unwrap(), subject_key_id: &subject_key.sha1(), authority_key_id: &issuer_key.sha1(), tcb_info_flags: TEST_TCB_INFO_FLAGS.try_into().unwrap(), tcb_info_device_info_hash: &TEST_DEVICE_INFO_HASH.try_into().unwrap(), tcb_info_fmc_tci: &TEST_FMC_HASH.try_into().unwrap(), tcb_info_fw_svn: &TEST_TCB_INFO_FW_SVN.try_into().unwrap(), tcb_info_fw_svn_fuses: &TEST_TCB_INFO_FW_SVN_FUSES.try_into().unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; FmcAliasCertTbsMlDsa87::new(&params) } #[test] fn test_cert_signing() { let subject_key = MlDsa87AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(cert.tbs(), FmcAliasCertTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::PUBLIC_KEY_OFFSET ..FmcAliasCertTbsMlDsa87::PUBLIC_KEY_OFFSET + FmcAliasCertTbsMlDsa87::PUBLIC_KEY_LEN], subject_key.pub_key(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::SUBJECT_SN_OFFSET ..FmcAliasCertTbsMlDsa87::SUBJECT_SN_OFFSET + FmcAliasCertTbsMlDsa87::SUBJECT_SN_LEN], subject_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::ISSUER_SN_OFFSET ..FmcAliasCertTbsMlDsa87::ISSUER_SN_OFFSET + FmcAliasCertTbsMlDsa87::ISSUER_SN_LEN], issuer_key.hex_str().into_bytes(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::UEID_OFFSET ..FmcAliasCertTbsMlDsa87::UEID_OFFSET + FmcAliasCertTbsMlDsa87::UEID_LEN], TEST_UEID, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET ..FmcAliasCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET + FmcAliasCertTbsMlDsa87::SUBJECT_KEY_ID_LEN], subject_key.sha1(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET ..FmcAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET + FmcAliasCertTbsMlDsa87::AUTHORITY_KEY_ID_LEN], issuer_key.sha1(), ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::TCB_INFO_FLAGS_OFFSET ..FmcAliasCertTbsMlDsa87::TCB_INFO_FLAGS_OFFSET + FmcAliasCertTbsMlDsa87::TCB_INFO_FLAGS_LEN], TEST_TCB_INFO_FLAGS, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::TCB_INFO_DEVICE_INFO_HASH_OFFSET ..FmcAliasCertTbsMlDsa87::TCB_INFO_DEVICE_INFO_HASH_OFFSET + FmcAliasCertTbsMlDsa87::TCB_INFO_DEVICE_INFO_HASH_LEN], TEST_DEVICE_INFO_HASH, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::TCB_INFO_FMC_TCI_OFFSET ..FmcAliasCertTbsMlDsa87::TCB_INFO_FMC_TCI_OFFSET + FmcAliasCertTbsMlDsa87::TCB_INFO_FMC_TCI_LEN], TEST_FMC_HASH, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_OFFSET ..FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_OFFSET + FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_LEN], TEST_TCB_INFO_FW_SVN, ); assert_eq!( &cert.tbs()[FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_FUSES_OFFSET ..FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_FUSES_OFFSET + FmcAliasCertTbsMlDsa87::TCB_INFO_FW_SVN_FUSES_LEN], TEST_TCB_INFO_FW_SVN_FUSES, ); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); } #[test] fn test_extensions() { let subject_key = MlDsa87AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let cert = make_test_cert(&subject_key, &issuer_key); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); let mldsa_sig = MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); // Basic checks on standard extensions let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(basic_constraints.value.ca); let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); // Check that TCG extensions are present let ext_map = parsed_cert.extensions_map().unwrap(); const UEID_OID: Oid = oid!(2.23.133 .5 .4 .4); assert!(!ext_map[&UEID_OID].critical); const MULTI_TCB_INFO_OID: Oid = oid!(2.23.133 .5 .4 .5); assert!(!ext_map[&MULTI_TCB_INFO_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_fmc_alias_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/fmc_alias_cert_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/fmc_alias_cert_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated FMC Alias Certificate template is not equal to the manual template." ) } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/src/ocp_lock_hpke_certs.rs
x509/src/ocp_lock_hpke_certs.rs
// Licensed under the Apache-2.0 license pub mod ml_kem_ecc_348 { #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/ocp_lock_ml_kem_cert_tbs_ecc_384.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/ocp_lock_ml_kem_cert_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::ecdsa::EcdsaSig; use openssl::sha::Sha384; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert() { let subject_key = MlKem1024AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let params = OcpLockMlKemCertTbsEcc384Params { serial_number: &[0xABu8; OcpLockMlKemCertTbsEcc384Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; OcpLockMlKemCertTbsEcc384Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; OcpLockMlKemCertTbsEcc384Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; OcpLockMlKemCertTbsEcc384Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), subject_key_id: &TryInto::<[u8; OcpLockMlKemCertTbsEcc384Params::SUBJECT_KEY_ID_LEN]>::try_into( subject_key.sha1(), ) .unwrap(), authority_key_id: &TryInto::< [u8; OcpLockMlKemCertTbsEcc384Params::AUTHORITY_KEY_ID_LEN], >::try_into(issuer_key.sha1()) .unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = OcpLockMlKemCertTbsEcc384::new(&params); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(cert.tbs(), OcpLockMlKemCertTbsEcc384::TBS_TEMPLATE); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsEcc384::PUBLIC_KEY_OFFSET ..OcpLockMlKemCertTbsEcc384::PUBLIC_KEY_OFFSET + OcpLockMlKemCertTbsEcc384::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsEcc384::SUBJECT_SN_OFFSET ..OcpLockMlKemCertTbsEcc384::SUBJECT_SN_OFFSET + OcpLockMlKemCertTbsEcc384::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsEcc384::ISSUER_SN_OFFSET ..OcpLockMlKemCertTbsEcc384::ISSUER_SN_OFFSET + OcpLockMlKemCertTbsEcc384::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsEcc384::SUBJECT_KEY_ID_OFFSET ..OcpLockMlKemCertTbsEcc384::SUBJECT_KEY_ID_OFFSET + OcpLockMlKemCertTbsEcc384::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET ..OcpLockMlKemCertTbsEcc384::AUTHORITY_KEY_ID_OFFSET + OcpLockMlKemCertTbsEcc384::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); let ecdsa_sig = crate::Ecdsa384Signature { r: TryInto::<[u8; 48]>::try_into(sig.r().to_vec_padded(48).unwrap()).unwrap(), s: TryInto::<[u8; 48]>::try_into(sig.s().to_vec_padded(48).unwrap()).unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(!basic_constraints.value.ca); // Check key usage. OCP LOCK HPKE certs should only allow key encipherment let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); assert!(key_usage.value.key_encipherment()); assert!(!key_usage.value.key_cert_sign()); assert!(!key_usage.value.digital_signature()); // Check that HPKE Identifiers extension is present let ext_map = parsed_cert.extensions_map().unwrap(); const HPKE_IDENTIFIERS_OID: Oid = oid!(2.23.133 .21 .1 .1); assert!(!ext_map[&HPKE_IDENTIFIERS_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ocp_lock_mlkem_ecc384_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/ocp_lock_ml_kem_cert_tbs_ecc_384.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/ocp_lock_ml_kem_cert_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated OCP LOCK ML-KEM 1024 EC Certificate template is not equal to the manual template." ) } } } } pub mod ml_kem_mldsa_87 { #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert() { let subject_key = MlKem1024AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let params = OcpLockMlKemCertTbsMlDsa87Params { serial_number: &[0xABu8; OcpLockMlKemCertTbsMlDsa87Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; OcpLockMlKemCertTbsMlDsa87Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; OcpLockMlKemCertTbsMlDsa87Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; OcpLockMlKemCertTbsMlDsa87Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), subject_key_id: &TryInto::< [u8; OcpLockMlKemCertTbsMlDsa87Params::SUBJECT_KEY_ID_LEN], >::try_into(subject_key.sha1()) .unwrap(), authority_key_id: &TryInto::< [u8; OcpLockMlKemCertTbsMlDsa87Params::AUTHORITY_KEY_ID_LEN], >::try_into(issuer_key.sha1()) .unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = OcpLockMlKemCertTbsMlDsa87::new(&params); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(cert.tbs(), OcpLockMlKemCertTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsMlDsa87::PUBLIC_KEY_OFFSET ..OcpLockMlKemCertTbsMlDsa87::PUBLIC_KEY_OFFSET + OcpLockMlKemCertTbsMlDsa87::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsMlDsa87::SUBJECT_SN_OFFSET ..OcpLockMlKemCertTbsMlDsa87::SUBJECT_SN_OFFSET + OcpLockMlKemCertTbsMlDsa87::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsMlDsa87::ISSUER_SN_OFFSET ..OcpLockMlKemCertTbsMlDsa87::ISSUER_SN_OFFSET + OcpLockMlKemCertTbsMlDsa87::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET ..OcpLockMlKemCertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET + OcpLockMlKemCertTbsMlDsa87::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[OcpLockMlKemCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET ..OcpLockMlKemCertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET + OcpLockMlKemCertTbsMlDsa87::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(!basic_constraints.value.ca); // Check key usage. OCP LOCK HPKE certs should only allow key encipherment let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); assert!(key_usage.value.key_encipherment()); assert!(!key_usage.value.key_cert_sign()); assert!(!key_usage.value.digital_signature()); // Check that HPKE Identifiers extension is present let ext_map = parsed_cert.extensions_map().unwrap(); const HPKE_IDENTIFIERS_OID: Oid = oid!(2.23.133 .21 .1 .1); assert!(!ext_map[&HPKE_IDENTIFIERS_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ocp_lock_mlkem_mldsa87_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated OCP LOCK ML-KEM 1024 ML-DSA Certificate template is not equal to the manual template." ) } } } } pub mod ecdh_384_ecc_348 { #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::ecdsa::EcdsaSig; use openssl::sha::Sha384; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert() { let subject_key = Ecc384AsymKey::default(); let issuer_key = Ecc384AsymKey::default(); let ec_key = issuer_key.priv_key().ec_key().unwrap(); let params = OcpLockEcdh384CertTbsEcc384Params { serial_number: &[0xABu8; OcpLockEcdh384CertTbsEcc384Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; OcpLockEcdh384CertTbsEcc384Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; OcpLockEcdh384CertTbsEcc384Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; OcpLockEcdh384CertTbsEcc384Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), subject_key_id: &TryInto::< [u8; OcpLockEcdh384CertTbsEcc384Params::SUBJECT_KEY_ID_LEN], >::try_into(subject_key.sha1()) .unwrap(), authority_key_id: &TryInto::< [u8; OcpLockEcdh384CertTbsEcc384Params::AUTHORITY_KEY_ID_LEN], >::try_into(issuer_key.sha1()) .unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = OcpLockEcdh384CertTbsEcc384::new(&params); let sig = cert .sign(|b| { let mut sha = Sha384::new(); sha.update(b); EcdsaSig::sign(&sha.finish(), &ec_key) }) .unwrap(); assert_ne!(cert.tbs(), OcpLockEcdh384CertTbsEcc384::TBS_TEMPLATE); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsEcc384::PUBLIC_KEY_OFFSET ..OcpLockEcdh384CertTbsEcc384::PUBLIC_KEY_OFFSET + OcpLockEcdh384CertTbsEcc384::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsEcc384::SUBJECT_SN_OFFSET ..OcpLockEcdh384CertTbsEcc384::SUBJECT_SN_OFFSET + OcpLockEcdh384CertTbsEcc384::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsEcc384::ISSUER_SN_OFFSET ..OcpLockEcdh384CertTbsEcc384::ISSUER_SN_OFFSET + OcpLockEcdh384CertTbsEcc384::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsEcc384::SUBJECT_KEY_ID_OFFSET ..OcpLockEcdh384CertTbsEcc384::SUBJECT_KEY_ID_OFFSET + OcpLockEcdh384CertTbsEcc384::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsEcc384::AUTHORITY_KEY_ID_OFFSET ..OcpLockEcdh384CertTbsEcc384::AUTHORITY_KEY_ID_OFFSET + OcpLockEcdh384CertTbsEcc384::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); let ecdsa_sig = crate::Ecdsa384Signature { r: TryInto::<[u8; 48]>::try_into(sig.r().to_vec_padded(48).unwrap()).unwrap(), s: TryInto::<[u8; 48]>::try_into(sig.s().to_vec_padded(48).unwrap()).unwrap(), }; let builder = crate::Ecdsa384CertBuilder::new(cert.tbs(), &ecdsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(!basic_constraints.value.ca); // Check key usage. OCP LOCK HPKE certs should only allow key encipherment let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); assert!(key_usage.value.key_encipherment()); assert!(!key_usage.value.key_cert_sign()); assert!(!key_usage.value.digital_signature()); // Check that HPKE Identifiers extension is present let ext_map = parsed_cert.extensions_map().unwrap(); const HPKE_IDENTIFIERS_OID: Oid = oid!(2.23.133 .21 .1 .1); assert!(!ext_map[&HPKE_IDENTIFIERS_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ocp_lock_ecdh_ecc384_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated OCP LOCK ECDH P-384 EC Certificate template is not equal to the manual template." ) } } } } pub mod ecdh_384_mldsa_87 { #[cfg(feature = "generate_templates")] include!(concat!( env!("OUT_DIR"), "/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs" )); #[cfg(not(feature = "generate_templates"))] include! {"../build/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs"} #[cfg(all(test, target_family = "unix"))] mod tests { use openssl::pkey_ctx::PkeyCtx; use openssl::pkey_ml_dsa::Variant; use openssl::signature::Signature; use openssl::x509::X509; use x509_parser::nom::Parser; use x509_parser::oid_registry::asn1_rs::oid; use x509_parser::oid_registry::Oid; use x509_parser::prelude::X509CertificateParser; use x509_parser::x509::X509Version; use super::*; use crate::test_util::tests::*; use crate::{NotAfter, NotBefore}; #[test] fn test_cert() { let subject_key = Ecc384AsymKey::default(); let issuer_key = MlDsa87AsymKey::default(); let mldsa_key = issuer_key.priv_key(); let params = OcpLockEcdh384CertTbsMlDsa87Params { serial_number: &[0xABu8; OcpLockEcdh384CertTbsMlDsa87Params::SERIAL_NUMBER_LEN], public_key: TryInto::<&[u8; OcpLockEcdh384CertTbsMlDsa87Params::PUBLIC_KEY_LEN]>::try_into( subject_key.pub_key(), ) .unwrap(), subject_sn: &TryInto::<[u8; OcpLockEcdh384CertTbsMlDsa87Params::SUBJECT_SN_LEN]>::try_into( subject_key.hex_str().into_bytes(), ) .unwrap(), issuer_sn: &TryInto::<[u8; OcpLockEcdh384CertTbsMlDsa87Params::ISSUER_SN_LEN]>::try_into( issuer_key.hex_str().into_bytes(), ) .unwrap(), subject_key_id: &TryInto::< [u8; OcpLockEcdh384CertTbsMlDsa87Params::SUBJECT_KEY_ID_LEN], >::try_into(subject_key.sha1()) .unwrap(), authority_key_id: &TryInto::< [u8; OcpLockEcdh384CertTbsMlDsa87Params::AUTHORITY_KEY_ID_LEN], >::try_into(issuer_key.sha1()) .unwrap(), not_before: &NotBefore::default().value, not_after: &NotAfter::default().value, }; let cert = OcpLockEcdh384CertTbsMlDsa87::new(&params); let sig = cert .sign(|b| { let mut signature = vec![]; let mut ctx = PkeyCtx::new(mldsa_key)?; let mut algo = Signature::for_ml_dsa(Variant::MlDsa87)?; ctx.sign_message_init(&mut algo)?; ctx.sign_to_vec(b, &mut signature)?; Ok::<Vec<u8>, openssl::error::ErrorStack>(signature) }) .unwrap(); assert_ne!(cert.tbs(), OcpLockEcdh384CertTbsMlDsa87::TBS_TEMPLATE); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsMlDsa87::PUBLIC_KEY_OFFSET ..OcpLockEcdh384CertTbsMlDsa87::PUBLIC_KEY_OFFSET + OcpLockEcdh384CertTbsMlDsa87::PUBLIC_KEY_LEN], params.public_key, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsMlDsa87::SUBJECT_SN_OFFSET ..OcpLockEcdh384CertTbsMlDsa87::SUBJECT_SN_OFFSET + OcpLockEcdh384CertTbsMlDsa87::SUBJECT_SN_LEN], params.subject_sn, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsMlDsa87::ISSUER_SN_OFFSET ..OcpLockEcdh384CertTbsMlDsa87::ISSUER_SN_OFFSET + OcpLockEcdh384CertTbsMlDsa87::ISSUER_SN_LEN], params.issuer_sn, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET ..OcpLockEcdh384CertTbsMlDsa87::SUBJECT_KEY_ID_OFFSET + OcpLockEcdh384CertTbsMlDsa87::SUBJECT_KEY_ID_LEN], params.subject_key_id, ); assert_eq!( &cert.tbs()[OcpLockEcdh384CertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET ..OcpLockEcdh384CertTbsMlDsa87::AUTHORITY_KEY_ID_OFFSET + OcpLockEcdh384CertTbsMlDsa87::AUTHORITY_KEY_ID_LEN], params.authority_key_id, ); let mldsa_sig = crate::MlDsa87Signature { sig: sig.try_into().unwrap(), }; let builder = crate::MlDsa87CertBuilder::new(cert.tbs(), &mldsa_sig).unwrap(); let mut buf = vec![0u8; builder.len()]; builder.build(&mut buf).unwrap(); let cert: X509 = X509::from_der(&buf).unwrap(); assert!(cert.verify(issuer_key.priv_key()).unwrap()); let mut parser = X509CertificateParser::new().with_deep_parse_extensions(true); let parsed_cert = match parser.parse(&buf) { Ok((_, parsed_cert)) => parsed_cert, Err(e) => panic!("x509 parsing failed: {:?}", e), }; assert_eq!(parsed_cert.version(), X509Version::V3); let basic_constraints = parsed_cert.basic_constraints().unwrap().unwrap(); assert!(basic_constraints.critical); assert!(!basic_constraints.value.ca); // Check key usage. OCP LOCK HPKE certs should only allow key encipherment let key_usage = parsed_cert.key_usage().unwrap().unwrap(); assert!(key_usage.critical); assert!(key_usage.value.key_encipherment()); assert!(!key_usage.value.key_cert_sign()); assert!(!key_usage.value.digital_signature()); // Check that HPKE Identifiers extension is present let ext_map = parsed_cert.extensions_map().unwrap(); const HPKE_IDENTIFIERS_OID: Oid = oid!(2.23.133 .21 .1 .1); assert!(!ext_map[&HPKE_IDENTIFIERS_OID].critical); } #[test] #[cfg(feature = "generate_templates")] fn test_ocp_lock_ecdh_mldsa87_template() { let manual_template = std::fs::read(std::path::Path::new( "./build/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs", )) .unwrap(); let auto_generated_template = std::fs::read(std::path::Path::new(concat!( env!("OUT_DIR"), "/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs" ))) .unwrap(); if auto_generated_template != manual_template { panic!( "Auto-generated OCP LOCK ECDH P-384 ML-DSA Certificate template is not equal to the manual template." ) } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/fuzz/src/fuzz_target_1.rs
x509/fuzz/src/fuzz_target_1.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; use std::mem::size_of; use caliptra_x509::{Ecdsa384CertBuilder, Ecdsa384Signature}; use openssl::x509::X509; fn harness(data: &[u8]) { let tbs: &[u8]; let sig: &Ecdsa384Signature; if data.len() < size_of::<Ecdsa384Signature>() { return; } // TODO: Alternatively, use structure-aware fuzzing, input comprising arguments // The corpus is seeded with TBS blobs, so parse the input as TBS first let tbs_len = data.len() - size_of::<Ecdsa384Signature>(); unsafe { tbs = &data[..tbs_len]; sig = &*(data[tbs_len..].as_ptr() as *const Ecdsa384Signature); } let builder = Ecdsa384CertBuilder::new(tbs, sig).unwrap(); let mut buf = vec![0u8; builder.len()]; if builder.build(&mut buf) == None { return; } // NB: This assumes that if x509 is returned, it is valid. // - Currently, that's not the case. This *will* panic. let _cert = X509::from_der(&buf).unwrap(); //assert!(_cert.unwrap().verify(issuer_key.priv_key()).unwrap()); } // cargo-fuzz target #[cfg(feature = "libfuzzer-sys")] fuzz_target!(|data: &[u8]| { harness(data); }); // cargo-afl target #[cfg(feature = "afl")] fn main() { fuzz!(|data: &[u8]| { harness(data); }); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/init_dev_id_csr_tbs_ecc_384.rs
x509/build/init_dev_id_csr_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct InitDevIdCsrTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub ueid: &'a [u8; 17usize], } impl InitDevIdCsrTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const UEID_LEN: usize = 17usize; } pub struct InitDevIdCsrTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl InitDevIdCsrTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 144usize; const SUBJECT_SN_OFFSET: usize = 57usize; const UEID_OFFSET: usize = 312usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const UEID_LEN: usize = 17usize; pub const TBS_TEMPLATE_LEN: usize = 329usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 1u8, 69u8, 2u8, 1u8, 0u8, 48u8, 112u8, 49u8, 35u8, 48u8, 33u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 26u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 73u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 160u8, 86u8, 48u8, 84u8, 6u8, 9u8, 42u8, 134u8, 72u8, 134u8, 247u8, 13u8, 1u8, 9u8, 14u8, 49u8, 71u8, 48u8, 69u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 7u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &InitDevIdCsrTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &InitDevIdCsrTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 329usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/code_gen.rs
x509/build/code_gen.rs
/*++ Licensed under the Apache-2.0 license. File Name: code_gen.rs Abstract: File contains code generation routines for X509 Templates --*/ use crate::tbs::TbsTemplate; use convert_case::{Case, Casing}; use quote::{__private::TokenStream, format_ident, quote}; use std::{path::Path, process::Command}; // Code Generator pub struct CodeGen {} impl CodeGen { /// Generate code /// /// # Arguments /// /// * `type_name` - Type Name, /// * `template` - To Be Signed template /// * `out_path` - Output Path pub fn gen_code(type_name: &str, template: TbsTemplate, out_path: &str) { let file_name = format!("{}.rs", type_name.to_case(Case::Snake)); let file_path = Path::new(out_path).join(file_name); std::fs::write(&file_path, Self::code(type_name, template)).unwrap(); if Command::new("rustfmt") .arg("--emit=files") .arg("--edition=2024") .arg(file_path) .spawn() .is_ok() {} } fn code(type_name: &str, template: TbsTemplate) -> String { let type_name = format_ident!("{}", type_name); let param_name = format_ident!("{}Params", type_name); let param_vars = template.params().iter().map(|p| { let name = format_ident!("{}", p.name.to_case(Case::Snake)); let value = p.len; quote! { #name: &'a[u8; #value], } }); let offset_consts = template.params().iter().map(|p| { let name = format_ident!("{}_OFFSET", p.name.to_uppercase()); let value = p.offset; quote! { const #name: usize = #value; } }); let len_consts: Vec<TokenStream> = template .params() .iter() .map(|p| { let name = format_ident!("{}_LEN", p.name.to_uppercase()); let value = p.len; quote! { const #name: usize = #value; } }) .collect(); let apply_calls = template.params().iter().map(|p| { let name = format_ident!("{}", p.name.to_case(Case::Snake)); let len = format_ident!("{}_LEN", p.name.to_uppercase()); let offset = format_ident!("{}_OFFSET", p.name.to_uppercase()); quote!( apply_slice::<{Self::#offset}, {Self::#len}>(&mut self.tbs, params.#name); ) }); let tbs_len = template.tbs().len(); let tbs_len_const = quote!( pub const TBS_TEMPLATE_LEN: usize = #tbs_len; ); let tbs = template.tbs(); quote!( #[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct #param_name<'a> { #(pub #param_vars)* } impl #param_name<'_>{ #(pub #len_consts)* } pub struct #type_name { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl #type_name { #(#offset_consts)* #(#len_consts)* #tbs_len_const const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [#(#tbs,)*]; pub fn new(params: &#param_name) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &#param_name) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>(buf: &mut [u8; #tbs_len], val: &[u8; LEN]) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } #(#apply_calls)* } } ) .to_string() } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/rt_alias_cert_tbs_ml_dsa_87.rs
x509/build/rt_alias_cert_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct RtAliasCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub tcb_info_rt_tci: &'a [u8; 48usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], pub tcb_info_fw_svn: &'a [u8; 1usize], } impl RtAliasCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const TCB_INFO_RT_TCI_LEN: usize = 48usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; pub const TCB_INFO_FW_SVN_LEN: usize = 1usize; } pub struct RtAliasCertTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl RtAliasCertTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 337usize; const SUBJECT_SN_OFFSET: usize = 251usize; const ISSUER_SN_OFFSET: usize = 98usize; const TCB_INFO_RT_TCI_OFFSET: usize = 3039usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 3107usize; const AUTHORITY_KEY_ID_OFFSET: usize = 3140usize; const UEID_OFFSET: usize = 2987usize; const NOT_BEFORE_OFFSET: usize = 166usize; const NOT_AFTER_OFFSET: usize = 183usize; const TCB_INFO_FW_SVN_OFFSET: usize = 3021usize; const PUBLIC_KEY_LEN: usize = 2592usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const TCB_INFO_RT_TCI_LEN: usize = 48usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; const TCB_INFO_FW_SVN_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 3160usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 12u8, 84u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 48u8, 116u8, 49u8, 39u8, 48u8, 37u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 30u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 10u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 3u8, 130u8, 10u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 228u8, 48u8, 129u8, 225u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 4u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 132u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 90u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 1u8, 4u8, 80u8, 48u8, 78u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 7u8, 82u8, 84u8, 95u8, 73u8, 78u8, 70u8, 79u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &RtAliasCertTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &RtAliasCertTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 3160usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::TCB_INFO_RT_TCI_OFFSET }, { Self::TCB_INFO_RT_TCI_LEN }>( &mut self.tbs, params.tcb_info_rt_tci, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_OFFSET }, { Self::TCB_INFO_FW_SVN_LEN }>( &mut self.tbs, params.tcb_info_fw_svn, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/rt_alias_cert_tbs_ecc_384.rs
x509/build/rt_alias_cert_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct RtAliasCertTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub tcb_info_rt_tci: &'a [u8; 48usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], pub tcb_info_fw_svn: &'a [u8; 1usize], } impl RtAliasCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const TCB_INFO_RT_TCI_LEN: usize = 48usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; pub const TCB_INFO_FW_SVN_LEN: usize = 1usize; } pub struct RtAliasCertTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl RtAliasCertTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 335usize; const SUBJECT_SN_OFFSET: usize = 248usize; const ISSUER_SN_OFFSET: usize = 96usize; const TCB_INFO_RT_TCI_OFFSET: usize = 542usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 610usize; const AUTHORITY_KEY_ID_OFFSET: usize = 643usize; const UEID_OFFSET: usize = 490usize; const NOT_BEFORE_OFFSET: usize = 164usize; const NOT_AFTER_OFFSET: usize = 181usize; const TCB_INFO_FW_SVN_OFFSET: usize = 524usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const TCB_INFO_RT_TCI_LEN: usize = 48usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; const TCB_INFO_FW_SVN_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 663usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 147u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 10u8, 6u8, 8u8, 42u8, 134u8, 72u8, 206u8, 61u8, 4u8, 3u8, 3u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 114u8, 49u8, 37u8, 48u8, 35u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 28u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 228u8, 48u8, 129u8, 225u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 4u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 132u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 90u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 1u8, 4u8, 80u8, 48u8, 78u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 7u8, 82u8, 84u8, 95u8, 73u8, 78u8, 70u8, 79u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &RtAliasCertTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &RtAliasCertTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 663usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::TCB_INFO_RT_TCI_OFFSET }, { Self::TCB_INFO_RT_TCI_LEN }>( &mut self.tbs, params.tcb_info_rt_tci, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_OFFSET }, { Self::TCB_INFO_FW_SVN_LEN }>( &mut self.tbs, params.tcb_info_fw_svn, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/ocp_lock_ml_kem_cert_tbs_ecc_384.rs
x509/build/ocp_lock_ml_kem_cert_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct OcpLockMlKemCertTbsEcc384Params<'a> { pub public_key: &'a [u8; 1568usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl OcpLockMlKemCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 1568usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct OcpLockMlKemCertTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl OcpLockMlKemCertTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 342usize; const SUBJECT_SN_OFFSET: usize = 256usize; const ISSUER_SN_OFFSET: usize = 95usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 1988usize; const AUTHORITY_KEY_ID_OFFSET: usize = 2021usize; const NOT_BEFORE_OFFSET: usize = 163usize; const NOT_AFTER_OFFSET: usize = 180usize; const PUBLIC_KEY_LEN: usize = 1568usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 2041usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 7u8, 245u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 10u8, 6u8, 8u8, 42u8, 134u8, 72u8, 206u8, 61u8, 4u8, 3u8, 3u8, 48u8, 114u8, 49u8, 37u8, 48u8, 35u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 28u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 123u8, 49u8, 46u8, 48u8, 44u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 37u8, 79u8, 67u8, 80u8, 32u8, 76u8, 79u8, 67u8, 75u8, 32u8, 72u8, 80u8, 75u8, 69u8, 32u8, 69u8, 110u8, 100u8, 111u8, 114u8, 115u8, 101u8, 109u8, 101u8, 110u8, 116u8, 32u8, 77u8, 76u8, 45u8, 75u8, 69u8, 77u8, 32u8, 49u8, 48u8, 50u8, 52u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 6u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 4u8, 3u8, 3u8, 130u8, 6u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 128u8, 48u8, 126u8, 48u8, 15u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 5u8, 48u8, 3u8, 2u8, 1u8, 0u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 5u8, 32u8, 48u8, 27u8, 6u8, 6u8, 103u8, 129u8, 5u8, 21u8, 1u8, 1u8, 4u8, 17u8, 48u8, 15u8, 48u8, 3u8, 2u8, 1u8, 66u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &OcpLockMlKemCertTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &OcpLockMlKemCertTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 2041usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs
x509/build/ocp_lock_ecdh_384_cert_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct OcpLockEcdh384CertTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl OcpLockEcdh384CertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct OcpLockEcdh384CertTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl OcpLockEcdh384CertTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 342usize; const SUBJECT_SN_OFFSET: usize = 255usize; const ISSUER_SN_OFFSET: usize = 95usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 517usize; const AUTHORITY_KEY_ID_OFFSET: usize = 550usize; const NOT_BEFORE_OFFSET: usize = 163usize; const NOT_AFTER_OFFSET: usize = 180usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 570usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 54u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 10u8, 6u8, 8u8, 42u8, 134u8, 72u8, 206u8, 61u8, 4u8, 3u8, 3u8, 48u8, 114u8, 49u8, 37u8, 48u8, 35u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 28u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 122u8, 49u8, 45u8, 48u8, 43u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 36u8, 79u8, 67u8, 80u8, 32u8, 76u8, 79u8, 67u8, 75u8, 32u8, 72u8, 80u8, 75u8, 69u8, 32u8, 69u8, 110u8, 100u8, 111u8, 114u8, 115u8, 101u8, 109u8, 101u8, 110u8, 116u8, 32u8, 69u8, 67u8, 68u8, 72u8, 32u8, 80u8, 45u8, 51u8, 56u8, 52u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 128u8, 48u8, 126u8, 48u8, 15u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 5u8, 48u8, 3u8, 2u8, 1u8, 0u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 5u8, 32u8, 48u8, 27u8, 6u8, 6u8, 103u8, 129u8, 5u8, 21u8, 1u8, 1u8, 4u8, 17u8, 48u8, 15u8, 48u8, 3u8, 2u8, 1u8, 17u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &OcpLockEcdh384CertTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &OcpLockEcdh384CertTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 570usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/build.rs
x509/build/build.rs
/*++ Licensed under the Apache-2.0 license. File Name: build.rs Abstract: File contains the entry point for build time script used for generating various X509 artifacts used by Caliptra Firmware. --*/ #[cfg(feature = "generate_templates")] mod cert; #[cfg(feature = "generate_templates")] mod code_gen; #[cfg(feature = "generate_templates")] mod csr; #[cfg(feature = "generate_templates")] mod tbs; #[cfg(feature = "generate_templates")] mod x509; #[cfg(feature = "generate_templates")] use { code_gen::CodeGen, std::env, x509::{EcdsaSha384Algo, Fwid, FwidParam, KeyUsage, MlDsa87Algo}, }; // Version strings #[cfg(feature = "generate_templates")] const IDEVID_ECC384: &str = "Caliptra 2.1 Ecc384 IDevID"; #[cfg(feature = "generate_templates")] const IDEVID_MLDSA87: &str = "Caliptra 2.1 MlDsa87 IDevID"; #[cfg(feature = "generate_templates")] const LDEVID_ECC384: &str = "Caliptra 2.1 Ecc384 LDevID"; #[cfg(feature = "generate_templates")] const LDEVID_MLDSA87: &str = "Caliptra 2.1 MlDsa87 LDevID"; #[cfg(feature = "generate_templates")] const FMC_ALIAS_ECC384: &str = "Caliptra 2.1 Ecc384 FMC Alias"; #[cfg(feature = "generate_templates")] const FMC_ALIAS_MLDSA87: &str = "Caliptra 2.1 MlDsa87 FMC Alias"; #[cfg(feature = "generate_templates")] const RT_ALIAS_ECC384: &str = "Caliptra 2.1 Ecc384 Rt Alias"; #[cfg(feature = "generate_templates")] const RT_ALIAS_MLDSA87: &str = "Caliptra 2.1 MlDsa87 Rt Alias"; // Main Entry point fn main() { #[cfg(feature = "generate_templates")] { let out_dir_os_str = env::var_os("OUT_DIR").unwrap(); let out_dir = out_dir_os_str.to_str().unwrap(); gen_init_devid_csr(out_dir); gen_fmc_alias_csr(out_dir); gen_local_devid_cert(out_dir); gen_fmc_alias_cert(out_dir); gen_rt_alias_cert(out_dir); gen_ocp_lock_endorsement_cert(out_dir); } } /// Generate Initial DeviceId Cert Signing request Template #[cfg(feature = "generate_templates")] fn gen_init_devid_csr(out_dir: &str) { let mut usage = KeyUsage::default(); usage.set_key_cert_sign(true); let bldr = csr::CsrTemplateBuilder::<EcdsaSha384Algo>::new() .add_basic_constraints_ext(true, 7) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]); let template = bldr.tbs_template(IDEVID_ECC384); CodeGen::gen_code("InitDevIdCsrTbsEcc384", template, out_dir); let bldr = csr::CsrTemplateBuilder::<MlDsa87Algo>::new() .add_basic_constraints_ext(true, 7) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]); let template = bldr.tbs_template(IDEVID_MLDSA87); CodeGen::gen_code("InitDevIdCsrTbsMlDsa87", template, out_dir); } #[cfg(feature = "generate_templates")] fn gen_fmc_alias_csr(out_dir: &str) { let mut usage = KeyUsage::default(); usage.set_key_cert_sign(true); let bldr = csr::CsrTemplateBuilder::<EcdsaSha384Algo>::new() .add_basic_constraints_ext(true, 5) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_fmc_dice_tcb_info_ext( /*device_fwids=*/ &[FwidParam { name: "TCB_INFO_DEVICE_INFO_HASH", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xEF; 48], }, }], /*fmc_fwids=*/ &[FwidParam { name: "TCB_INFO_FMC_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }], ); let template = bldr.tbs_template(FMC_ALIAS_ECC384); CodeGen::gen_code("FmcAliasCsrTbsEcc384", template, out_dir); let bldr = csr::CsrTemplateBuilder::<MlDsa87Algo>::new() .add_basic_constraints_ext(true, 5) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_fmc_dice_tcb_info_ext( /*device_fwids=*/ &[FwidParam { name: "TCB_INFO_DEVICE_INFO_HASH", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xEF; 48], }, }], /*fmc_fwids=*/ &[FwidParam { name: "TCB_INFO_FMC_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }], ); let template = bldr.tbs_template(FMC_ALIAS_MLDSA87); CodeGen::gen_code("FmcAliasTbsMlDsa87", template, out_dir); } /// Generate Local DeviceId Certificate Template #[cfg(feature = "generate_templates")] fn gen_local_devid_cert(out_dir: &str) { let mut usage = KeyUsage::default(); usage.set_key_cert_sign(true); let bldr = cert::CertTemplateBuilder::<EcdsaSha384Algo, EcdsaSha384Algo>::new() .add_basic_constraints_ext(true, 6) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]); let template = bldr.tbs_template(LDEVID_ECC384, IDEVID_ECC384); CodeGen::gen_code("LocalDevIdCertTbsEcc384", template, out_dir); let bldr = cert::CertTemplateBuilder::<MlDsa87Algo, MlDsa87Algo>::new() .add_basic_constraints_ext(true, 6) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]); let template = bldr.tbs_template(LDEVID_MLDSA87, IDEVID_MLDSA87); CodeGen::gen_code("LocalDevIdCertTbsMlDsa87", template, out_dir); } /// Generate FMC Alias Certificate Template #[cfg(feature = "generate_templates")] fn gen_fmc_alias_cert(out_dir: &str) { let mut usage = KeyUsage::default(); usage.set_key_cert_sign(true); let bldr = cert::CertTemplateBuilder::<EcdsaSha384Algo, EcdsaSha384Algo>::new() .add_basic_constraints_ext(true, 5) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_fmc_dice_tcb_info_ext( /*device_fwids=*/ &[FwidParam { name: "TCB_INFO_DEVICE_INFO_HASH", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xEF; 48], }, }], /*fmc_fwids=*/ &[FwidParam { name: "TCB_INFO_FMC_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }], ); let template = bldr.tbs_template(FMC_ALIAS_ECC384, LDEVID_ECC384); CodeGen::gen_code("FmcAliasCertTbsEcc384", template, out_dir); let bldr = cert::CertTemplateBuilder::<MlDsa87Algo, MlDsa87Algo>::new() .add_basic_constraints_ext(true, 5) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_fmc_dice_tcb_info_ext( /*device_fwids=*/ &[FwidParam { name: "TCB_INFO_DEVICE_INFO_HASH", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xEF; 48], }, }], /*fmc_fwids=*/ &[FwidParam { name: "TCB_INFO_FMC_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }], ); let template = bldr.tbs_template(FMC_ALIAS_MLDSA87, LDEVID_MLDSA87); CodeGen::gen_code("FmcAliasCertTbsMlDsa87", template, out_dir); } /// Generate Runtime Alias Certificate Template #[cfg(feature = "generate_templates")] fn gen_rt_alias_cert(out_dir: &str) { let mut usage = KeyUsage::default(); // Add KeyCertSign to allow signing of other certs usage.set_key_cert_sign(true); // Add DigitalSignature to allow signing of firmware usage.set_digital_signature(true); let bldr = cert::CertTemplateBuilder::<EcdsaSha384Algo, EcdsaSha384Algo>::new() // Basic Constraints : CA = true, PathLen = 4 .add_basic_constraints_ext(true, 4) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_rt_dice_tcb_info_ext(&[FwidParam { name: "TCB_INFO_RT_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }]); let template = bldr.tbs_template(RT_ALIAS_ECC384, FMC_ALIAS_ECC384); CodeGen::gen_code("RtAliasCertTbsEcc384", template, out_dir); let bldr = cert::CertTemplateBuilder::<MlDsa87Algo, MlDsa87Algo>::new() // Basic Constraints : CA = true, PathLen = 4 .add_basic_constraints_ext(true, 4) .add_key_usage_ext(usage) .add_ueid_ext(&[0xFF; 17]) .add_rt_dice_tcb_info_ext(&[FwidParam { name: "TCB_INFO_RT_TCI", fwid: Fwid { hash_alg: asn1::oid!(/*sha384*/ 2, 16, 840, 1, 101, 3, 4, 2, 2), digest: &[0xCD; 48], }, }]); let template = bldr.tbs_template(RT_ALIAS_MLDSA87, FMC_ALIAS_MLDSA87); CodeGen::gen_code("RtAliasCertTbsMlDsa87", template, out_dir); } /// Generate OCP LOCK HPKE Endorsement Certificate Templates #[cfg(feature = "generate_templates")] fn gen_ocp_lock_endorsement_cert(out_dir: &str) { use x509::{HPKEIdentifiers, MlKem1024Algo}; let mut usage = KeyUsage::default(); // 4.2.2.1.3 // In addition, the X.509 extended attributes SHALL: // * Indicate the key usage as keyEncipherment usage.set_key_encipherment(true); let bldr = cert::CertTemplateBuilder::<EcdsaSha384Algo, MlKem1024Algo>::new() .add_basic_constraints_ext(false, 0) .add_key_usage_ext(usage) .add_hpke_identifiers_ext(&HPKEIdentifiers::new( HPKEIdentifiers::ML_KEM_1024_IANA_CODE_POINT, HPKEIdentifiers::HKDF_SHA384_IANA_CODE_POINT, HPKEIdentifiers::AES_256_GCM_IANA_CODE_POINT, )); let template = bldr.tbs_template("OCP LOCK HPKE Endorsement ML-KEM 1024", RT_ALIAS_ECC384); CodeGen::gen_code("OcpLockMlKemCertTbsEcc384", template, out_dir); let bldr = cert::CertTemplateBuilder::<MlDsa87Algo, MlKem1024Algo>::new() .add_basic_constraints_ext(false, 0) .add_key_usage_ext(usage) .add_hpke_identifiers_ext(&HPKEIdentifiers::new( HPKEIdentifiers::ML_KEM_1024_IANA_CODE_POINT, HPKEIdentifiers::HKDF_SHA384_IANA_CODE_POINT, HPKEIdentifiers::AES_256_GCM_IANA_CODE_POINT, )); let template = bldr.tbs_template("OCP LOCK HPKE Endorsement ML-KEM 1024", RT_ALIAS_MLDSA87); CodeGen::gen_code("OcpLockMlKemCertTbsMlDsa87", template, out_dir); let bldr = cert::CertTemplateBuilder::<EcdsaSha384Algo, EcdsaSha384Algo>::new() .add_basic_constraints_ext(false, 0) .add_key_usage_ext(usage) .add_hpke_identifiers_ext(&HPKEIdentifiers::new( HPKEIdentifiers::ECDH_P384_IANA_CODE_POINT, HPKEIdentifiers::HKDF_SHA384_IANA_CODE_POINT, HPKEIdentifiers::AES_256_GCM_IANA_CODE_POINT, )); let template = bldr.tbs_template("OCP LOCK HPKE Endorsement ECDH P-384", RT_ALIAS_ECC384); CodeGen::gen_code("OcpLockEcdh384CertTbsEcc384", template, out_dir); let bldr = cert::CertTemplateBuilder::<MlDsa87Algo, EcdsaSha384Algo>::new() .add_basic_constraints_ext(false, 0) .add_key_usage_ext(usage) .add_hpke_identifiers_ext(&HPKEIdentifiers::new( HPKEIdentifiers::ECDH_P384_IANA_CODE_POINT, HPKEIdentifiers::HKDF_SHA384_IANA_CODE_POINT, HPKEIdentifiers::AES_256_GCM_IANA_CODE_POINT, )); let template = bldr.tbs_template("OCP LOCK HPKE Endorsement ECDH P-384", RT_ALIAS_MLDSA87); CodeGen::gen_code("OcpLockEcdh384CertTbsMlDsa87", template, out_dir); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/tbs.rs
x509/build/tbs.rs
/*++ Licensed under the Apache-2.0 license. File Name: tbs.rs Abstract: File contains definition of types used as templates and parameters. --*/ use hex::ToHex; /// Template parameter #[derive(Debug, Copy, Clone)] pub struct TbsParam { pub name: &'static str, pub offset: usize, pub len: usize, } impl TbsParam { /// Create an instance `TbsParam` pub fn new(name: &'static str, offset: usize, len: usize) -> Self { Self { name, offset, len } } } /// Template pub struct TbsTemplate { buf: Vec<u8>, params: Vec<TbsParam>, } impl TbsTemplate { /// Create an instance of `TbsTemplate` pub fn new(template: Vec<u8>, params: Vec<TbsParam>) -> Self { Self { buf: template, params, } } /// Retrieve template blob pub fn tbs(&self) -> &[u8] { &self.buf } /// Retrieve template parameters pub fn params(&self) -> &[TbsParam] { &self.params } } /// Initialize template parameter with its offset pub fn init_param(needle: &[u8], haystack: &[u8], param: TbsParam) -> TbsParam { assert_eq!(needle.len(), param.len); eprintln!("{}", param.name); // Throw an error if there are multiple instances of our "needle" // This could lead to incorrect offsets in the cert template if haystack.windows(param.len).filter(|w| *w == needle).count() > 1 { panic!( "Multiple instances of needle '{}' with value\n\n{}\n\nin haystack\n\n{}", param.name, needle.encode_hex::<String>(), haystack.encode_hex::<String>() ); } let pos = haystack.windows(param.len).position(|w| w == needle); match pos { Some(offset) => TbsParam { offset, ..param }, None => panic!( "Could not find needle '{}' with value\n\n{}\n\nin haystack\n\n{}", param.name, needle.encode_hex::<String>(), haystack.encode_hex::<String>() ), } } /// Sanitize the TBS buffer for the specified parameter pub fn sanitize(param: TbsParam, buf: &mut [u8]) -> TbsParam { for byte in buf.iter_mut().skip(param.offset).take(param.len) { *byte = 0x5F; } param } /// Retrieve the TBS from DER encoded vector /// /// Note: Rust OpenSSL binding is missing the extensions to retrieve TBS portion of the X509 /// artifact #[cfg(feature = "std")] pub fn get_tbs(der: Vec<u8>) -> Vec<u8> { if der[0] != 0x30 { panic!("Invalid DER start tag"); } let der_len_offset = 1; let tbs_offset = match der[der_len_offset] { 0..=0x7F => der_len_offset + 1, 0x81 => der_len_offset + 2, 0x82 => der_len_offset + 3, _ => panic!("Unsupported DER Length"), }; if der[tbs_offset] != 0x30 { panic!("Invalid TBS start tag"); } let tbs_len_offset = tbs_offset + 1; let tbs_len = match der[tbs_len_offset] { 0..=0x7F => der[tbs_len_offset] as usize + 2, 0x81 => (der[tbs_len_offset + 1]) as usize + 3, 0x82 => { (((der[tbs_len_offset + 1]) as usize) << u8::BITS) | (((der[tbs_len_offset + 2]) as usize) + 4) } _ => panic!("Invalid DER Length"), }; der[tbs_offset..tbs_offset + tbs_len].to_vec() }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/local_dev_id_cert_tbs_ml_dsa_87.rs
x509/build/local_dev_id_cert_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct LocalDevIdCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl LocalDevIdCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct LocalDevIdCertTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl LocalDevIdCertTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 332usize; const SUBJECT_SN_OFFSET: usize = 246usize; const ISSUER_SN_OFFSET: usize = 95usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 3010usize; const AUTHORITY_KEY_ID_OFFSET: usize = 3043usize; const UEID_OFFSET: usize = 2982usize; const NOT_BEFORE_OFFSET: usize = 163usize; const NOT_AFTER_OFFSET: usize = 180usize; const PUBLIC_KEY_LEN: usize = 2592usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 3063usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 11u8, 243u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 48u8, 113u8, 49u8, 36u8, 48u8, 34u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 27u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 73u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 113u8, 49u8, 36u8, 48u8, 34u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 27u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 76u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 10u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 3u8, 130u8, 10u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 136u8, 48u8, 129u8, 133u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 6u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &LocalDevIdCertTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &LocalDevIdCertTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 3063usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/fmc_alias_csr_tbs_ecc_384.rs
x509/build/fmc_alias_csr_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct FmcAliasCsrTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub tcb_info_device_info_hash: &'a [u8; 48usize], pub tcb_info_fmc_tci: &'a [u8; 48usize], pub ueid: &'a [u8; 17usize], pub tcb_info_flags: &'a [u8; 4usize], pub tcb_info_fmc_svn: &'a [u8; 1usize], pub tcb_info_fmc_svn_fuses: &'a [u8; 1usize], } impl FmcAliasCsrTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; pub const TCB_INFO_FMC_TCI_LEN: usize = 48usize; pub const UEID_LEN: usize = 17usize; pub const TCB_INFO_FLAGS_LEN: usize = 4usize; pub const TCB_INFO_FMC_SVN_LEN: usize = 1usize; pub const TCB_INFO_FMC_SVN_FUSES_LEN: usize = 1usize; } pub struct FmcAliasCsrTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl FmcAliasCsrTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 147usize; const SUBJECT_SN_OFFSET: usize = 60usize; const TCB_INFO_DEVICE_INFO_HASH_OFFSET: usize = 380usize; const TCB_INFO_FMC_TCI_OFFSET: usize = 478usize; const UEID_OFFSET: usize = 323usize; const TCB_INFO_FLAGS_OFFSET: usize = 431usize; const TCB_INFO_FMC_SVN_OFFSET: usize = 460usize; const TCB_INFO_FMC_SVN_FUSES_OFFSET: usize = 362usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; const TCB_INFO_FMC_TCI_LEN: usize = 48usize; const UEID_LEN: usize = 17usize; const TCB_INFO_FLAGS_LEN: usize = 4usize; const TCB_INFO_FMC_SVN_LEN: usize = 1usize; const TCB_INFO_FMC_SVN_FUSES_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 536usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 20u8, 2u8, 1u8, 0u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 160u8, 130u8, 1u8, 32u8, 48u8, 130u8, 1u8, 28u8, 6u8, 9u8, 42u8, 134u8, 72u8, 134u8, 247u8, 13u8, 1u8, 9u8, 14u8, 49u8, 130u8, 1u8, 13u8, 48u8, 130u8, 1u8, 9u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 5u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 129u8, 193u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 5u8, 4u8, 129u8, 182u8, 48u8, 129u8, 179u8, 48u8, 96u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 135u8, 5u8, 0u8, 95u8, 95u8, 95u8, 95u8, 137u8, 11u8, 68u8, 69u8, 86u8, 73u8, 67u8, 69u8, 95u8, 73u8, 78u8, 70u8, 79u8, 138u8, 5u8, 0u8, 208u8, 0u8, 0u8, 1u8, 48u8, 79u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 8u8, 70u8, 77u8, 67u8, 95u8, 73u8, 78u8, 70u8, 79u8, ]; pub fn new(params: &FmcAliasCsrTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &FmcAliasCsrTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 536usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::< { Self::TCB_INFO_DEVICE_INFO_HASH_OFFSET }, { Self::TCB_INFO_DEVICE_INFO_HASH_LEN }, >(&mut self.tbs, params.tcb_info_device_info_hash); apply_slice::<{ Self::TCB_INFO_FMC_TCI_OFFSET }, { Self::TCB_INFO_FMC_TCI_LEN }>( &mut self.tbs, params.tcb_info_fmc_tci, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::TCB_INFO_FLAGS_OFFSET }, { Self::TCB_INFO_FLAGS_LEN }>( &mut self.tbs, params.tcb_info_flags, ); apply_slice::<{ Self::TCB_INFO_FMC_SVN_OFFSET }, { Self::TCB_INFO_FMC_SVN_LEN }>( &mut self.tbs, params.tcb_info_fmc_svn, ); apply_slice::<{ Self::TCB_INFO_FMC_SVN_FUSES_OFFSET }, { Self::TCB_INFO_FMC_SVN_FUSES_LEN }>( &mut self.tbs, params.tcb_info_fmc_svn_fuses, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/fmc_alias_cert_tbs_ecc_384.rs
x509/build/fmc_alias_cert_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct FmcAliasCertTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub tcb_info_device_info_hash: &'a [u8; 48usize], pub tcb_info_fmc_tci: &'a [u8; 48usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], pub tcb_info_flags: &'a [u8; 4usize], pub tcb_info_fw_svn: &'a [u8; 1usize], pub tcb_info_fw_svn_fuses: &'a [u8; 1usize], } impl FmcAliasCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; pub const TCB_INFO_FMC_TCI_LEN: usize = 48usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; pub const TCB_INFO_FLAGS_LEN: usize = 4usize; pub const TCB_INFO_FW_SVN_LEN: usize = 1usize; pub const TCB_INFO_FW_SVN_FUSES_LEN: usize = 1usize; } pub struct FmcAliasCertTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl FmcAliasCertTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 333usize; const SUBJECT_SN_OFFSET: usize = 246usize; const ISSUER_SN_OFFSET: usize = 93usize; const TCB_INFO_DEVICE_INFO_HASH_OFFSET: usize = 547usize; const TCB_INFO_FMC_TCI_OFFSET: usize = 645usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 714usize; const AUTHORITY_KEY_ID_OFFSET: usize = 747usize; const UEID_OFFSET: usize = 490usize; const NOT_BEFORE_OFFSET: usize = 161usize; const NOT_AFTER_OFFSET: usize = 178usize; const TCB_INFO_FLAGS_OFFSET: usize = 598usize; const TCB_INFO_FW_SVN_OFFSET: usize = 627usize; const TCB_INFO_FW_SVN_FUSES_OFFSET: usize = 529usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; const TCB_INFO_FMC_TCI_LEN: usize = 48usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; const TCB_INFO_FLAGS_LEN: usize = 4usize; const TCB_INFO_FW_SVN_LEN: usize = 1usize; const TCB_INFO_FW_SVN_FUSES_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 767usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 251u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 10u8, 6u8, 8u8, 42u8, 134u8, 72u8, 206u8, 61u8, 4u8, 3u8, 3u8, 48u8, 112u8, 49u8, 35u8, 48u8, 33u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 26u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 76u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 130u8, 1u8, 77u8, 48u8, 130u8, 1u8, 73u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 5u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 129u8, 193u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 5u8, 4u8, 129u8, 182u8, 48u8, 129u8, 179u8, 48u8, 96u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 135u8, 5u8, 0u8, 95u8, 95u8, 95u8, 95u8, 137u8, 11u8, 68u8, 69u8, 86u8, 73u8, 67u8, 69u8, 95u8, 73u8, 78u8, 70u8, 79u8, 138u8, 5u8, 0u8, 208u8, 0u8, 0u8, 1u8, 48u8, 79u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 8u8, 70u8, 77u8, 67u8, 95u8, 73u8, 78u8, 70u8, 79u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &FmcAliasCertTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &FmcAliasCertTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 767usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::< { Self::TCB_INFO_DEVICE_INFO_HASH_OFFSET }, { Self::TCB_INFO_DEVICE_INFO_HASH_LEN }, >(&mut self.tbs, params.tcb_info_device_info_hash); apply_slice::<{ Self::TCB_INFO_FMC_TCI_OFFSET }, { Self::TCB_INFO_FMC_TCI_LEN }>( &mut self.tbs, params.tcb_info_fmc_tci, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); apply_slice::<{ Self::TCB_INFO_FLAGS_OFFSET }, { Self::TCB_INFO_FLAGS_LEN }>( &mut self.tbs, params.tcb_info_flags, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_OFFSET }, { Self::TCB_INFO_FW_SVN_LEN }>( &mut self.tbs, params.tcb_info_fw_svn, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_FUSES_OFFSET }, { Self::TCB_INFO_FW_SVN_FUSES_LEN }>( &mut self.tbs, params.tcb_info_fw_svn_fuses, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs
x509/build/ocp_lock_ml_kem_cert_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct OcpLockMlKemCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 1568usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl OcpLockMlKemCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 1568usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct OcpLockMlKemCertTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl OcpLockMlKemCertTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 344usize; const SUBJECT_SN_OFFSET: usize = 258usize; const ISSUER_SN_OFFSET: usize = 97usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 1990usize; const AUTHORITY_KEY_ID_OFFSET: usize = 2023usize; const NOT_BEFORE_OFFSET: usize = 165usize; const NOT_AFTER_OFFSET: usize = 182usize; const PUBLIC_KEY_LEN: usize = 1568usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 2043usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 7u8, 247u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 123u8, 49u8, 46u8, 48u8, 44u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 37u8, 79u8, 67u8, 80u8, 32u8, 76u8, 79u8, 67u8, 75u8, 32u8, 72u8, 80u8, 75u8, 69u8, 32u8, 69u8, 110u8, 100u8, 111u8, 114u8, 115u8, 101u8, 109u8, 101u8, 110u8, 116u8, 32u8, 77u8, 76u8, 45u8, 75u8, 69u8, 77u8, 32u8, 49u8, 48u8, 50u8, 52u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 6u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 4u8, 3u8, 3u8, 130u8, 6u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 128u8, 48u8, 126u8, 48u8, 15u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 5u8, 48u8, 3u8, 2u8, 1u8, 0u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 5u8, 32u8, 48u8, 27u8, 6u8, 6u8, 103u8, 129u8, 5u8, 21u8, 1u8, 1u8, 4u8, 17u8, 48u8, 15u8, 48u8, 3u8, 2u8, 1u8, 66u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &OcpLockMlKemCertTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &OcpLockMlKemCertTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 2043usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/csr.rs
x509/build/csr.rs
/*++ Licensed under the Apache-2.0 license. File Name: csr.rs Abstract: File contains generation of X509 Certificate Signing Request (CSR) To Be Signed (TBS) template that can be substituted at firmware runtime. --*/ use crate::tbs::{get_tbs, init_param, sanitize, TbsParam, TbsTemplate}; use crate::x509::{self, AsymKey, FwidParam, KeyUsage, SigningAlgorithm}; use openssl::stack::Stack; use openssl::x509::{X509Extension, X509NameBuilder, X509ReqBuilder}; /// CSR Template Parameter struct CsrTemplateParam { tbs_param: TbsParam, needle: Vec<u8>, } /// CSR Template Builder pub struct CsrTemplateBuilder<Algo: SigningAlgorithm> { algo: Algo, builder: X509ReqBuilder, exts: Stack<X509Extension>, params: Vec<CsrTemplateParam>, } impl<Algo: SigningAlgorithm> CsrTemplateBuilder<Algo> { // Create an instance of `CertificateTemplateBuilder` pub fn new() -> Self { Self { algo: Algo::default(), builder: X509ReqBuilder::new().unwrap(), exts: Stack::new().unwrap(), params: vec![], } } /// Add X509 Basic Constraints Extension /// /// # Arguments /// /// * `ca` - Flag indicating if the certificate is a Certificate Authority /// * `path_len` - Certificate path length pub fn add_basic_constraints_ext(mut self, ca: bool, path_len: u32) -> Self { self.exts .push(x509::make_basic_constraints_ext(ca, path_len)) .unwrap(); self } /// Add X509 Key Usage Extension /// /// # Arguments /// /// * `usage` - Key Usage pub fn add_key_usage_ext(mut self, usage: KeyUsage) -> Self { self.exts.push(x509::make_key_usage_ext(usage)).unwrap(); self } /// Add TCG UEID extension /// /// # Arguments /// /// * `ueid` - Unique Endpoint Identifier pub fn add_ueid_ext(mut self, ueid: &[u8]) -> Self { self.exts.push(x509::make_tcg_ueid_ext(ueid)).unwrap(); let param = CsrTemplateParam { tbs_param: TbsParam::new("UEID", 0, ueid.len()), needle: ueid.to_vec(), }; self.params.push(param); self } pub fn add_fmc_dice_tcb_info_ext( mut self, device_fwids: &[FwidParam], fmc_fwids: &[FwidParam], ) -> Self { // This method of finding the offsets is fragile. Especially for the 1 byte values. // These may need to be updated to stay unique when the cert template is updated. let flags: u32 = 0xC0C1C2C3; let svn: u8 = 0xC4; let svn_fuses: u8 = 0xC6; self.exts .push(x509::make_fmc_dice_tcb_info_ext( flags, svn, svn_fuses, device_fwids, fmc_fwids, )) .unwrap(); self.params.push(CsrTemplateParam { tbs_param: TbsParam::new("tcb_info_flags", 0, std::mem::size_of_val(&flags)), needle: flags.to_be_bytes().to_vec(), }); self.params.push(CsrTemplateParam { tbs_param: TbsParam::new("tcb_info_fmc_svn", 0, std::mem::size_of_val(&svn)), needle: svn.to_be_bytes().to_vec(), }); self.params.push(CsrTemplateParam { tbs_param: TbsParam::new( "tcb_info_fmc_svn_fuses", 0, std::mem::size_of_val(&svn_fuses), ), needle: svn_fuses.to_be_bytes().to_vec(), }); for fwid in device_fwids.iter().chain(fmc_fwids.iter()) { self.params.push(CsrTemplateParam { tbs_param: TbsParam::new(fwid.name, 0, fwid.fwid.digest.len()), needle: fwid.fwid.digest.to_vec(), }); } self } /// Generate To Be Signed (TBS) Template pub fn tbs_template(mut self, subject_cn: &str) -> TbsTemplate { // Generate key pair let key = self.algo.gen_key(); // Set Version self.builder.set_version(0).unwrap(); // Set Public Key self.builder.set_pubkey(key.priv_key()).unwrap(); let param = CsrTemplateParam { tbs_param: TbsParam::new("PUBLIC_KEY", 0, key.pub_key().len()), needle: key.pub_key().to_vec(), }; self.params.push(param); // Set the subject name let mut subject_name = X509NameBuilder::new().unwrap(); subject_name.append_entry_by_text("CN", subject_cn).unwrap(); subject_name .append_entry_by_text("serialNumber", &key.hex_str()) .unwrap(); let subject_name = subject_name.build(); self.builder.set_subject_name(&subject_name).unwrap(); let param = CsrTemplateParam { tbs_param: TbsParam::new("SUBJECT_SN", 0, key.hex_str().len()), needle: key.hex_str().into_bytes(), }; self.params.push(param); // Add the requested extensions self.builder.add_extensions(&self.exts).unwrap(); // Sign the CSR self.builder .sign(key.priv_key(), self.algo.digest()) .unwrap(); // Generate the CSR let csr = self.builder.build(); // Serialize the CSR to DER let der = csr.to_der().unwrap(); // Retrieve the To be signed portion from the CSR let mut tbs = get_tbs(der); // Sort the params largest to smallest to decrease the risk of duplicate "needles" in larger fields before being sanitized self.params .sort_by_key(|p| std::cmp::Reverse(p.tbs_param.len)); // Calculate the offset of parameters and sanitize the TBS section let params = self .params .iter() .map(|p| sanitize(init_param(&p.needle, &tbs, p.tbs_param), &mut tbs)) .collect(); // Create the template TbsTemplate::new(tbs, params) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs
x509/build/ocp_lock_ecdh_384_cert_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct OcpLockEcdh384CertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl OcpLockEcdh384CertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct OcpLockEcdh384CertTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl OcpLockEcdh384CertTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 344usize; const SUBJECT_SN_OFFSET: usize = 257usize; const ISSUER_SN_OFFSET: usize = 97usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 519usize; const AUTHORITY_KEY_ID_OFFSET: usize = 552usize; const NOT_BEFORE_OFFSET: usize = 165usize; const NOT_AFTER_OFFSET: usize = 182usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 572usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 56u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 48u8, 115u8, 49u8, 38u8, 48u8, 36u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 29u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 82u8, 116u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 122u8, 49u8, 45u8, 48u8, 43u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 36u8, 79u8, 67u8, 80u8, 32u8, 76u8, 79u8, 67u8, 75u8, 32u8, 72u8, 80u8, 75u8, 69u8, 32u8, 69u8, 110u8, 100u8, 111u8, 114u8, 115u8, 101u8, 109u8, 101u8, 110u8, 116u8, 32u8, 69u8, 67u8, 68u8, 72u8, 32u8, 80u8, 45u8, 51u8, 56u8, 52u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 128u8, 48u8, 126u8, 48u8, 15u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 5u8, 48u8, 3u8, 2u8, 1u8, 0u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 5u8, 32u8, 48u8, 27u8, 6u8, 6u8, 103u8, 129u8, 5u8, 21u8, 1u8, 1u8, 4u8, 17u8, 48u8, 15u8, 48u8, 3u8, 2u8, 1u8, 17u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 3u8, 2u8, 1u8, 2u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &OcpLockEcdh384CertTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &OcpLockEcdh384CertTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 572usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/cert.rs
x509/build/cert.rs
/*++ Licensed under the Apache-2.0 license. File Name: cert.rs Abstract: File contains generation of X509 Certificate To Be Singed (TBS) template that can be substituted at firmware runtime. --*/ use crate::tbs::{get_tbs, init_param, sanitize, TbsParam, TbsTemplate}; use crate::x509::{self, AsymKey, FwidParam, KeyUsage, SigningAlgorithm}; use openssl::asn1::Asn1Time; use openssl::bn::BigNum; use openssl::stack::Stack; use openssl::x509::{X509Builder, X509Extension, X509NameBuilder}; /// Certificate Template Param struct CertTemplateParam { tbs_param: TbsParam, needle: Vec<u8>, } /// Certificate Template Builder pub struct CertTemplateBuilder<AlgoIssuer: SigningAlgorithm, AlgoSubject: SigningAlgorithm> { issuer: AlgoIssuer, subject: AlgoSubject, builder: X509Builder, exts: Stack<X509Extension>, params: Vec<CertTemplateParam>, } impl<AlgoIssuer: SigningAlgorithm, AlgoSubject: SigningAlgorithm> CertTemplateBuilder<AlgoIssuer, AlgoSubject> { // Create an instance of `CertificateTemplateBuilder` pub fn new() -> Self { Self { issuer: AlgoIssuer::default(), subject: AlgoSubject::default(), builder: X509Builder::new().unwrap(), exts: Stack::new().unwrap(), params: vec![], } } /// Add X509 Basic Constraints Extension /// /// # Arguments /// /// * `ca` - Flag indicating if the certificate is a Certificate Authority /// * `path_len` - Certificate path length pub fn add_basic_constraints_ext(mut self, ca: bool, path_len: u32) -> Self { self.exts .push(x509::make_basic_constraints_ext(ca, path_len)) .unwrap(); self } /// Add X509 Key Usage Extension /// /// # Arguments /// /// * `usage` - Key Usage pub fn add_key_usage_ext(mut self, usage: KeyUsage) -> Self { self.exts.push(x509::make_key_usage_ext(usage)).unwrap(); self } /// Add TCG UEID extension /// /// # Arguments /// /// * `ueid` - Unique Endpoint Identifier pub fn add_ueid_ext(mut self, ueid: &[u8]) -> Self { self.exts.push(x509::make_tcg_ueid_ext(ueid)).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("UEID", 0, ueid.len()), needle: ueid.to_vec(), }; self.params.push(param); self } pub fn add_fmc_dice_tcb_info_ext( mut self, device_fwids: &[FwidParam], fmc_fwids: &[FwidParam], ) -> Self { // This method of finding the offsets is fragile. Especially for the 1 byte values. // These may need to be updated to stay unique when the cert template is updated. let flags: u32 = 0xC0C1C2C3; let svn: u8 = 0xC4; let svn_fuses: u8 = 0xC6; self.exts .push(x509::make_fmc_dice_tcb_info_ext( flags, svn, svn_fuses, device_fwids, fmc_fwids, )) .unwrap(); self.params.push(CertTemplateParam { tbs_param: TbsParam::new("tcb_info_flags", 0, std::mem::size_of_val(&flags)), needle: flags.to_be_bytes().to_vec(), }); self.params.push(CertTemplateParam { tbs_param: TbsParam::new("tcb_info_fw_svn", 0, std::mem::size_of_val(&svn)), needle: svn.to_be_bytes().to_vec(), }); self.params.push(CertTemplateParam { tbs_param: TbsParam::new( "tcb_info_fw_svn_fuses", 0, std::mem::size_of_val(&svn_fuses), ), needle: svn_fuses.to_be_bytes().to_vec(), }); for fwid in device_fwids.iter().chain(fmc_fwids.iter()) { self.params.push(CertTemplateParam { tbs_param: TbsParam::new(fwid.name, 0, fwid.fwid.digest.len()), needle: fwid.fwid.digest.to_vec(), }); } self } pub fn add_rt_dice_tcb_info_ext(mut self, fwids: &[FwidParam]) -> Self { let svn: u8 = 0xC1; self.exts .push(x509::make_rt_dice_tcb_info_ext(svn, fwids)) .unwrap(); self.params.push(CertTemplateParam { tbs_param: TbsParam::new("tcb_info_fw_svn", 0, std::mem::size_of_val(&svn)), needle: svn.to_be_bytes().to_vec(), }); for fwid in fwids.iter() { self.params.push(CertTemplateParam { tbs_param: TbsParam::new(fwid.name, 0, fwid.fwid.digest.len()), needle: fwid.fwid.digest.to_vec(), }); } self } /// Add Subject Key Id Extension /// /// # Arguments /// /// * `key_id` - Key Id fn add_subj_key_id_ext(&mut self, key_id: &[u8]) { self.exts .push(x509::make_subj_key_id_ext( &self.builder.x509v3_context(None, None), )) .unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("SUBJECT_KEY_ID", 0, key_id.len()), needle: key_id.to_vec(), }; self.params.push(param); } /// Add Authority Key Id Extension /// /// # Arguments /// /// * `key_id` - Key Id fn add_auth_key_id_ext(&mut self, key_id: &[u8]) { self.exts.push(x509::make_auth_key_id_ext(key_id)).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("AUTHORITY_KEY_ID", 0, key_id.len()), needle: key_id.to_vec(), }; self.params.push(param); } pub fn add_hpke_identifiers_ext(mut self, identifier: &crate::x509::HPKEIdentifiers) -> Self { self.exts .push(x509::make_hpke_identifier_ext(identifier)) .unwrap(); self } /// Generate To Be Signed (TBS) Template pub fn tbs_template(mut self, subject_cn: &str, issuer_cn: &str) -> TbsTemplate { // Generate key pair let subject_key = self.subject.gen_key(); let issuer_key = self.issuer.gen_key(); // Set Version self.builder.set_version(2).unwrap(); // Set the valid from time let not_before = "20230101000000Z"; let valid_from = Asn1Time::from_str(not_before).unwrap(); self.builder.set_not_before(&valid_from).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("NOT_BEFORE", 0, not_before.len()), needle: not_before.as_bytes().to_vec(), }; self.params.push(param); // Set the valid to time let not_after = "99991231235959Z"; let valid_to = Asn1Time::from_str(not_after).unwrap(); self.builder.set_not_after(&valid_to).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("NOT_AFTER", 0, not_after.len()), needle: not_after.as_bytes().to_vec(), }; self.params.push(param); // Set the serial number let serial_number_bytes = [0x7Fu8; 20]; let serial_number = BigNum::from_slice(&serial_number_bytes).unwrap(); let serial_number = serial_number.to_asn1_integer().unwrap(); self.builder.set_serial_number(&serial_number).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("SERIAL_NUMBER", 0, serial_number_bytes.len()), needle: serial_number_bytes.to_vec(), }; self.params.push(param); // Set Subject Public Key self.builder.set_pubkey(subject_key.priv_key()).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("PUBLIC_KEY", 0, subject_key.pub_key().len()), needle: subject_key.pub_key().to_vec(), }; self.params.push(param); // Set the subject name let mut subject_name = X509NameBuilder::new().unwrap(); subject_name.append_entry_by_text("CN", subject_cn).unwrap(); subject_name .append_entry_by_text("serialNumber", &subject_key.hex_str()) .unwrap(); let subject_name = subject_name.build(); self.builder.set_subject_name(&subject_name).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("SUBJECT_SN", 0, subject_key.hex_str().len()), needle: subject_key.hex_str().into_bytes(), }; self.params.push(param); // Set the issuer name let mut issuer_name = X509NameBuilder::new().unwrap(); issuer_name.append_entry_by_text("CN", issuer_cn).unwrap(); issuer_name .append_entry_by_text("serialNumber", &issuer_key.hex_str()) .unwrap(); let issuer_name = issuer_name.build(); self.builder.set_issuer_name(&issuer_name).unwrap(); let param = CertTemplateParam { tbs_param: TbsParam::new("ISSUER_SN", 0, issuer_key.hex_str().len()), needle: issuer_key.hex_str().into_bytes(), }; self.params.push(param); // Add Subject Key Identifier self.add_subj_key_id_ext(&subject_key.sha1()); // Add Authority Key Identifier self.add_auth_key_id_ext(&issuer_key.sha1()); // Add the requested extensions for ext in self.exts { self.builder.append_extension(ext).unwrap(); } // Sign the Certificate self.builder .sign(issuer_key.priv_key(), self.issuer.digest()) .unwrap(); // Generate the Certificate let cert = self.builder.build(); // Serialize the Certificate to DER let der = cert.to_der().unwrap(); // Retrieve the To be signed portion from the Certificate let mut tbs = get_tbs(der); // Match long params first to ensure a subset is not sanitized by a short param. self.params .sort_by(|a, b| a.needle.len().cmp(&b.needle.len()).reverse()); // Sort the params largest to smallest to decrease the risk of duplicate "needles" in larger fields before being sanitized self.params .sort_by_key(|p| std::cmp::Reverse(p.tbs_param.len)); // Calculate the offset of parameters and sanitize the TBS section let params = self .params .iter() .map(|p| sanitize(init_param(&p.needle, &tbs, p.tbs_param), &mut tbs)) .collect(); // Create the template TbsTemplate::new(tbs, params) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/local_dev_id_cert_tbs_ecc_384.rs
x509/build/local_dev_id_cert_tbs_ecc_384.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct LocalDevIdCertTbsEcc384Params<'a> { pub public_key: &'a [u8; 97usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], } impl LocalDevIdCertTbsEcc384Params<'_> { pub const PUBLIC_KEY_LEN: usize = 97usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; } pub struct LocalDevIdCertTbsEcc384 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl LocalDevIdCertTbsEcc384 { const PUBLIC_KEY_OFFSET: usize = 330usize; const SUBJECT_SN_OFFSET: usize = 243usize; const ISSUER_SN_OFFSET: usize = 93usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 513usize; const AUTHORITY_KEY_ID_OFFSET: usize = 546usize; const UEID_OFFSET: usize = 485usize; const NOT_BEFORE_OFFSET: usize = 161usize; const NOT_AFTER_OFFSET: usize = 178usize; const PUBLIC_KEY_LEN: usize = 97usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; pub const TBS_TEMPLATE_LEN: usize = 566usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 2u8, 50u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 10u8, 6u8, 8u8, 42u8, 134u8, 72u8, 206u8, 61u8, 4u8, 3u8, 3u8, 48u8, 112u8, 49u8, 35u8, 48u8, 33u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 26u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 73u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 112u8, 49u8, 35u8, 48u8, 33u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 26u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 69u8, 99u8, 99u8, 51u8, 56u8, 52u8, 32u8, 76u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 118u8, 48u8, 16u8, 6u8, 7u8, 42u8, 134u8, 72u8, 206u8, 61u8, 2u8, 1u8, 6u8, 5u8, 43u8, 129u8, 4u8, 0u8, 34u8, 3u8, 98u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 129u8, 136u8, 48u8, 129u8, 133u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 6u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &LocalDevIdCertTbsEcc384Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &LocalDevIdCertTbsEcc384Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 566usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/x509.rs
x509/build/x509.rs
/*++ Licensed under the Apache-2.0 license. File Name: x509.rs Abstract: File contains helper functions for cryptography and X509 object manipulation --*/ use openssl::asn1::{Asn1Object, Asn1OctetString}; use openssl::bn::BigNumContext; use openssl::ec::EcGroup; use openssl::ec::EcKey; use openssl::ec::PointConversionForm; use openssl::hash::MessageDigest; use openssl::nid::Nid; use openssl::pkey::PKey; use openssl::pkey::{Private, Public}; use openssl::pkey_ml_dsa::{PKeyMlDsaBuilder, PKeyMlDsaParams, Variant as MlDsaVariant}; use openssl::pkey_ml_kem::{PKeyMlKemBuilder, PKeyMlKemParams, Variant as MlKemVariant}; use openssl::sha::Sha1; use openssl::sha::Sha256; use openssl::x509::extension::BasicConstraints; use openssl::x509::extension::KeyUsage as Usage; use openssl::x509::extension::SubjectKeyIdentifier; use openssl::x509::X509Extension; use openssl::x509::X509v3Context; use rand::Rng; const FLAG_BIT_NOT_CONFIGURED: u32 = 1 << 0; const FLAG_BIT_NOT_SECURE: u32 = 1 << 1; const FLAG_BIT_DEBUG: u32 = 1 << 3; const FLAG_BIT_FIXED_WIDTH: u32 = 1 << 31; const FLAG_MASK: u32 = FLAG_BIT_NOT_CONFIGURED | FLAG_BIT_NOT_SECURE | FLAG_BIT_DEBUG | FLAG_BIT_FIXED_WIDTH; const AUTH_KEY_ID_OID: &str = "2.5.29.35"; const TCG_UEID_OID: &str = "2.23.133.5.4.4"; const TCG_TCB_INFO_OID: &str = "2.23.133.5.4.1"; const TCG_MULTI_TCB_INFO_OID: &str = "2.23.133.5.4.5"; #[derive(asn1::Asn1Write)] struct TcbInfo<'a> { #[implicit(0)] vendor: Option<asn1::Utf8String<'a>>, #[implicit(1)] model: Option<asn1::Utf8String<'a>>, #[implicit(2)] version: Option<asn1::Utf8String<'a>>, #[implicit(3)] svn: Option<u32>, #[implicit(4)] layer: Option<u64>, #[implicit(5)] index: Option<u64>, #[implicit(6)] fwids: Option<asn1::SequenceOfWriter<'a, &'a Fwid<'a>>>, #[implicit(7)] flags: Option<asn1::BitString<'a>>, #[implicit(8)] vendor_info: Option<&'a [u8]>, #[implicit(9)] tcb_type: Option<&'a [u8]>, #[implicit(10)] flags_mask: Option<asn1::BitString<'a>>, } /// Asymmetric Key pub trait AsymKey: Default { /// Retrieve Private Key fn priv_key(&self) -> &PKey<Private>; /// Retrieve Public Key fn pub_key(&self) -> &[u8]; /// Retrieve SHA-256 digest of the public key fn sha256(&self) -> [u8; 32] { let mut sha = Sha256::new(); sha.update(self.pub_key()); sha.finish() } /// Retrieve SHA1 digest of the public key fn sha1(&self) -> [u8; 20] { let mut sha = Sha1::new(); sha.update(self.pub_key()); sha.finish() } /// Retrieve the hex string of SHA-256 Digest of the public key fn hex_str(&self) -> String { hex::encode(self.sha256()).to_uppercase() } } /// Digest pub trait Digest { /// Digest Algorithm fn algo() -> MessageDigest; } /// Signing Algorithm pub trait SigningAlgorithm: Default { type AsymKey: AsymKey; type Digest: Digest; /// Generate Asymmetric Key Pair fn gen_key(&self) -> Self::AsymKey; /// Retrieve digest algorithm fn digest(&self) -> MessageDigest { Self::Digest::algo() } } /// ECC-348 Asymmetric Key Pair pub struct Ecc384AsymKey { priv_key: PKey<Private>, pub_key: Vec<u8>, } impl AsymKey for Ecc384AsymKey { /// Retrieve Private Key fn priv_key(&self) -> &PKey<Private> { &self.priv_key } /// Retrieve Public Key fn pub_key(&self) -> &[u8] { &self.pub_key } } impl Default for Ecc384AsymKey { /// Returns the "default value" for a type. fn default() -> Self { let ecc_group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); let priv_key = EcKey::generate(&ecc_group).unwrap(); let mut bn_ctx = BigNumContext::new().unwrap(); let pub_key = priv_key .public_key() .to_bytes(&ecc_group, PointConversionForm::UNCOMPRESSED, &mut bn_ctx) .unwrap(); Self { priv_key: PKey::from_ec_key(priv_key).unwrap(), pub_key, } } } /// SHA2-384 Algorithm pub struct Sha384 {} impl Digest for Sha384 { /// Retrieve the algorithm fn algo() -> MessageDigest { MessageDigest::sha384() } } #[derive(Default)] pub struct EcdsaSha384Algo {} impl SigningAlgorithm for EcdsaSha384Algo { type AsymKey = Ecc384AsymKey; type Digest = Sha384; fn gen_key(&self) -> Self::AsymKey { Self::AsymKey::default() } } /// ML-DSA87 Asymmetric Key Pair pub struct MlDsa87AsymKey { priv_key: PKey<Private>, pub_key: Vec<u8>, } impl AsymKey for MlDsa87AsymKey { /// Retrieve Private Key fn priv_key(&self) -> &PKey<Private> { &self.priv_key } /// Retrieve Public Key fn pub_key(&self) -> &[u8] { &self.pub_key } } impl Default for MlDsa87AsymKey { /// Returns the "default value" for a type. fn default() -> Self { let mut random_bytes: [u8; 32] = [0; 32]; let mut rng = rand::thread_rng(); rng.fill(&mut random_bytes); let pk_builder = PKeyMlDsaBuilder::<Private>::from_seed(MlDsaVariant::MlDsa87, &random_bytes).unwrap(); let private_key = pk_builder.build().unwrap(); let public_params = PKeyMlDsaParams::<Public>::from_pkey(&private_key).unwrap(); let public_key = public_params.public_key().unwrap(); Self { priv_key: private_key, pub_key: public_key.to_vec(), } } } /// Nothing as MLDSA has it's internal hashing scheme pub struct Noop {} impl Digest for Noop { /// Retrieve the algorithm fn algo() -> MessageDigest { MessageDigest::null() } } #[derive(Default)] pub struct MlDsa87Algo {} impl SigningAlgorithm for MlDsa87Algo { type AsymKey = MlDsa87AsymKey; type Digest = Noop; fn gen_key(&self) -> Self::AsymKey { Self::AsymKey::default() } } pub struct MlKem1024Key { priv_key: PKey<Private>, pub_key: Vec<u8>, } #[derive(Default)] pub struct MlKem1024Algo {} impl SigningAlgorithm for MlKem1024Algo { type AsymKey = MlKem1024Key; type Digest = Noop; fn gen_key(&self) -> Self::AsymKey { Self::AsymKey::default() } } impl AsymKey for MlKem1024Key { /// Retrieve Public Key fn pub_key(&self) -> &[u8] { &self.pub_key } /// Retrieve Private Key fn priv_key(&self) -> &PKey<Private> { &self.priv_key } } impl Default for MlKem1024Key { /// Returns the "default value" for a type. fn default() -> Self { let mut random_bytes: [u8; 64] = [0; 64]; let mut rng = rand::thread_rng(); rng.fill(&mut random_bytes); let pk_builder = PKeyMlKemBuilder::<Private>::from_seed(MlKemVariant::MlKem1024, &random_bytes).unwrap(); let private_key = pk_builder.build().unwrap(); let public_params = PKeyMlKemParams::<Public>::from_pkey(&private_key).unwrap(); let public_key = public_params.public_key().unwrap(); Self { priv_key: private_key, pub_key: public_key.to_vec(), } } } bitfield::bitfield! { #[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] /// Key Usage pub struct KeyUsage(u16); pub digital_signature, set_digital_signature: 0; pub non_repudiation, set_non_repudiation: 1; pub key_encipherment, set_key_encipherment: 2; pub data_encipherment, set_data_encipherment: 3; pub key_agreement, set_key_agreement: 4; pub key_cert_sign, set_key_cert_sign: 5; pub crl_sign, set_crl_sign: 6; pub encipher_only, set_encipher_only: 7; pub decipher_only, set_decipher_only: 8; } impl From<KeyUsage> for Usage { /// Converts to this type from the input type. fn from(value: KeyUsage) -> Self { let mut usage = Usage::new(); if value.digital_signature() { usage.digital_signature(); } if value.non_repudiation() { usage.non_repudiation(); } if value.key_encipherment() { usage.key_encipherment(); } if value.data_encipherment() { usage.data_encipherment(); } if value.key_agreement() { usage.key_agreement(); } if value.key_cert_sign() { usage.key_cert_sign(); } if value.crl_sign() { usage.crl_sign(); } if value.encipher_only() { usage.encipher_only(); } if value.decipher_only() { usage.decipher_only(); } usage } } /// Make X509 Basic Constraints Extension pub fn make_basic_constraints_ext(ca: bool, path_len: u32) -> X509Extension { let mut ext = BasicConstraints::new(); if ca { ext.ca(); } ext.critical().pathlen(path_len).build().unwrap() } /// Make Key Usage Extension pub fn make_key_usage_ext(key_usage: KeyUsage) -> X509Extension { let mut usage: Usage = key_usage.into(); usage.critical().build().unwrap() } /// Make TCG UEID extension pub fn make_tcg_ueid_ext(ueid: &[u8]) -> X509Extension { #[derive(asn1::Asn1Read, asn1::Asn1Write)] struct TcgUeid<'a> { ueid: &'a [u8], } let tcg_ueid = TcgUeid { ueid }; let der = asn1::write_single(&tcg_ueid).unwrap(); let der = Asn1OctetString::new_from_bytes(&der).unwrap(); let oid = Asn1Object::from_str(TCG_UEID_OID).unwrap(); X509Extension::new_from_der(&oid, false, &der).unwrap() } /// Make Subject Key ID extension pub fn make_subj_key_id_ext(ctx: &X509v3Context) -> X509Extension { SubjectKeyIdentifier::new().build(ctx).unwrap() } /// Make Authority Key ID extension pub fn make_auth_key_id_ext(key_id: &[u8]) -> X509Extension { #[derive(asn1::Asn1Read, asn1::Asn1Write)] struct AuthKeyId<'a> { #[implicit(0)] key_id: Option<&'a [u8]>, } let auth_key_id = AuthKeyId { key_id: Some(key_id), }; let der = asn1::write_single(&auth_key_id).unwrap(); let der = Asn1OctetString::new_from_bytes(&der).unwrap(); let oid = Asn1Object::from_str(AUTH_KEY_ID_OID).unwrap(); X509Extension::new_from_der(&oid, false, &der).unwrap() } #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct Fwid<'a> { pub(crate) hash_alg: asn1::ObjectIdentifier, pub(crate) digest: &'a [u8], } pub struct FwidParam<'a> { pub(crate) name: &'static str, pub(crate) fwid: Fwid<'a>, } fn fixed_width_svn(svn: u8) -> u16 { (1_u16 << 8) | svn as u16 } // Make a tcg-dice-MultiTcbInfo extension pub fn make_fmc_dice_tcb_info_ext( flags: u32, svn: u8, svn_fuses: u8, device_fwids: &[FwidParam], fmc_fwids: &[FwidParam], ) -> X509Extension { let wide_svn = fixed_width_svn(svn); let wide_svn_fuses = fixed_width_svn(svn_fuses); let be_flags = flags.to_be_bytes(); let be_flags_mask = FLAG_MASK.reverse_bits().to_be_bytes(); let device_asn1_fwids: Vec<&Fwid> = device_fwids.iter().map(|f| &f.fwid).collect(); let device_info = TcbInfo { vendor: None, model: None, version: None, svn: Some(wide_svn_fuses.into()), layer: None, index: None, fwids: Some(asn1::SequenceOfWriter::new(&device_asn1_fwids)), flags: asn1::BitString::new(be_flags.as_ref(), 0), vendor_info: None, tcb_type: Some(b"DEVICE_INFO"), flags_mask: asn1::BitString::new(be_flags_mask.as_ref(), 0), }; let fmc_asn1_fwids: Vec<&Fwid> = fmc_fwids.iter().map(|f| &f.fwid).collect(); let fmc_info = TcbInfo { vendor: None, model: None, version: None, svn: Some(wide_svn.into()), layer: None, index: None, fwids: Some(asn1::SequenceOfWriter::new(&fmc_asn1_fwids)), flags: None, vendor_info: None, tcb_type: Some(b"FMC_INFO"), flags_mask: None, }; let tcb_infos = asn1::SequenceOfWriter::new(vec![&device_info, &fmc_info]); let der = asn1::write_single(&tcb_infos).unwrap(); let der = Asn1OctetString::new_from_bytes(&der).unwrap(); let oid = Asn1Object::from_str(TCG_MULTI_TCB_INFO_OID).unwrap(); X509Extension::new_from_der(&oid, false, &der).unwrap() } // Make a tcg-dice-TcbInfo extension pub fn make_rt_dice_tcb_info_ext(svn: u8, fwids: &[FwidParam]) -> X509Extension { let wide_svn = fixed_width_svn(svn); let asn1_fwids: Vec<&Fwid> = fwids.iter().map(|f| &f.fwid).collect(); let rt_info = TcbInfo { vendor: None, model: None, version: None, svn: Some(wide_svn.into()), layer: None, index: None, fwids: Some(asn1::SequenceOfWriter::new(&asn1_fwids)), flags: None, vendor_info: None, tcb_type: Some(b"RT_INFO"), flags_mask: None, }; let der = asn1::write_single(&rt_info).unwrap(); let der = Asn1OctetString::new_from_bytes(&der).unwrap(); let oid = Asn1Object::from_str(TCG_TCB_INFO_OID).unwrap(); X509Extension::new_from_der(&oid, false, &der).unwrap() } #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct KemId(u16); #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct KdfId(u16); #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct AeadId(u16); /// MEK MPA Spec v1 /// /// Section 4.2.2.1.3.1 #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct HPKEIdentifiers { kem_id: KemId, kdf_id: KdfId, aead_id: AeadId, } impl HPKEIdentifiers { pub fn new(kem_id: KemId, kdf_id: KdfId, aead_id: AeadId) -> Self { Self { kem_id, kdf_id, aead_id, } } } impl HPKEIdentifiers { // TCG_STORAGE_HPKE_ pub const OID: &str = "2.23.133.21.1.1"; /// KEM id's pub const ML_KEM_1024_IANA_CODE_POINT: KemId = KemId(0x0042); // TODO(clundin): This will be used in a follow up PR. #[allow(dead_code)] pub const ML_KEM_EC_P384_IANA_CODE_POINT: KemId = KemId(0x0052); pub const ECDH_P384_IANA_CODE_POINT: KemId = KemId(0x0011); /// KDF id's pub const HKDF_SHA384_IANA_CODE_POINT: KdfId = KdfId(0x0002); /// AEAD id's pub const AES_256_GCM_IANA_CODE_POINT: AeadId = AeadId(0x0002); } #[derive(asn1::Asn1Read, asn1::Asn1Write)] pub struct HPKEIdentifierExt<'a> { pub(crate) hpke_oid: asn1::ObjectIdentifier, pub(crate) critical: bool, pub(crate) extn_value: &'a [u8], } pub fn make_hpke_identifier_ext(identifiers: &HPKEIdentifiers) -> X509Extension { let der = asn1::write_single(&identifiers).unwrap(); let der = Asn1OctetString::new_from_bytes(&der).unwrap(); let oid = Asn1Object::from_str(HPKEIdentifiers::OID).unwrap(); X509Extension::new_from_der(&oid, false, &der).unwrap() }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/init_dev_id_csr_tbs_ml_dsa_87.rs
x509/build/init_dev_id_csr_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct InitDevIdCsrTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], pub ueid: &'a [u8; 17usize], } impl InitDevIdCsrTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const UEID_LEN: usize = 17usize; } pub struct InitDevIdCsrTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl InitDevIdCsrTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 144usize; const SUBJECT_SN_OFFSET: usize = 58usize; const UEID_OFFSET: usize = 2807usize; const PUBLIC_KEY_LEN: usize = 2592usize; const SUBJECT_SN_LEN: usize = 64usize; const UEID_LEN: usize = 17usize; pub const TBS_TEMPLATE_LEN: usize = 2824usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 11u8, 4u8, 2u8, 1u8, 0u8, 48u8, 113u8, 49u8, 36u8, 48u8, 34u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 27u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 73u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 10u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 3u8, 130u8, 10u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 160u8, 86u8, 48u8, 84u8, 6u8, 9u8, 42u8, 134u8, 72u8, 134u8, 247u8, 13u8, 1u8, 9u8, 14u8, 49u8, 71u8, 48u8, 69u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 7u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &InitDevIdCsrTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &InitDevIdCsrTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 2824usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/fmc_alias_cert_tbs_ml_dsa_87.rs
x509/build/fmc_alias_cert_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct FmcAliasCertTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], pub issuer_sn: &'a [u8; 64usize], pub tcb_info_device_info_hash: &'a [u8; 48usize], pub tcb_info_fmc_tci: &'a [u8; 48usize], pub serial_number: &'a [u8; 20usize], pub subject_key_id: &'a [u8; 20usize], pub authority_key_id: &'a [u8; 20usize], pub ueid: &'a [u8; 17usize], pub not_before: &'a [u8; 15usize], pub not_after: &'a [u8; 15usize], pub tcb_info_flags: &'a [u8; 4usize], pub tcb_info_fw_svn: &'a [u8; 1usize], pub tcb_info_fw_svn_fuses: &'a [u8; 1usize], } impl FmcAliasCertTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const ISSUER_SN_LEN: usize = 64usize; pub const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; pub const TCB_INFO_FMC_TCI_LEN: usize = 48usize; pub const SERIAL_NUMBER_LEN: usize = 20usize; pub const SUBJECT_KEY_ID_LEN: usize = 20usize; pub const AUTHORITY_KEY_ID_LEN: usize = 20usize; pub const UEID_LEN: usize = 17usize; pub const NOT_BEFORE_LEN: usize = 15usize; pub const NOT_AFTER_LEN: usize = 15usize; pub const TCB_INFO_FLAGS_LEN: usize = 4usize; pub const TCB_INFO_FW_SVN_LEN: usize = 1usize; pub const TCB_INFO_FW_SVN_FUSES_LEN: usize = 1usize; } pub struct FmcAliasCertTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl FmcAliasCertTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 335usize; const SUBJECT_SN_OFFSET: usize = 249usize; const ISSUER_SN_OFFSET: usize = 95usize; const TCB_INFO_DEVICE_INFO_HASH_OFFSET: usize = 3044usize; const TCB_INFO_FMC_TCI_OFFSET: usize = 3142usize; const SERIAL_NUMBER_OFFSET: usize = 11usize; const SUBJECT_KEY_ID_OFFSET: usize = 3211usize; const AUTHORITY_KEY_ID_OFFSET: usize = 3244usize; const UEID_OFFSET: usize = 2987usize; const NOT_BEFORE_OFFSET: usize = 163usize; const NOT_AFTER_OFFSET: usize = 180usize; const TCB_INFO_FLAGS_OFFSET: usize = 3095usize; const TCB_INFO_FW_SVN_OFFSET: usize = 3124usize; const TCB_INFO_FW_SVN_FUSES_OFFSET: usize = 3026usize; const PUBLIC_KEY_LEN: usize = 2592usize; const SUBJECT_SN_LEN: usize = 64usize; const ISSUER_SN_LEN: usize = 64usize; const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; const TCB_INFO_FMC_TCI_LEN: usize = 48usize; const SERIAL_NUMBER_LEN: usize = 20usize; const SUBJECT_KEY_ID_LEN: usize = 20usize; const AUTHORITY_KEY_ID_LEN: usize = 20usize; const UEID_LEN: usize = 17usize; const NOT_BEFORE_LEN: usize = 15usize; const NOT_AFTER_LEN: usize = 15usize; const TCB_INFO_FLAGS_LEN: usize = 4usize; const TCB_INFO_FW_SVN_LEN: usize = 1usize; const TCB_INFO_FW_SVN_FUSES_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 3264usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 12u8, 188u8, 160u8, 3u8, 2u8, 1u8, 2u8, 2u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 48u8, 113u8, 49u8, 36u8, 48u8, 34u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 27u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 76u8, 68u8, 101u8, 118u8, 73u8, 68u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 34u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 24u8, 15u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 116u8, 49u8, 39u8, 48u8, 37u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 30u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 10u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 3u8, 130u8, 10u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 163u8, 130u8, 1u8, 77u8, 48u8, 130u8, 1u8, 73u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 5u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 129u8, 193u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 5u8, 4u8, 129u8, 182u8, 48u8, 129u8, 179u8, 48u8, 96u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 135u8, 5u8, 0u8, 95u8, 95u8, 95u8, 95u8, 137u8, 11u8, 68u8, 69u8, 86u8, 73u8, 67u8, 69u8, 95u8, 73u8, 78u8, 70u8, 79u8, 138u8, 5u8, 0u8, 208u8, 0u8, 0u8, 1u8, 48u8, 79u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 8u8, 70u8, 77u8, 67u8, 95u8, 73u8, 78u8, 70u8, 79u8, 48u8, 29u8, 6u8, 3u8, 85u8, 29u8, 14u8, 4u8, 22u8, 4u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 31u8, 6u8, 3u8, 85u8, 29u8, 35u8, 4u8, 24u8, 48u8, 22u8, 128u8, 20u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, ]; pub fn new(params: &FmcAliasCertTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &FmcAliasCertTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 3264usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::<{ Self::ISSUER_SN_OFFSET }, { Self::ISSUER_SN_LEN }>( &mut self.tbs, params.issuer_sn, ); apply_slice::< { Self::TCB_INFO_DEVICE_INFO_HASH_OFFSET }, { Self::TCB_INFO_DEVICE_INFO_HASH_LEN }, >(&mut self.tbs, params.tcb_info_device_info_hash); apply_slice::<{ Self::TCB_INFO_FMC_TCI_OFFSET }, { Self::TCB_INFO_FMC_TCI_LEN }>( &mut self.tbs, params.tcb_info_fmc_tci, ); apply_slice::<{ Self::SERIAL_NUMBER_OFFSET }, { Self::SERIAL_NUMBER_LEN }>( &mut self.tbs, params.serial_number, ); apply_slice::<{ Self::SUBJECT_KEY_ID_OFFSET }, { Self::SUBJECT_KEY_ID_LEN }>( &mut self.tbs, params.subject_key_id, ); apply_slice::<{ Self::AUTHORITY_KEY_ID_OFFSET }, { Self::AUTHORITY_KEY_ID_LEN }>( &mut self.tbs, params.authority_key_id, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::NOT_BEFORE_OFFSET }, { Self::NOT_BEFORE_LEN }>( &mut self.tbs, params.not_before, ); apply_slice::<{ Self::NOT_AFTER_OFFSET }, { Self::NOT_AFTER_LEN }>( &mut self.tbs, params.not_after, ); apply_slice::<{ Self::TCB_INFO_FLAGS_OFFSET }, { Self::TCB_INFO_FLAGS_LEN }>( &mut self.tbs, params.tcb_info_flags, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_OFFSET }, { Self::TCB_INFO_FW_SVN_LEN }>( &mut self.tbs, params.tcb_info_fw_svn, ); apply_slice::<{ Self::TCB_INFO_FW_SVN_FUSES_OFFSET }, { Self::TCB_INFO_FW_SVN_FUSES_LEN }>( &mut self.tbs, params.tcb_info_fw_svn_fuses, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/x509/build/fmc_alias_tbs_ml_dsa_87.rs
x509/build/fmc_alias_tbs_ml_dsa_87.rs
#[doc = "++ Licensed under the Apache-2.0 license. Abstract: Regenerate the template by building caliptra-x509-build with the generate-templates flag. --"] #[allow(clippy::needless_lifetimes)] pub struct FmcAliasTbsMlDsa87Params<'a> { pub public_key: &'a [u8; 2592usize], pub subject_sn: &'a [u8; 64usize], pub tcb_info_device_info_hash: &'a [u8; 48usize], pub tcb_info_fmc_tci: &'a [u8; 48usize], pub ueid: &'a [u8; 17usize], pub tcb_info_flags: &'a [u8; 4usize], pub tcb_info_fmc_svn: &'a [u8; 1usize], pub tcb_info_fmc_svn_fuses: &'a [u8; 1usize], } impl FmcAliasTbsMlDsa87Params<'_> { pub const PUBLIC_KEY_LEN: usize = 2592usize; pub const SUBJECT_SN_LEN: usize = 64usize; pub const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; pub const TCB_INFO_FMC_TCI_LEN: usize = 48usize; pub const UEID_LEN: usize = 17usize; pub const TCB_INFO_FLAGS_LEN: usize = 4usize; pub const TCB_INFO_FMC_SVN_LEN: usize = 1usize; pub const TCB_INFO_FMC_SVN_FUSES_LEN: usize = 1usize; } pub struct FmcAliasTbsMlDsa87 { tbs: [u8; Self::TBS_TEMPLATE_LEN], } impl FmcAliasTbsMlDsa87 { const PUBLIC_KEY_OFFSET: usize = 147usize; const SUBJECT_SN_OFFSET: usize = 61usize; const TCB_INFO_DEVICE_INFO_HASH_OFFSET: usize = 2875usize; const TCB_INFO_FMC_TCI_OFFSET: usize = 2973usize; const UEID_OFFSET: usize = 2818usize; const TCB_INFO_FLAGS_OFFSET: usize = 2926usize; const TCB_INFO_FMC_SVN_OFFSET: usize = 2955usize; const TCB_INFO_FMC_SVN_FUSES_OFFSET: usize = 2857usize; const PUBLIC_KEY_LEN: usize = 2592usize; const SUBJECT_SN_LEN: usize = 64usize; const TCB_INFO_DEVICE_INFO_HASH_LEN: usize = 48usize; const TCB_INFO_FMC_TCI_LEN: usize = 48usize; const UEID_LEN: usize = 17usize; const TCB_INFO_FLAGS_LEN: usize = 4usize; const TCB_INFO_FMC_SVN_LEN: usize = 1usize; const TCB_INFO_FMC_SVN_FUSES_LEN: usize = 1usize; pub const TBS_TEMPLATE_LEN: usize = 3031usize; const TBS_TEMPLATE: [u8; Self::TBS_TEMPLATE_LEN] = [ 48u8, 130u8, 11u8, 211u8, 2u8, 1u8, 0u8, 48u8, 116u8, 49u8, 39u8, 48u8, 37u8, 6u8, 3u8, 85u8, 4u8, 3u8, 12u8, 30u8, 67u8, 97u8, 108u8, 105u8, 112u8, 116u8, 114u8, 97u8, 32u8, 50u8, 46u8, 49u8, 32u8, 77u8, 108u8, 68u8, 115u8, 97u8, 56u8, 55u8, 32u8, 70u8, 77u8, 67u8, 32u8, 65u8, 108u8, 105u8, 97u8, 115u8, 49u8, 73u8, 48u8, 71u8, 6u8, 3u8, 85u8, 4u8, 5u8, 19u8, 64u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 130u8, 10u8, 50u8, 48u8, 11u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 3u8, 19u8, 3u8, 130u8, 10u8, 33u8, 0u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 160u8, 130u8, 1u8, 32u8, 48u8, 130u8, 1u8, 28u8, 6u8, 9u8, 42u8, 134u8, 72u8, 134u8, 247u8, 13u8, 1u8, 9u8, 14u8, 49u8, 130u8, 1u8, 13u8, 48u8, 130u8, 1u8, 9u8, 48u8, 18u8, 6u8, 3u8, 85u8, 29u8, 19u8, 1u8, 1u8, 255u8, 4u8, 8u8, 48u8, 6u8, 1u8, 1u8, 255u8, 2u8, 1u8, 5u8, 48u8, 14u8, 6u8, 3u8, 85u8, 29u8, 15u8, 1u8, 1u8, 255u8, 4u8, 4u8, 3u8, 2u8, 2u8, 4u8, 48u8, 31u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 4u8, 4u8, 21u8, 48u8, 19u8, 4u8, 17u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 48u8, 129u8, 193u8, 6u8, 6u8, 103u8, 129u8, 5u8, 5u8, 4u8, 5u8, 4u8, 129u8, 182u8, 48u8, 129u8, 179u8, 48u8, 96u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 135u8, 5u8, 0u8, 95u8, 95u8, 95u8, 95u8, 137u8, 11u8, 68u8, 69u8, 86u8, 73u8, 67u8, 69u8, 95u8, 73u8, 78u8, 70u8, 79u8, 138u8, 5u8, 0u8, 208u8, 0u8, 0u8, 1u8, 48u8, 79u8, 131u8, 2u8, 1u8, 95u8, 166u8, 63u8, 48u8, 61u8, 6u8, 9u8, 96u8, 134u8, 72u8, 1u8, 101u8, 3u8, 4u8, 2u8, 2u8, 4u8, 48u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 95u8, 137u8, 8u8, 70u8, 77u8, 67u8, 95u8, 73u8, 78u8, 70u8, 79u8, ]; pub fn new(params: &FmcAliasTbsMlDsa87Params) -> Self { let mut template = Self { tbs: Self::TBS_TEMPLATE, }; template.apply(params); template } pub fn sign<Sig, Error>( &self, sign_fn: impl Fn(&[u8]) -> Result<Sig, Error>, ) -> Result<Sig, Error> { sign_fn(&self.tbs) } pub fn tbs(&self) -> &[u8] { &self.tbs } fn apply(&mut self, params: &FmcAliasTbsMlDsa87Params) { #[inline(always)] fn apply_slice<const OFFSET: usize, const LEN: usize>( buf: &mut [u8; 3031usize], val: &[u8; LEN], ) { buf[OFFSET..OFFSET + LEN].copy_from_slice(val); } apply_slice::<{ Self::PUBLIC_KEY_OFFSET }, { Self::PUBLIC_KEY_LEN }>( &mut self.tbs, params.public_key, ); apply_slice::<{ Self::SUBJECT_SN_OFFSET }, { Self::SUBJECT_SN_LEN }>( &mut self.tbs, params.subject_sn, ); apply_slice::< { Self::TCB_INFO_DEVICE_INFO_HASH_OFFSET }, { Self::TCB_INFO_DEVICE_INFO_HASH_LEN }, >(&mut self.tbs, params.tcb_info_device_info_hash); apply_slice::<{ Self::TCB_INFO_FMC_TCI_OFFSET }, { Self::TCB_INFO_FMC_TCI_LEN }>( &mut self.tbs, params.tcb_info_fmc_tci, ); apply_slice::<{ Self::UEID_OFFSET }, { Self::UEID_LEN }>(&mut self.tbs, params.ueid); apply_slice::<{ Self::TCB_INFO_FLAGS_OFFSET }, { Self::TCB_INFO_FLAGS_LEN }>( &mut self.tbs, params.tcb_info_flags, ); apply_slice::<{ Self::TCB_INFO_FMC_SVN_OFFSET }, { Self::TCB_INFO_FMC_SVN_LEN }>( &mut self.tbs, params.tcb_info_fmc_svn, ); apply_slice::<{ Self::TCB_INFO_FMC_SVN_FUSES_OFFSET }, { Self::TCB_INFO_FMC_SVN_FUSES_LEN }>( &mut self.tbs, params.tcb_info_fmc_svn_fuses, ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/tty.rs
ci-tools/fpga-boss/src/tty.rs
// Licensed under the Apache-2.0 license use std::{ io::{self, ErrorKind, Read}, mem::MaybeUninit, os::fd::AsRawFd, }; pub struct RawTerminal { old_termios: libc::termios, } impl RawTerminal { pub fn from_stdin() -> io::Result<Self> { let stdin = io::stdin().lock(); unsafe { let mut termios = MaybeUninit::<libc::termios>::uninit(); if libc::tcgetattr(stdin.as_raw_fd(), termios.as_mut_ptr()) != 0 { return Err(io::Error::last_os_error()); } let mut termios = termios.assume_init(); let old_termios = termios; termios.c_iflag &= !(libc::IGNBRK | libc::BRKINT | libc::PARMRK | libc::ISTRIP | libc::ICRNL | libc::INLCR | libc::IGNCR | libc::IXON); termios.c_oflag &= !libc::OPOST; // Do we want this? termios.c_oflag |= libc::ONLCR | libc::OPOST; termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::IEXTEN | libc::ISIG); termios.c_cflag &= !(libc::CSIZE | libc::PARENB); termios.c_cflag |= libc::CS8; termios.c_cc[libc::VMIN] = 1; termios.c_cc[libc::VTIME] = 0; if libc::tcsetattr(stdin.as_raw_fd(), libc::TCSANOW, &termios as *const _) != 0 { return Err(io::Error::last_os_error()); } Ok(RawTerminal { old_termios }) } } } impl Drop for RawTerminal { fn drop(&mut self) { unsafe { libc::tcsetattr( io::stdin().as_raw_fd(), libc::TCSANOW, &self.old_termios as *const _, ); } } } pub fn read_stdin_nonblock(buf: &mut [u8]) -> io::Result<usize> { unsafe { let mut stdin = io::stdin().lock(); let flags = libc::fcntl(stdin.as_raw_fd(), libc::F_GETFL); if flags == -1 { return Err(io::Error::last_os_error()); } let rv = libc::fcntl(stdin.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK); if rv == -1 { return Err(io::Error::last_os_error()); } let bytes_read = match stdin.read(buf) { Ok(bytes_read) => Ok(bytes_read), Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(0), Err(e) => Err(e), }?; let rv = libc::fcntl(stdin.as_raw_fd(), libc::F_SETFL, flags); if rv == -1 { return Err(io::Error::last_os_error()); } Ok(bytes_read) } } pub struct EscapeSeqStateMachine { escaped: bool, } impl EscapeSeqStateMachine { pub fn new() -> Self { Self { escaped: false } } pub fn process(&mut self, buf: &mut [u8], len: &mut usize, mut cb: impl FnMut(u8)) { let mut copy_offset = 0; for i in 0..*len { let ch = buf[i]; if self.escaped { self.escaped = false; if ch != 0x14 { cb(ch); copy_offset += 1; *len -= 1; continue; } } else if ch == 0x14 { // Ctrl-T was pressed self.escaped = true; copy_offset += 1; *len -= 1; continue; } buf[i - copy_offset] = ch; } } } #[cfg(test)] mod tests { use super::EscapeSeqStateMachine; #[test] fn test_escape_sequence() { let mut callback_invocations = Vec::new(); let mut sm = EscapeSeqStateMachine::new(); let mut buf = [b'H', b'i', 0x14, 0x00]; let mut len = 3; sm.process(&mut buf, &mut len, |ch| callback_invocations.push(ch)); assert_eq!(&buf[..len], [b'H', b'i']); assert_eq!(callback_invocations, vec![]); len = 2; buf = [b'q', b'W', 0x00, 0x00]; sm.process(&mut buf, &mut len, |ch| callback_invocations.push(ch)); assert_eq!(&buf[..len], [b'W']); assert_eq!(callback_invocations, vec![b'q']); callback_invocations.clear(); len = 9; let mut buf = [b'h', 0x14, b'w', b'j', 0x14, 0x14, 0x14, b'd', b'x']; sm.process(&mut buf, &mut len, |ch| callback_invocations.push(ch)); assert_eq!(&buf[..len], [b'h', b'j', 0x14, b'x']); assert_eq!(callback_invocations, vec![b'w', b'd']); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/fpga_jtag.rs
ci-tools/fpga-boss/src/fpga_jtag.rs
// Licensed under the Apache-2.0 license use std::time::Duration; use crate::{ ftdi::{BitMode, FtdiInterface}, FtdiCtx, UsbPortPath, }; pub enum FpgaReset { Reset = 0, Run = 1, } pub struct FpgaJtag { pub ftdi: FtdiCtx, } impl FpgaJtag { pub fn open(port_path: UsbPortPath) -> anyhow::Result<Self> { Ok(Self { ftdi: FtdiCtx::open(port_path, FtdiInterface::INTERFACE_A)?, }) } pub fn set_reset(&mut self, reset: FpgaReset) -> anyhow::Result<()> { self.ftdi.set_bitmode(0xc0, BitMode::BitBang)?; match reset { FpgaReset::Reset => { // Set PS_POR_B and PS_SRST_B pins low self.ftdi.write_all_data(&[0x0d])?; } FpgaReset::Run => { // Set PS_POR_B high, PS_SRST_B low self.ftdi.write_all_data(&[0x8d])?; // wait a bit std::thread::sleep(Duration::from_millis(1)); // Set PS_POR_B and PS_SRST_B pins high self.ftdi.write_all_data(&[0xcd])?; } } Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/find_usb_block_device.rs
ci-tools/fpga-boss/src/find_usb_block_device.rs
// Licensed under the Apache-2.0 license use std::{ os::unix::prelude::OsStrExt, path::{Path, PathBuf}, }; use crate::UsbPortPath; /// Returns the path to the block device connected to a particular USB port. pub fn find_usb_block_device(usb_path: &UsbPortPath) -> anyhow::Result<PathBuf> { let iface_prefix = format!("{usb_path}:"); let path = Path::new("/sys/bus/usb/devices").join(usb_path.to_string()); for entry in std::fs::read_dir(path)? { let entry = entry?; if entry .file_name() .as_bytes() .starts_with(iface_prefix.as_bytes()) { let Ok(iface_dir_iter) = std::fs::read_dir(entry.path()) else { continue; }; for entry2 in iface_dir_iter { let Ok(iface_entry) = entry2 else { continue; }; if !iface_entry.file_name().as_bytes().starts_with(b"host") { continue; } let Ok(iter3) = std::fs::read_dir(iface_entry.path()) else { continue; }; for entry3 in iter3 { let Ok(entry3) = entry3 else { continue; }; if !entry3.file_name().as_bytes().starts_with(b"target") { continue; } let Ok(iter4) = std::fs::read_dir(entry3.path()) else { continue; }; for entry4 in iter4 { let Ok(entry4) = entry4 else { continue; }; let block_dir = entry4.path().join("block"); let Ok(block_devs) = std::fs::read_dir(block_dir) else { continue; }; let block_devs: Vec<_> = block_devs.collect(); if block_devs.len() != 1 { continue; } let Ok(block_dev_name) = &block_devs[0] else { continue; }; let result = Path::new("/dev").join(block_dev_name.file_name()); println!( "Block device associated with {usb_path} is {}", result.display() ); return Ok(result); } } } } } unreachable!(); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/ftdi.rs
ci-tools/fpga-boss/src/ftdi.rs
// Licensed under the Apache-2.0 license use std::ffi::{c_int, CStr}; use libftdi1_sys::{ftdi_bits_type, ftdi_parity_type, ftdi_stopbits_type}; use rusb::{Device, GlobalContext}; use crate::UsbPortPath; fn device_from_path(port_path: &UsbPortPath) -> anyhow::Result<Device<GlobalContext>> { for dev in rusb::devices()?.iter() { if dev.bus_number() == port_path.bus && dev.port_numbers()? == port_path.ports { return Ok(dev); } } anyhow::bail!("USB device not found: {}", port_path); } pub type FtdiInterface = libftdi1_sys::ftdi_interface; #[repr(u8)] pub enum BitMode { Reset = 0, BitBang = 0x01, CBus = 0x20, } pub struct FtdiCtx { ctx: *mut libftdi1_sys::ftdi_context, port_path: UsbPortPath, } impl FtdiCtx { pub fn open(port_path: UsbPortPath, iface: FtdiInterface) -> anyhow::Result<Self> { let dev = device_from_path(&port_path)?; println!("Opening device {} {}", dev.bus_number(), dev.address()); unsafe { let ctx = libftdi1_sys::ftdi_new(); if ctx.is_null() { anyhow::bail!("ftdi_new failed"); } let rv = libftdi1_sys::ftdi_set_interface(ctx, iface); if rv < 0 { let err = anyhow::format_err!( "{} ftdi_set_interface failed: {:?}", port_path, CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(ctx)) ); libftdi1_sys::ftdi_free(ctx); return Err(err); } let rv = libftdi1_sys::ftdi_usb_open_dev(ctx, dev.as_raw()); if rv < 0 { let err = anyhow::format_err!( "ftdi_usb_open failed for device {port_path}: {:?}", CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(ctx)) ); libftdi1_sys::ftdi_free(ctx); return Err(err); } Ok(Self { ctx, port_path }) } } pub fn reset(&mut self) -> anyhow::Result<()> { unsafe { let rv = libftdi1_sys::ftdi_usb_reset(self.ctx); if rv < 0 { anyhow::bail!( "{} ftdi_usb_reset failed: {:?}", self.port_path, CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } } Ok(()) } pub fn set_bitmode(&mut self, pin_state: u8, mode: BitMode) -> anyhow::Result<()> { unsafe { let rv = libftdi1_sys::ftdi_set_bitmode(self.ctx, pin_state, mode as u8); if rv < 0 { anyhow::bail!( "{} ftdi_set_bitmode failed: {:?}", self.port_path, CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } Ok(()) } } #[allow(unused)] pub fn read_pins(&mut self, pin_state: u8, mode: BitMode) -> anyhow::Result<u8> { unsafe { let mut pins: u8 = 0; let rv = libftdi1_sys::ftdi_read_pins(self.ctx, &mut pins as *mut _); if rv < 0 { anyhow::bail!( "{} ftdi_read_pins failed: {:?}", self.port_path, CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } Ok(pins) } } pub fn read_data(&mut self, buf: &mut [u8]) -> anyhow::Result<usize> { unsafe { let rv = libftdi1_sys::ftdi_read_data(self.ctx, buf.as_mut_ptr(), buf.len().try_into()?); if rv < 0 { anyhow::bail!( "ftdi_write_data failed: {:?}", CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } Ok(rv.try_into()?) } } pub fn write_all_data(&mut self, data: &[u8]) -> anyhow::Result<()> { let bytes_written = self.write_data(data)?; if bytes_written != data.len() { anyhow::bail!( "{} ftdi_write data returned {} bytes, expected {}", self.port_path, bytes_written, data.len() ); } Ok(()) } pub fn write_data(&mut self, data: &[u8]) -> anyhow::Result<usize> { unsafe { let rv = libftdi1_sys::ftdi_write_data(self.ctx, data.as_ptr(), data.len().try_into()?); if rv < 0 { anyhow::bail!( "ftdi_write_data failed: {:?}", CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } Ok(rv.try_into()?) } } pub fn set_baudrate(&mut self, baudrate: u32) -> anyhow::Result<()> { unsafe { let rv = libftdi1_sys::ftdi_set_baudrate(self.ctx, c_int::try_from(baudrate)?); if rv < 0 { anyhow::bail!( "ftdi_set_baudrate failed: {:?}", CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } } Ok(()) } pub fn set_line_property( &mut self, bits: ftdi_bits_type, stopbits: ftdi_stopbits_type, parity: ftdi_parity_type, ) -> anyhow::Result<()> { unsafe { let rv = libftdi1_sys::ftdi_set_line_property(self.ctx, bits, stopbits, parity); if rv < 0 { anyhow::bail!( "ftdi_set_line_property failed: {:?}", CStr::from_ptr(libftdi1_sys::ftdi_get_error_string(self.ctx)) ); } } Ok(()) } } impl Drop for FtdiCtx { fn drop(&mut self) { unsafe { libftdi1_sys::ftdi_usb_close(self.ctx) }; unsafe { libftdi1_sys::ftdi_free(self.ctx) }; } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/ftdi_uart.rs
ci-tools/fpga-boss/src/ftdi_uart.rs
// Licensed under the Apache-2.0 license use std::{ io::{self, ErrorKind}, time::{Duration, Instant}, }; use libftdi1_sys::{ftdi_bits_type, ftdi_interface, ftdi_parity_type, ftdi_stopbits_type}; use std::cell::RefCell; use std::rc::Rc; use crate::{ ftdi::{BitMode, FtdiCtx}, usb_port_path::UsbPortPath, }; pub struct FtdiUartReader { ftdi: Rc<RefCell<FtdiCtx>>, } pub struct FtdiUartReaderBlocking { ftdi: Rc<RefCell<FtdiCtx>>, timeout: Option<Duration>, } pub struct FtdiUartWriter { ftdi: Rc<RefCell<FtdiCtx>>, } impl FtdiUartWriter { pub fn send_break(&self) -> anyhow::Result<()> { const BREAK_TIME: Duration = Duration::from_micros(100); let mut ftdi = self.ftdi.borrow_mut(); ftdi.set_bitmode(0x01, BitMode::BitBang)?; ftdi.write_all_data(&[0x00])?; std::thread::sleep(BREAK_TIME); ftdi.set_bitmode(0x01, BitMode::Reset)?; ftdi.set_baudrate(115200)?; ftdi.set_line_property( ftdi_bits_type::BITS_8, ftdi_stopbits_type::STOP_BIT_1, ftdi_parity_type::NONE, )?; Ok(()) } } pub fn open( port_path: UsbPortPath, iface: ftdi_interface, ) -> anyhow::Result<(FtdiUartReader, FtdiUartWriter)> { let mut ftdi = FtdiCtx::open(port_path, iface)?; ftdi.set_bitmode(0, BitMode::Reset)?; ftdi.set_baudrate(115200)?; ftdi.set_line_property( ftdi_bits_type::BITS_8, ftdi_stopbits_type::STOP_BIT_1, ftdi_parity_type::NONE, )?; let ftdi = Rc::new(RefCell::new(ftdi)); Ok(( FtdiUartReader { ftdi: ftdi.clone() }, FtdiUartWriter { ftdi }, )) } pub fn open_blocking( port_path: UsbPortPath, iface: ftdi_interface, timeout: Option<Duration>, ) -> anyhow::Result<(FtdiUartReaderBlocking, FtdiUartWriter)> { let (rx, tx) = open(port_path, iface)?; Ok(( FtdiUartReaderBlocking { ftdi: rx.ftdi, timeout, }, tx, )) } impl io::Read for FtdiUartReader { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.ftdi .borrow_mut() .read_data(buf) .map_err(|e| io::Error::new(ErrorKind::Other, e)) } } impl io::Read for FtdiUartReaderBlocking { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let start_time = Instant::now(); loop { let bytes_read = self .ftdi .borrow_mut() .read_data(buf) .map_err(|e| io::Error::new(ErrorKind::Other, e))?; if bytes_read > 0 { return Ok(bytes_read); } if let Some(timeout) = self.timeout { if start_time.elapsed() > timeout { Err(io::Error::new( ErrorKind::TimedOut, "timed out reading from FPGA UART", ))? } } } } } impl io::Write for FtdiUartWriter { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.ftdi .borrow_mut() .write_data(buf) .map_err(|e| io::Error::new(ErrorKind::Other, e)) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/usb_port_path.rs
ci-tools/fpga-boss/src/usb_port_path.rs
// Licensed under the Apache-2.0 license use std::fmt::{Debug, Display}; use std::str::FromStr; use anyhow::{anyhow, Context}; /// Identifies a USB device connected to a particular port (For example "3-1.4") #[derive(Clone, Eq, PartialEq)] pub struct UsbPortPath { pub bus: u8, pub ports: Vec<u8>, } impl UsbPortPath { #[allow(unused)] pub fn new(bus: u8, ports: Vec<u8>) -> Self { Self { bus, ports } } pub fn child(&self, index: u8) -> Self { let mut ports = self.ports.clone(); ports.push(index); Self { bus: self.bus, ports, } } } impl FromStr for UsbPortPath { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let context = || format!("Unable to parse UsbPortPath {s:?}"); let Some((root, remainder)) = s.split_once('-') else { return Err(anyhow!("no '-'")).with_context(context); }; let bus = u8::from_str(root).with_context(context)?; let mut ports = vec![]; for item in remainder.split('.') { ports.push(u8::from_str(item).with_context(context)?); } Ok(UsbPortPath { bus, ports }) } } impl Display for UsbPortPath { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.bus)?; for (index, item) in self.ports.iter().enumerate() { if index == 0 { write!(f, "-")?; } else { write!(f, ".")?; } write!(f, "{}", item)?; } Ok(()) } } impl Debug for UsbPortPath { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_port_path_parse() { assert_eq!( UsbPortPath::from_str("5-1.2.3.23").unwrap(), UsbPortPath::new(5, vec![1, 2, 3, 23]) ); assert_eq!( UsbPortPath::from_str("23-6").unwrap(), UsbPortPath::new(23, vec![6]) ); assert_eq!( UsbPortPath::from_str("23-a").unwrap_err().to_string(), "Unable to parse UsbPortPath \"23-a\"" ); assert_eq!( UsbPortPath::from_str("23").unwrap_err().to_string(), "Unable to parse UsbPortPath \"23\"" ); assert_eq!( UsbPortPath::from_str("").unwrap_err().to_string(), "Unable to parse UsbPortPath \"\"" ); } #[test] fn test_port_path_display() { assert_eq!(UsbPortPath::new(52, vec![1, 4]).to_string(), "52-1.4"); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/main.rs
ci-tools/fpga-boss/src/main.rs
// Licensed under the Apache-2.0 license mod find_usb_block_device; mod fpga_jtag; mod ftdi; mod ftdi_uart; mod sd_mux; mod tty; mod usb_port_path; use anyhow::{anyhow, Context}; use clap::{arg, value_parser}; use libftdi1_sys::ftdi_interface; use std::{ ffi::OsString, fs::{File, OpenOptions}, io::{stdout, BufRead, BufReader, Error, ErrorKind, Lines, Read, Seek, SeekFrom, Write}, path::{Path, PathBuf}, process::Stdio, time::{Duration, Instant}, }; pub(crate) use fpga_jtag::{FpgaJtag, FpgaReset}; pub(crate) use ftdi::FtdiCtx; use sd_mux::{SDWire, SdMux, SdMuxTarget, UsbsdMux}; pub(crate) use usb_port_path::UsbPortPath; // 3 hours const JOB_TIMEOUT: Duration = Duration::from_secs(10_800); fn cli() -> clap::Command<'static> { clap::Command::new("fpga-boss") .about("FPGA boss tool") .arg( arg!(--"sdwire" [PORT_PATH] "USB port path to the hub chip on the SDWire (ex: 3-1.2)") .value_parser(value_parser!(OsString))) .arg( arg!(--"usbsdmux" [USBID] "USB unique ID for the usbsdmux device (ex: 00048.00643)") .value_parser(value_parser!(OsString)) ) .arg( arg!(--"zcu104" [PORT_PATH] "USB port path to the FTDI chip on the ZCU104 dev board (ex: 3-1.2)") .value_parser(value_parser!(UsbPortPath)) ) .arg( arg!(--"boss_ftdi" [PORT_PATH] "USB port path to a FTDI C232HM-DDHSL cable plugged into an rPi (ex: 3-1.2") .value_parser(value_parser!(UsbPortPath)) ) .subcommand_required(true) .subcommand(clap::Command::new("mode") .about("Set the state of the reset / sdwire pins") .arg(arg!(<MODE>).value_parser(value_parser!(SdMuxTarget)))) .arg_required_else_help(true) .subcommand(clap::Command::new("flash") .about("Flash an image file to the sdwire and boot the DUT") .arg(arg!(-r --read_first).takes_value(false).help("To reduce write cycles, read contents first, and don't flash if they are already as expected.")) .arg(arg!(<IMAGE_FILENAME>).value_parser(value_parser!(PathBuf)))) .subcommand(clap::Command::new("console") .about("Tail the UART output from zcu104")) .subcommand(clap::Command::new("reset_fpga") .about("Reset FPGA SoC using FTDI on zcu104 by toggle POR_B reset.")) .subcommand(clap::Command::new("reset_ftdi") .about("Reset FTDI chip on zcu104")) .subcommand(clap::Command::new("serve") .arg(arg!(<IMAGE_FILENAME>).value_parser(value_parser!(PathBuf))) .arg(arg!(<CMD> ...).value_parser(value_parser!(OsString)).help("The command (and arguments) to read jitconfig entries from"))) } fn main() { match main_impl() { Ok(()) => std::process::exit(0), Err(e) => { eprintln!("Fatal error: {e:#}"); std::process::exit(1); } } } fn open_block_dev(path: &Path) -> std::io::Result<File> { let mut tries = 0_u32; loop { match OpenOptions::new().read(true).write(true).open(path) { Ok(result) => return Ok(result), Err(err) => { if err.raw_os_error() == Some(libc::ENOMEDIUM) { if tries == 0 { println!("Waiting for attached sd card to be noticed by OS") } // SD card hasn't been found by the OS yet tries += 1; if tries < 1000 { std::thread::sleep(Duration::from_millis(10)); continue; } } return Err(err); } } } } /// Returns true if the device already contains the image. fn verify_image(dev: &mut File, image: &mut File) -> std::io::Result<bool> { dev.seek(SeekFrom::Start(0))?; let file_len = image.metadata()?.len(); let mut want = vec![0_u8; 1024 * 1024]; let mut have = vec![0_u8; 1024 * 1024]; let mut total_read: u64 = 0; let start_time = Instant::now(); loop { let bytes_read = image.read(&mut want)?; if bytes_read == 0 { return Ok(true); } dev.read_exact(&mut have[..bytes_read])?; if want[..bytes_read] != have[..bytes_read] { return Ok(false); } total_read += u64::try_from(bytes_read).unwrap(); let duration = Instant::now() - start_time; print!( "Read {} MB of {} MB: {:.1} MB/sec \r", total_read / (1024 * 1024), file_len / (1024 * 1024), total_read as f64 / duration.as_secs_f64() / (1024.0 * 1024.0) ); std::io::stdout().flush()?; } } fn copy_file(dest: &mut File, src: &mut File) -> std::io::Result<()> { src.seek(SeekFrom::Start(0))?; dest.seek(SeekFrom::Start(0))?; let file_len = src.metadata()?.len(); let mut buf = vec![0_u8; 1024 * 1024]; let mut total_written: u64 = 0; let start_time = Instant::now(); loop { let bytes_read = src.read(&mut buf)?; if bytes_read == 0 { break; } total_written += u64::try_from(bytes_read).unwrap(); dest.write_all(&buf[..bytes_read])?; dest.sync_data()?; let duration = Instant::now() - start_time; print!( "Wrote {} MB of {} MB: {:.1} MB/sec \r", total_written / (1024 * 1024), file_len / (1024 * 1024), total_written as f64 / duration.as_secs_f64() / (1024.0 * 1024.0) ); std::io::stdout().flush()?; } dest.flush()?; dest.sync_all()?; Ok(()) } /// As we observe conditions that get the FGPA stuck, add them to the error parser. fn active_runner_error_checks(input: &str) -> std::io::Result<()> { check_for_github_runner_exception(input)?; check_for_kernel_panic(input)?; Ok(()) } /// If the GitHub runner has an unhandled exception it will crash and get stuck. Add this check /// to recover the FPGA. fn check_for_github_runner_exception(input: &str) -> std::io::Result<()> { if input.contains("Unhandled exception") || input.contains("Bus error") { Err(Error::new( ErrorKind::BrokenPipe, "Github runner had an unhandled exception", ))?; } Ok(()) } /// A kernel panic will cause the FPGA to never complete the job, so we want to reset the FPGA. fn check_for_kernel_panic(input: &str) -> std::io::Result<()> { if input.contains("Kernel panic") { Err(Error::new(ErrorKind::BrokenPipe, "FPGA had a kernel panic"))?; } Ok(()) } fn log_uart_until<R: BufRead>( lines: &mut Lines<R>, needle: &str, error_parser: impl Fn(&str) -> std::io::Result<()>, ) -> std::io::Result<()> { log_uart_until_helper(lines, needle, None, Some(error_parser)) } fn log_uart_until_with_timeout<R: BufRead>( lines: &mut Lines<R>, needle: &str, timeout: Duration, ) -> std::io::Result<()> { log_uart_until_helper( lines, needle, Some(timeout), None::<fn(&str) -> std::io::Result<()>>, ) } fn log_uart_until_helper<R: BufRead>( lines: &mut Lines<R>, needle: &str, timeout: Option<Duration>, error_parser: Option<impl Fn(&str) -> std::io::Result<()>>, ) -> std::io::Result<()> { let start = Instant::now(); for line in lines.by_ref() { match line { Ok(line) => { println!("UART: {}", line); if line.contains(needle) { return Ok(()); } if let Some(ref error_parser) = error_parser { error_parser(&line)?; } } // If no time out was configured, swallow this error. Err(e) if e.kind() == ErrorKind::TimedOut => { if let Some(timeout) = timeout { if start.elapsed() > timeout { return Err(e); } } } Err(e) => { println!("UART error: {}", e); } } } Err(Error::new(ErrorKind::UnexpectedEof, "unexpected EOF")) } fn get_sd_mux( sdwire: Option<&OsString>, usbsdmux: Option<&OsString>, ) -> anyhow::Result<Box<dyn SdMux>> { match (sdwire, usbsdmux) { (Some(sdwire), None) => { Ok(Box::new(SDWire::open(String::from(sdwire.to_str().unwrap()))?) as Box<dyn SdMux>) } (None, Some(usbsdmux)) => Ok(Box::new(UsbsdMux::open(String::from( usbsdmux.to_str().unwrap(), ))?) as Box<dyn SdMux>), _ => Err(anyhow!("One of --sdwire or --usbsdmux required")), } } fn main_impl() -> anyhow::Result<()> { let matches = cli().get_matches(); let sdwire = matches.get_one::<OsString>("sdwire"); let usbsdmux = matches.get_one::<OsString>("usbsdmux"); let zcu104_path = matches.get_one::<UsbPortPath>("zcu104"); let boss_ftdi_path = matches.get_one::<UsbPortPath>("boss_ftdi"); let get_nonblocking_uart = || match (zcu104_path, boss_ftdi_path) { (Some(zcu104_path), None) => { ftdi_uart::open(zcu104_path.clone(), ftdi_interface::INTERFACE_B) } (None, Some(boss_ftdi_path)) => { ftdi_uart::open(boss_ftdi_path.clone(), ftdi_interface::INTERFACE_A) } _ => Err(anyhow!("One of --zcu104_path or --boss_ftdi_path required")), }; let get_zcu104_path = || { zcu104_path .ok_or(anyhow!("--zcu104 flag required")) .cloned() }; let get_fpga_ftdi = || FpgaJtag::open(get_zcu104_path()?); match matches.subcommand() { Some(("mode", sub_matches)) => { let mut sd_mux = get_sd_mux(sdwire, usbsdmux)?; let mut fpga = get_fpga_ftdi(); match sub_matches.get_one::<SdMuxTarget>("MODE").unwrap() { SdMuxTarget::Dut => { if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Reset)?; } sd_mux.set_target(SdMuxTarget::Dut)?; std::thread::sleep(Duration::from_millis(1)); if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Run)?; } } SdMuxTarget::Host => { if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Reset)?; } sd_mux.set_target(SdMuxTarget::Host)?; } } } Some(("reset_fpga", _)) => { let mut fpga = get_fpga_ftdi(); if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Reset)?; std::thread::sleep(Duration::from_millis(1)); fpga.set_reset(FpgaReset::Run)?; } else { return Err(anyhow!("Error: failed to connect to FTDI chip.")); } } Some(("reset_ftdi", _)) => { let mut fpga = get_fpga_ftdi()?; fpga.ftdi.reset()?; } Some(("console", _)) => { let (mut uart_rx, mut uart_tx) = get_nonblocking_uart()?; let mut stdout_buf = [0_u8; 4096]; let mut stdin_buf = [0_u8; 4096]; println!("To exit terminal type Ctrl-T then Q"); // Will reset terminal back to regular settings upon drop let raw_terminal = tty::RawTerminal::from_stdin()?; let mut escaper = tty::EscapeSeqStateMachine::new(); let mut alive = true; while alive { let mut stdin_len = tty::read_stdin_nonblock(&mut stdin_buf)?; escaper.process(&mut stdin_buf, &mut stdin_len, |ch| match ch { b'q' | b'Q' => alive = false, b'b' | b'B' => { uart_tx.send_break().unwrap(); } ch => println!( "Unknown escape sequence: Ctrl-T + {:?}", char::from_u32(ch.into()).unwrap_or('?') ), }); if stdin_len > 0 { uart_tx.write_all(&stdin_buf[..stdin_len])?; } let stdout_len = uart_rx.read(&mut stdout_buf)?; if stdout_len > 0 { stdout().write_all(&stdout_buf[..stdout_len])?; stdout().flush()?; } } drop(raw_terminal); println!(); } Some(("flash", sub_matches)) => { let mut sd_mux = get_sd_mux(sdwire, usbsdmux)?; let mut fpga = get_fpga_ftdi(); let sd_dev_path = sd_mux.get_sd_dev_path()?; if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Reset)?; } sd_mux.set_target(SdMuxTarget::Host)?; let image_filename = sub_matches.get_one::<PathBuf>("IMAGE_FILENAME").unwrap(); println!( "Flashing {} to {}", image_filename.display(), sd_dev_path.display() ); let mut file = File::open(image_filename).with_context(|| image_filename.display().to_string())?; let mut sd_dev = open_block_dev(&sd_dev_path).with_context(|| sd_dev_path.display().to_string())?; if !sub_matches.is_present("read_first") || !verify_image(&mut sd_dev, &mut file)? { copy_file(&mut sd_dev, &mut file)?; if !verify_image(&mut sd_dev, &mut file)? { return Err(anyhow!("Failed to verify image after flashing. Please try again.")); } } else { println!("Device already contains the desired image"); } sd_mux.set_target(SdMuxTarget::Dut)?; std::thread::sleep(Duration::from_millis(100)); if let Ok(fpga) = &mut fpga { fpga.set_reset(FpgaReset::Run)? } } Some(("serve", sub_matches)) => { let mut sd_mux = get_sd_mux(sdwire, usbsdmux)?; // Reuse the previous token if we never connect to GitHub. // This avoids creating a bunch of offline runners if the FPGA fails to establish a // connection. let mut cached_token: Option<Vec<u8>> = None; let mut fpga = get_fpga_ftdi()?; let sd_dev_path = sd_mux.get_sd_dev_path()?; 'outer: loop { println!("Putting FPGA into reset"); fpga.set_reset(FpgaReset::Reset)?; sd_mux.set_target(SdMuxTarget::Host)?; { println!("Ensuring SD card contents are as expected"); let image_filename = sub_matches.get_one::<PathBuf>("IMAGE_FILENAME").unwrap(); let mut file = File::open(image_filename) .with_context(|| image_filename.display().to_string())?; let mut sd_dev = open_block_dev(&sd_dev_path) .with_context(|| sd_dev_path.display().to_string())?; if !verify_image(&mut sd_dev, &mut file)? { copy_file(&mut sd_dev, &mut file)?; } std::thread::sleep(Duration::from_millis(100)); } let boot_timeout = Duration::from_secs(180); let (uart_rx, mut uart_tx) = ftdi_uart::open_blocking( get_zcu104_path()?, ftdi_interface::INTERFACE_B, Some(boot_timeout), )?; println!("Taking FPGA out of reset"); sd_mux.set_target(SdMuxTarget::Dut)?; std::thread::sleep(Duration::from_millis(100)); fpga.set_reset(FpgaReset::Run)?; let mut uart_lines = BufReader::new(uart_rx).lines(); // FPGA has `fpga_timeout: Duration` to boot until we reset and try again. match log_uart_until_with_timeout( &mut uart_lines, "36668aa492b1c83cdd3ade8466a0153d --- Command input", boot_timeout, ) { Err(e) if e.kind() == ErrorKind::TimedOut => { eprintln!("Timed out waiting for FPGA to boot!"); continue 'outer; } Err(e) => Err(e)?, _ => (), } if cached_token.is_none() { let command_args: Vec<_> = sub_matches.get_many::<OsString>("CMD").unwrap().collect(); println!("Executing command {:?} to retrieve jitconfig", command_args); let output = std::process::Command::new(command_args[0]) .args(&command_args[1..]) .stderr(Stdio::inherit()) .output()?; if !output.status.success() { println!("Error retrieving jitconfig: stdout:"); stdout().write_all(&output.stdout)?; continue; } cached_token = Some(output.stdout); } uart_tx.write_all(b"runner-jitconfig ")?; uart_tx.write_all( &cached_token .clone() .expect("A token should always be cached before sending it over the UART"), )?; uart_tx.write_all(b"\n")?; // FGPA has `boot_timeout: Duration` to connect to GitHub until we reset and try again. match log_uart_until_with_timeout( &mut uart_lines, "Listening for Jobs", boot_timeout, ) { Err(e) if e.kind() == ErrorKind::TimedOut => { eprintln!("Timed out waiting for FPGA to connect to Github!"); continue 'outer; } Err(e) => Err(e)?, _ => (), } cached_token = None; // The period of time we wait to receive a job is undefined so a timeout is not // appropriate. log_uart_until(&mut uart_lines, "Running job", active_runner_error_checks)?; // Now the job is started, so we want to enforce a timeout with enough time for the // job to complete. match log_uart_until_with_timeout( &mut uart_lines, "3297327285280f1ffb8b57222e0a5033 --- ACTION IS COMPLETE", JOB_TIMEOUT, ) { Err(e) if e.kind() == ErrorKind::TimedOut => { eprintln!("Timed out waiting for FPGA to complete job!"); continue 'outer; } Err(e) => Err(e)?, _ => (), } } } _ => unreachable!(), } Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/fpga-boss/src/sd_mux.rs
ci-tools/fpga-boss/src/sd_mux.rs
// Licensed under the Apache-2.0 license use anyhow::Context; use std::fs; use std::path::PathBuf; use std::str::FromStr; use clap::PossibleValue; use libftdi1_sys::ftdi_interface; use crate::{find_usb_block_device::find_usb_block_device, ftdi, FtdiCtx, UsbPortPath}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SdMuxTarget { Host, Dut, } impl clap::ValueEnum for SdMuxTarget { fn value_variants<'a>() -> &'a [Self] { &[Self::Host, Self::Dut] } fn to_possible_value<'a>(&self) -> Option<clap::PossibleValue<'a>> { match self { Self::Host => Some(PossibleValue::new("host").help("host can access sd card")), Self::Dut => { Some(PossibleValue::new("dut").help("device-under-test can boot from sd card")) } } } } impl FromStr for SdMuxTarget { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "dut" => Ok(Self::Dut), "host" => Ok(Self::Host), _ => Err(()), } } } // SdMux is a trait for SD muxes. It provides a way to set the target (DUT or host) and open the mux. pub trait SdMux { fn set_target(&mut self, target: SdMuxTarget) -> anyhow::Result<()>; /// Opens the mux and returns a new instance of the mux. /// For SDWire, this is the FTDI device. It will be converted into UsbPortPath. /// For UsbSDMux, this is UID for the USBSDMUX device. fn open(port_path: String) -> anyhow::Result<Self> where Self: Sized; /// Returns the path to the block device associated with the SD mux. fn get_sd_dev_path(&mut self) -> anyhow::Result<PathBuf>; } // Implementation specific to SDWire (idVendor=04e8, idProduct=6001) pub struct SDWire { // The FTDI device used to communicate with the SDWire mux. ftdi: FtdiCtx, // The USB port path of the SDWire mux. port_path: UsbPortPath, } impl SdMux for SDWire { fn open(port_path: String) -> anyhow::Result<Self> { let port_path: UsbPortPath = UsbPortPath::from_str(&port_path) .map_err(|_| anyhow::anyhow!("Failed to parse port path"))?; let mut result = Self { ftdi: FtdiCtx::open(port_path.child(2), ftdi_interface::INTERFACE_A)?, port_path, }; result.ftdi.set_bitmode(0xc0, ftdi::BitMode::BitBang)?; Ok(result) } fn set_target(&mut self, target: SdMuxTarget) -> anyhow::Result<()> { let pin_state = match target { SdMuxTarget::Dut => 0xf0, SdMuxTarget::Host => 0xf1, }; self.ftdi.set_bitmode(pin_state, ftdi::BitMode::CBus)?; Ok(()) } fn get_sd_dev_path(&mut self) -> anyhow::Result<PathBuf> { let sdwire_hub_path = self.port_path.child(1); find_usb_block_device(&sdwire_hub_path).with_context(|| { format!( "Could not find block device associated with {}", sdwire_hub_path ) }) } } // The UsbSDMux does expose the following things: // 1. A python cli interface to set the target. // 1.1 change target // 1.2 Shut the mux off // 1.3 manipulate GPIO pins on the MUX // 2. A SCSI generic device interface to set the target. // 2.1 A block device that can be used to access the SD card. // NO FTDI interface is exposed. // The SCSI generic device is usually /dev/sg0 but can be different (check sg_map -i). // https://github.com/linux-automation/usbsdmux/ pub struct UsbsdMux { // SCSI generic device name, e.g. sg0. scsi_generic_name: String, } impl SdMux for UsbsdMux { /// USBSDMUX exposes all connected adapters as linux devices under dev/usb-sd-mux/id-xxxxx.xxxxx. /// The ID used to construct an UsbdsdMux instance is the symlink name without the leading "id-". /// Resolving these symlinks by ID resolves them to the according /dev/sgX device. fn open(sdmux_id: String) -> anyhow::Result<Self> { let symlink_path = format!("/dev/usb-sd-mux/id-{}", sdmux_id); // this will be of format ../sgx let had_dev = std::fs::read_link(symlink_path)? .to_string_lossy() .to_string(); Ok(Self { scsi_generic_name: had_dev.strip_prefix("../").unwrap().to_string(), }) } // For now we use the python cli tool implementation provided by the vendor. // Further, we assume there is only one usbsdmux device connected, exposed // via /dev/sg0. fn set_target(&mut self, target: SdMuxTarget) -> anyhow::Result<()> { let target = match target { SdMuxTarget::Dut => "dut", SdMuxTarget::Host => "host", }; if std::process::Command::new("usbsdmux") .arg("--help") .output() .is_err() { return Err(anyhow::anyhow!("usbsdmux tool not found")); } let out = std::process::Command::new("usbsdmux") .arg(format!("/dev/{}", self.scsi_generic_name.clone())) .arg(target) .output() .map_err(|e| anyhow::anyhow!("usbsdmux: {}", e))?; if !out.status.success() { return Err(anyhow::anyhow!( "Failed to set target: {}", String::from_utf8_lossy(&out.stderr) )); } if !out.stdout.is_empty() { println!("usbsdmux output: {}", String::from_utf8_lossy(&out.stdout)); } Ok(()) } // Resolve the SCSI generic device name to the block device name. fn get_sd_dev_path(&mut self) -> anyhow::Result<PathBuf> { let scsi_block_dev = format!( "/sys/class/scsi_generic/{}/device/block/", self.scsi_generic_name ); if let Some(entry) = fs::read_dir(&scsi_block_dev)?.next() { let entry = entry?; let block_dev_name = entry.file_name(); let block_dev_path = format!("/dev/{}", block_dev_name.to_string_lossy()); Ok(PathBuf::from(block_dev_path)) } else { Err(anyhow::anyhow!( "Failed to find block device for SCSI generic device {}. Ensure the device is connected and the path {} exists.", self.scsi_generic_name, &scsi_block_dev )) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_sd_mux_target() { assert_eq!(SdMuxTarget::from_str("host").unwrap(), SdMuxTarget::Host); assert_eq!(SdMuxTarget::from_str("dut").unwrap(), SdMuxTarget::Dut); assert!(SdMuxTarget::from_str("invalid").is_err()); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/html.rs
ci-tools/size-history/src/html.rs
// Licensed under the Apache-2.0 license use std::{cmp::Ordering, fmt::Write, io}; use serde::{Deserialize, Serialize}; use serde_json::Value; use tinytemplate::TinyTemplate; use crate::{git, SizeRecord, Sizes}; // The GitHub "HTML sanitizer" is incredibly sensitive to whitespace; do not attempt to break newlines. static TEMPLATE: &str = r#" <table> <tr><th>Commit</th><th>Author</th><th>Commit</th><th>ROM prod size</th><th>ROM with-uart size</th><th>FMC size</th><th>App size</th></tr> {{ for record in records }} <tr> <td><a href="https://github.com/chipsalliance/caliptra-sw/commit/{ record.commit.id }">{ record.commit.id | trim_8 }</a></td> <td>{ record.commit.author | name_only }</td> {{ if record.important }}<td><strong>{ record.commit.title }</strong></td>{{ else }}<td>{ record.commit.title }</td>{{ endif }} <td>{{ if record.sizes.rom_size_prod }}{ record.sizes.rom_size_prod.total }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>({ record.sizes.rom_size_prod.delta | delta_format }){{ else }}build error{{ endif }}</td><td>{{ if record.sizes.rom_size_with_uart }}{ record.sizes.rom_size_with_uart.total }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>({ record.sizes.rom_size_with_uart.delta | delta_format }){{ else }}build error{{ endif }}</td><td>{{ if record.sizes.fmc_size_with_uart }}{ record.sizes.fmc_size_with_uart.total }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>({ record.sizes.fmc_size_with_uart.delta | delta_format }){{ else }}build error{{ endif }}</td><td>{{ if record.sizes.app_size_with_uart }}{ record.sizes.app_size_with_uart.total }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>({ record.sizes.app_size_with_uart.delta | delta_format }){{ else }}build error{{ endif }}</td> </tr> {{ endfor }} </table> "#; pub(crate) fn format_records(records: &[SizeRecord]) -> io::Result<String> { let mut extended_records = vec![]; let mut last_sizes = Sizes::default(); for record in records.iter().rev() { let ext_sizes = ExtendedSizes { rom_size_prod: ExtendedSizeInfo::from_change( last_sizes.rom_size_prod, record.sizes.rom_size_prod, ), rom_size_with_uart: ExtendedSizeInfo::from_change( last_sizes.rom_size_with_uart, record.sizes.rom_size_with_uart, ), fmc_size_with_uart: ExtendedSizeInfo::from_change( last_sizes.fmc_size_with_uart, record.sizes.fmc_size_with_uart, ), app_size_with_uart: ExtendedSizeInfo::from_change( last_sizes.app_size_with_uart, record.sizes.app_size_with_uart, ), }; let mut ext_record = ExtendedRecord { commit: record.commit.clone(), important: is_important(&ext_sizes), sizes: ext_sizes, }; ext_record.commit.title.truncate(80); extended_records.push(ext_record); last_sizes.update_from(&record.sizes); } extended_records.reverse(); let mut tt = TinyTemplate::new(); tt.add_formatter("name_only", |val, out| { if let Some(s) = val.as_str() { out.write_str(name_only(s))?; } Ok(()) }); tt.add_template("index", TEMPLATE).unwrap(); tt.add_formatter("trim_8", |val, out| { if let Some(s) = val.as_str() { out.write_str(s.get(..8).unwrap_or(s))?; } Ok(()) }); tt.add_formatter("delta_format", |val, out| { if let Value::Number(delta) = val { if let Some(delta) = delta.as_i64() { match delta.cmp(&0) { Ordering::Greater => write!(out, "🟥 +{delta}")?, Ordering::Less => write!(out, "🟩 {delta}")?, Ordering::Equal => write!(out, "{delta}")?, } } } Ok(()) }); Ok(tt .render( "index", &TemplateContext { records: extended_records, }, ) .unwrap()) } fn is_important(sizes: &ExtendedSizes) -> bool { fn has_delta(info: &Option<ExtendedSizeInfo>) -> bool { info.map(|i| i.delta != 0).unwrap_or(false) } has_delta(&sizes.rom_size_prod) || has_delta(&sizes.rom_size_with_uart) || has_delta(&sizes.fmc_size_with_uart) || has_delta(&sizes.app_size_with_uart) } fn name_only(val: &str) -> &str { if let Some((name, _)) = val.split_once('<') { name.trim() } else { val } } #[derive(Serialize)] struct TemplateContext { records: Vec<ExtendedRecord>, } #[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] struct ExtendedSizeInfo { total: u64, delta: i64, } impl ExtendedSizeInfo { fn from_change(prev: Option<u64>, current: Option<u64>) -> Option<Self> { let prev = prev.unwrap_or(0); current.map(|current| Self { total: current, delta: current.wrapping_sub(prev) as i64, }) } } #[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] struct ExtendedSizes { // If fields are None, there was a problem building the commit rom_size_prod: Option<ExtendedSizeInfo>, rom_size_with_uart: Option<ExtendedSizeInfo>, fmc_size_with_uart: Option<ExtendedSizeInfo>, app_size_with_uart: Option<ExtendedSizeInfo>, } #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] struct ExtendedRecord { commit: git::CommitInfo, important: bool, sizes: ExtendedSizes, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/process.rs
ci-tools/size-history/src/process.rs
// Licensed under the Apache-2.0 license use std::{ io, process::{Command, Stdio}, }; pub fn run_cmd(cmd: &mut Command) -> io::Result<()> { let status = cmd.status()?; if status.success() { Ok(()) } else { Err(io::Error::new( io::ErrorKind::Other, format!( "Process {:?} {:?} exited with status code {:?}", cmd.get_program(), cmd.get_args(), status.code() ), )) } } pub fn run_cmd_stdout(cmd: &mut Command, input: Option<&[u8]>) -> io::Result<Vec<u8>> { cmd.stdin(Stdio::piped()); cmd.stdout(Stdio::piped()); let mut child = cmd.spawn()?; if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) { std::io::Write::write_all(&mut stdin, input)?; } let out = child.wait_with_output()?; if out.status.success() { Ok(out.stdout) } else { Err(io::Error::new( io::ErrorKind::Other, format!( "Process {:?} {:?} exited with status code {:?} stdout {} stderr {}", cmd.get_program(), cmd.get_args(), out.status.code(), String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr) ), )) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/http.rs
ci-tools/size-history/src/http.rs
// Licensed under the Apache-2.0 license use std::str::FromStr; use std::{borrow::Cow, io, process::Command}; use crate::util::expect_line_with_prefix_ignore_case; use crate::{ process::run_cmd_stdout, util::{expect_line_with_prefix, other_err}, }; pub struct Content<'a> { mime_type: Cow<'a, str>, data: Cow<'a, [u8]>, } impl<'a> Content<'a> { pub fn octet_stream(val: impl Into<Cow<'a, [u8]>>) -> Self { Self { mime_type: "application/octet-stream".into(), data: val.into(), } } pub fn protobuf(val: impl Into<Cow<'a, [u8]>>) -> Self { Self { mime_type: "application/protobuf".into(), data: val.into(), } } } pub struct HttpResponse { pub status: u32, pub content_type: String, pub location: Option<String>, pub data: Vec<u8>, } impl HttpResponse { fn parse(raw: Vec<u8>) -> io::Result<Self> { use std::io::BufRead; let mut raw = &raw[..]; let mut line = String::new(); raw.read_line(&mut line)?; let status_str = expect_line_with_prefix("HTTP/1.1 ", Some(&line)) .or_else(|_| expect_line_with_prefix("HTTP/2 ", Some(&line)))?; if status_str.len() < 3 { return Err(other_err(format!("HTTP line too short: {line:?}"))); } let status = u32::from_str(&status_str[..3]) .map_err(|_| other_err(format!("Bad HTTP status code: {line:?}")))?; let mut content_type = String::new(); let mut location = None; loop { let mut line = String::new(); raw.read_line(&mut line)?; if line == "\r\n" { break; } if let Ok(header_val) = expect_line_with_prefix_ignore_case("Content-Type: ", Some(&line)) { content_type = header_val.trim().into(); } if let Ok(header_val) = expect_line_with_prefix_ignore_case("Location: ", Some(&line)) { location = Some(header_val.trim().into()); } } Ok(HttpResponse { status, content_type, location, data: raw.into(), }) } } impl std::fmt::Debug for HttpResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("HttpResponse") .field("status", &self.status) .field("content_type", &self.content_type) .field("location", &self.location) .field("data", &String::from_utf8_lossy(&self.data)) .finish() } } fn auth_header() -> io::Result<String> { let token = std::env::var("ACTIONS_RUNTIME_TOKEN") .map_err(|_| other_err("env-var ACTIONS_RUNTIME_TOKEN must be set"))?; Ok(format!("Authorization: Bearer {token}")) } pub fn raw_get(url: &str) -> io::Result<HttpResponse> { HttpResponse::parse(run_cmd_stdout( Command::new("curl").arg("-sSi").arg(url), None, )?) } pub fn raw_get_ok(url: &str) -> io::Result<HttpResponse> { let response = raw_get(url)?; if !status_ok(response.status) { return Err(other_err(format!( "HTTP request to {url} failed: {response:?}" ))); } Ok(response) } pub fn api_post(url: &str, content: Option<&Content>) -> io::Result<HttpResponse> { let mut cmd = Command::new("curl"); cmd.arg("-sSi"); cmd.arg("-X").arg("POST"); cmd.arg("-H").arg(auth_header()?); cmd.arg("-H") .arg("Accept: application/json;api-version=6.0-preview.1"); if let Some(content) = content { cmd.arg("-H") .arg(format!("Content-Type: {}", content.mime_type)); cmd.arg("--data-binary").arg("@-"); cmd.arg(url); HttpResponse::parse(run_cmd_stdout(&mut cmd, Some(&content.data))?) } else { cmd.arg(url); HttpResponse::parse(run_cmd_stdout(&mut cmd, None)?) } } pub fn api_post_ok(url: &str, content: Option<&Content>) -> io::Result<HttpResponse> { let response = api_post(url, content)?; if !status_ok(response.status) { return Err(other_err(format!( "HTTP request to {url} failed: {response:?}" ))); } Ok(response) } pub fn api_put(url: &str, content: &Content) -> io::Result<HttpResponse> { HttpResponse::parse(run_cmd_stdout( Command::new("curl") .arg("-sSi") .arg("-H") .arg(format!("Content-Type: {}", content.mime_type)) .arg("-H") .arg("x-ms-blob-type: BlockBlob") .arg("-H") .arg("x-ms-version: 2025-05-05") .arg("-X") .arg("PUT") .arg("--data-binary") .arg("@-") .arg(url), Some(&content.data), )?) } pub fn api_put_ok(url: &str, content: &Content) -> io::Result<HttpResponse> { let response = api_put(url, content)?; if !status_ok(response.status) { return Err(other_err(format!( "HTTP request to {url} failed: {response:?}" ))); } Ok(response) } fn status_ok(status: u32) -> bool { matches!(status, 200..=299) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/git.rs
ci-tools/size-history/src/git.rs
// Licensed under the Apache-2.0 license use std::{io, path::Path, process::Command}; use serde::{Deserialize, Serialize}; use crate::{ process::{run_cmd, run_cmd_stdout}, util::{bytes_to_string, expect_line, expect_line_with_prefix, other_err}, }; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct CommitInfo { pub id: String, pub author: String, pub title: String, } impl CommitInfo { fn parse_multiple(s: &str) -> io::Result<Vec<CommitInfo>> { let mut lines = s.lines(); let mut result = vec![]; 'outer: loop { let Some(line) = lines.next() else { break; }; let commit_id = expect_line_with_prefix("commit ", Some(line))?; let line = lines.next().unwrap_or_default(); // skip merge commit lines let line = if line.starts_with("Merge:") { lines.next() } else { Some(line) }; let author = expect_line_with_prefix("Author: ", line)?; expect_line("", lines.next())?; let mut title = expect_line_with_prefix(" ", lines.next())?.to_string(); 'inner: loop { let Some(line) = lines.next() else { result.push(CommitInfo { id: commit_id.into(), author: author.into(), title, }); break 'outer; }; if line.is_empty() { break 'inner; } title.push('\n'); title.push_str(expect_line_with_prefix(" ", Some(line))?); } result.push(CommitInfo { id: commit_id.into(), author: author.into(), title, }); } Ok(result) } } fn to_utf8(bytes: Vec<u8>) -> io::Result<String> { String::from_utf8(bytes).map_err(|_| other_err("git output is not utf-8")) } pub struct WorkTree<'a> { pub path: &'a Path, } impl<'a> WorkTree<'a> { pub fn new(path: &'a Path) -> io::Result<Self> { run_cmd( Command::new("git") .arg("worktree") .arg("add") .arg(path) .arg("HEAD"), )?; Ok(Self { path }) } pub fn is_log_linear(&self) -> io::Result<bool> { let stdout = to_utf8(run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("rev-list") .arg("--min-parents=2") .arg("--count") .arg("HEAD"), None, )?)?; Ok(stdout.trim() == "0") } pub fn commit_log(&self) -> io::Result<Vec<CommitInfo>> { CommitInfo::parse_multiple(&bytes_to_string(run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("log") .arg("--pretty=short") .arg("--decorate=no"), None, )?)?) } pub fn checkout(&self, commit_id: &str) -> io::Result<()> { run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("checkout") .arg("--no-recurse-submodule") .arg("--quiet") .arg(commit_id), None, )?; Ok(()) } pub fn submodule_update(&self) -> io::Result<()> { run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("submodule") .arg("update"), None, )?; Ok(()) } pub fn head_commit_id(&self) -> io::Result<String> { Ok(to_utf8(run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("rev-parse") .arg("HEAD"), None, )?)? .trim() .into()) } pub fn reset_hard(&self, commit_id: &str) -> io::Result<()> { run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("reset") .arg("--hard") .arg(commit_id), None, )?; Ok(()) } pub fn set_fs_contents(&self, commit_id: &str) -> io::Result<()> { run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("checkout") .arg(commit_id) .arg("--") .arg("."), None, )?; Ok(()) } pub fn commit(&self, message: &str) -> io::Result<()> { run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("commit") .arg("-a") .arg("-m") .arg(message), None, )?; Ok(()) } pub fn is_ancestor(&self, possible_ancestor: &str, commit: &str) -> io::Result<bool> { Ok(Command::new("git") .current_dir(self.path) .arg("merge-base") .arg("--is-ancestor") .arg(possible_ancestor) .arg(commit) .status()? .code() == Some(0)) } pub fn merge_log(&self) -> io::Result<Vec<Vec<String>>> { let stdout = to_utf8(run_cmd_stdout( Command::new("git") .current_dir(self.path) .arg("log") .arg("--merges") .arg("--pretty=%P"), None, )?)?; let mut result = vec![]; for line in stdout.lines() { let parents: Vec<String> = line.split(' ').map(|s| s.to_string()).collect(); if !parents.is_empty() { result.push(parents); } } Ok(result) } } impl Drop for WorkTree<'_> { fn drop(&mut self) { let _ = run_cmd( Command::new("git") .arg("worktree") .arg("remove") .arg(self.path), ); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_commit_info_parse() { let text = r#"commit e1b1e3c566b6bd7cdef0310dc88480034f0aa29f Author: Vishal Mhatre <38512878+mhatrevi@users.noreply.github.com> [fix] Vendor signature should not include owner signed data (#319) commit bd306c4809f54426a357ff01507ef660291e2b91 Author: Kor Nielsen <kor@google.com> Remove RUSTFLAGS from legacy ROM makefile. (#318) Multiline title "#; assert_eq!( CommitInfo::parse_multiple(text).unwrap(), vec![ CommitInfo { id: "e1b1e3c566b6bd7cdef0310dc88480034f0aa29f".into(), author: "Vishal Mhatre <38512878+mhatrevi@users.noreply.github.com>".into(), title: "[fix] Vendor signature should not include owner signed data (#319)" .into() }, CommitInfo { id: "bd306c4809f54426a357ff01507ef660291e2b91".into(), author: "Kor Nielsen <kor@google.com>".into(), title: "Remove RUSTFLAGS from legacy ROM makefile. (#318)\nMultiline title" .into() } ] ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/cache_gha.rs
ci-tools/size-history/src/cache_gha.rs
// Licensed under the Apache-2.0 license use ghac::v1::{ self as ghac_types, CreateCacheEntryResponse, FinalizeCacheEntryUploadResponse, GetCacheEntryDownloadUrlResponse, }; use prost::Message; use crate::{ http::{self, Content}, util::{hex, other_err}, Cache, }; // The server complains with an unhelpful message if VERSION is not a hex string const VERSION: &str = "a02f6dd76ad9bbe075065ed95abff21f02c1789ecbdbf8753bc823b0be6d99b3"; pub struct GithubActionCache { prefix: String, } impl GithubActionCache { pub fn new() -> std::io::Result<Self> { let wrap_err = |_| other_err("ACTIONS_RESULTS_URL environment variable not set".to_string()); let prefix = format!( "{}twirp/github.actions.results.api.v1.CacheService", std::env::var("ACTIONS_RESULTS_URL").map_err(wrap_err)? ); println!("Using GithubActionCache prefix {prefix:?}"); Ok(Self { prefix }) } } impl Cache for GithubActionCache { fn set(&self, key: &str, val: &[u8]) -> std::io::Result<()> { let url_key = format_key(key); let request = ghac_types::CreateCacheEntryRequest { key: url_key.clone(), version: VERSION.into(), metadata: None, }; let content = Content::protobuf(request.encode_to_vec()); let body = Some(&content); let response = http::api_post_ok(&format!("{}/CreateCacheEntry", self.prefix), body)?; let response: ghac_types::CreateCacheEntryResponse = CreateCacheEntryResponse::decode(response.data.as_ref())?; if !response.ok { return Err(other_err(format!( "Unable to create cache entry for {url_key:?}" ))); } let cache_url = response.signed_upload_url; http::api_put_ok(&cache_url, &Content::octet_stream(val))?; let request = ghac_types::FinalizeCacheEntryUploadRequest { key: url_key.clone(), version: VERSION.into(), size_bytes: val.len() as i64, metadata: None, }; let content = Content::protobuf(request.encode_to_vec()); let body = Some(&content); let response = http::api_post_ok(&format!("{}/FinalizeCacheEntryUpload", self.prefix), body)?; let response: ghac_types::FinalizeCacheEntryUploadResponse = FinalizeCacheEntryUploadResponse::decode(response.data.as_ref())?; if !response.ok { return Err(other_err(format!( "Unable to finalize cache upload for {url_key:?}" ))); } Ok(()) } fn get(&self, key: &str) -> std::io::Result<Option<Vec<u8>>> { let url_key = format_key(key); let request = ghac_types::GetCacheEntryDownloadUrlRequest { key: url_key.clone(), version: VERSION.into(), metadata: None, restore_keys: vec![], }; let content = Content::protobuf(request.encode_to_vec()); let body = Some(&content); let response = http::api_post_ok(&format!("{}/GetCacheEntryDownloadURL", self.prefix), body)?; let response: GetCacheEntryDownloadUrlResponse = GetCacheEntryDownloadUrlResponse::decode(response.data.as_ref())?; if !response.ok { return Ok(None); } if response.matched_key != url_key { return Err(other_err(format!( "Expected key {url_key:?}, was {:?}", response.matched_key ))); } let url = &response.signed_download_url; let response = http::raw_get_ok(url)?; Ok(Some(response.data)) } } fn format_key(key: &str) -> String { format!("size-history-{}", hex(key.as_bytes())) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/util.rs
ci-tools/size-history/src/util.rs
// Licensed under the Apache-2.0 license use std::io; pub fn expect_line(expected_val: &str, line: Option<&str>) -> io::Result<()> { if let Some(line) = line { if line == expected_val { return Ok(()); } } Err(io::Error::new( io::ErrorKind::Other, format!("Expected line with contents {expected_val:?}; was {line:?}"), )) } pub fn expect_line_with_prefix<'a>(prefix: &str, line: Option<&'a str>) -> io::Result<&'a str> { if let Some(line) = line { if let Some(stripped) = line.strip_prefix(prefix) { return Ok(stripped); } }; Err(io::Error::new( io::ErrorKind::Other, format!("Expected line with prefix {prefix:?}; was {line:?}"), )) } pub fn expect_line_with_prefix_ignore_case<'a>( prefix: &str, line: Option<&'a str>, ) -> io::Result<&'a str> { if let Some(line) = line { if let Some(line_prefix) = line.get(..prefix.len()) { if line_prefix.eq_ignore_ascii_case(prefix) { return Ok(&line[prefix.len()..]); } } }; Err(io::Error::new( io::ErrorKind::Other, format!("Expected line with prefix {prefix:?}; was {line:?}"), )) } pub fn hex(bytes: &[u8]) -> String { use std::fmt::Write; let mut result = String::new(); for b in bytes { write!(&mut result, "{:02x}", b).unwrap(); } result } pub fn bytes_to_string(vec: Vec<u8>) -> io::Result<String> { String::from_utf8(vec).map_err(other_err) } pub fn other_err(e: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> io::Error { io::Error::new(io::ErrorKind::Other, e) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/main.rs
ci-tools/size-history/src/main.rs
// Licensed under the Apache-2.0 license use std::{ env::{self}, fs, io, path::Path, }; use caliptra_builder::{elf_size, firmware, FwId}; use serde::{Deserialize, Serialize}; mod cache; mod cache_gha; mod git; mod html; mod http; mod process; mod util; use crate::cache::{Cache, FsCache}; use crate::{cache_gha::GithubActionCache, util::other_err}; // Increment with non-backwards-compatible changes are made to the cache record // format const CACHE_FORMAT_VERSION: &str = "v2"; #[derive(Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize)] struct Sizes { rom_size_with_uart: Option<u64>, rom_size_prod: Option<u64>, fmc_size_with_uart: Option<u64>, app_size_with_uart: Option<u64>, } impl Sizes { fn update_from(&mut self, other: &Sizes) { self.rom_size_with_uart = other.rom_size_with_uart.or(self.rom_size_with_uart); self.rom_size_prod = other.rom_size_prod.or(self.rom_size_prod); self.fmc_size_with_uart = other.fmc_size_with_uart.or(self.fmc_size_with_uart); self.app_size_with_uart = other.app_size_with_uart.or(self.app_size_with_uart); } } #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] struct SizeRecord { commit: git::CommitInfo, sizes: Sizes, } fn main() { if let Err(e) = real_main() { println!("Fatal Error: {e}"); std::process::exit(1); } } fn real_main() -> io::Result<()> { let cache = GithubActionCache::new().map(box_cache).or_else(|e| { let fs_cache_path = "/tmp/caliptra-size-cache"; println!( "Unable to create github action cache: {e}; using fs-cache instead at {fs_cache_path}" ); FsCache::new(fs_cache_path.into()).map(box_cache) })?; let worktree = git::WorkTree::new(Path::new("/tmp/caliptra-size-history-wt"))?; let head_commit = worktree.head_commit_id()?; let is_pr = env::var("EVENT_NAME").is_ok_and(|name| name == "pull_request") && env::var("PR_BASE_COMMIT").is_ok(); // require linear history for PRs; non-linear is OK for main branches if is_pr && !worktree.is_log_linear()? { println!("git history is not linear; attempting to squash PR"); let (Ok(pull_request_title), Ok(base_ref)) = (env::var("PR_TITLE"), env::var("PR_BASE_COMMIT")) else { return Err(other_err("cannot attempt squash outside of a PR")); }; let mut rebase_onto: String = base_ref; for merge_parents in worktree.merge_log()? { for parent in merge_parents { if worktree.is_ancestor(&parent, "remotes/origin/main")? && !worktree.is_ancestor(&parent, &rebase_onto)? { println!( "Found more recent merge from main; will rebase onto {}", parent ); rebase_onto = parent; } } } println!("Resetting to {}", rebase_onto); worktree.reset_hard(&rebase_onto)?; println!("Set fs contents to {}", head_commit); worktree.set_fs_contents(&head_commit)?; println!("Committing squashed commit {pull_request_title:?}"); worktree.commit(&pull_request_title)?; // we can't guarantee linear history even after squashing, so we can't check here } let git_commits = worktree.commit_log()?; env::set_current_dir(worktree.path)?; let mut records = vec![]; let mut cached_commit = None; for commit in git_commits.iter() { match cache.get(&format_cache_key(&commit.id)) { Ok(Some(cached_records)) => { if let Ok(cached_records) = serde_json::from_slice::<Vec<SizeRecord>>(&cached_records) { println!("Found cache entry for remaining commits at {}", commit.id); records.extend(cached_records); cached_commit = Some(commit.id.clone()); break; } else { println!( "Error parsing cache entry {:?}", String::from_utf8_lossy(&cached_records) ); } } Ok(None) => {} // not found Err(e) => println!("Error reading from cache: {e}"), } println!( "Building firmware at commit {}: {}", commit.id, commit.title ); worktree.checkout(&commit.id)?; worktree.submodule_update()?; records.push(SizeRecord { commit: commit.clone(), sizes: compute_size(&worktree, &commit.id), }); } for (i, record) in records.iter().enumerate() { if Some(&record.commit.id) == cached_commit.as_ref() { break; } if let Err(e) = cache.set( &format_cache_key(&record.commit.id), &serde_json::to_vec(&records[i..]).unwrap(), ) { println!( "Unable to write to cache for commit {}: {e}", record.commit.id ); } } let html = html::format_records(&records)?; if let Ok(file) = env::var("GITHUB_STEP_SUMMARY") { fs::write(file, &html)?; } else { println!("{html}"); } Ok(()) } fn compute_size(worktree: &git::WorkTree, commit_id: &str) -> Sizes { // TODO: consider using caliptra_builder from the same repo as the firmware let fwid_elf_size = |fwid: &FwId| -> io::Result<u64> { let workspace_dir = Some(worktree.path); let elf_bytes = caliptra_builder::build_firmware_elf_uncached(workspace_dir, fwid)?; elf_size(&elf_bytes) }; let fwid_elf_size_or_none = |fwid: &FwId| -> Option<u64> { match fwid_elf_size(fwid) { Ok(result) => Some(result), Err(err) => { println!("Error building commit {}: {err}", commit_id); None } } }; Sizes { rom_size_with_uart: fwid_elf_size_or_none(&firmware::ROM_WITH_UART), rom_size_prod: fwid_elf_size_or_none(&firmware::ROM), fmc_size_with_uart: fwid_elf_size_or_none(&firmware::FMC_WITH_UART), app_size_with_uart: fwid_elf_size_or_none(&firmware::APP_WITH_UART), } } fn box_cache(val: impl Cache + 'static) -> Box<dyn Cache> { Box::new(val) } fn format_cache_key(commit: &str) -> String { format!("{CACHE_FORMAT_VERSION}-{commit}") }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/size-history/src/cache.rs
ci-tools/size-history/src/cache.rs
// Licensed under the Apache-2.0 license use std::{fs, io, path::PathBuf}; use crate::util::hex; pub trait Cache { fn set(&self, key: &str, val: &[u8]) -> io::Result<()>; fn get(&self, key: &str) -> io::Result<Option<Vec<u8>>>; } pub struct FsCache { dir: PathBuf, } impl FsCache { pub fn new(dir: PathBuf) -> io::Result<Self> { fs::create_dir_all(&dir)?; Ok(Self { dir }) } } impl Cache for FsCache { fn set(&self, key: &str, val: &[u8]) -> io::Result<()> { fs::write(self.dir.join(hex(key.as_bytes())), val) } fn get(&self, key: &str) -> io::Result<Option<Vec<u8>>> { match fs::read(self.dir.join(hex(key.as_bytes()))) { Ok(data) => Ok(Some(data)), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e), } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/bitstream-downloader/src/lib.rs
ci-tools/bitstream-downloader/src/lib.rs
// Licensed under the Apache-2.0 license use std::fs; use std::io; use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; use serde::Deserialize; use sha2::{Digest, Sha256}; #[derive(Debug, Deserialize)] pub struct Bitstream { pub name: String, pub url: String, pub hash: String, pub caliptra_variant: String, } #[derive(Debug, Deserialize)] pub struct Manifest { pub bitstream: Bitstream, } pub fn download_bitstream(manifest_path: &Path) -> Result<PathBuf> { let manifest_content = fs::read_to_string(manifest_path) .context("failed to read manifest file")?; let manifest: Manifest = toml::from_str(&manifest_content) .context("failed to parse manifest TOML")?; println!("Downloading bitstream: {}", manifest.bitstream.name); println!("URL: {}", manifest.bitstream.url); let response = reqwest::blocking::get(&manifest.bitstream.url) .context("failed to make request")?; let mut content = io::Cursor::new(response.bytes().context("failed to read response bytes")?); let mut hasher = Sha256::new(); io::copy(&mut content, &mut hasher).context("failed to read content for hashing")?; let calculated_hash = hasher.finalize(); let calculated_hash_hex = hex::encode(calculated_hash); println!("Expected hash: {}", manifest.bitstream.hash); println!("Calculated hash: {}", calculated_hash_hex); if calculated_hash_hex == manifest.bitstream.hash { println!("Hash verification successful!"); } else { bail!( "hash mismatch expected: {}, got: {}", manifest.bitstream.hash, calculated_hash_hex ); } let output_filename = format!("{}.pdi", manifest.bitstream.caliptra_variant); let output_path = PathBuf::from(&output_filename); let mut file = fs::File::create(&output_path).context("failed to create output file")?; content.set_position(0); io::copy(&mut content, &mut file).context("failed to write output file")?; println!("PDI saved to: {}", output_filename); Ok(output_path) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/bitstream-downloader/src/main.rs
ci-tools/bitstream-downloader/src/main.rs
// Licensed under the Apache-2.0 license use std::path::PathBuf; use anyhow::Result; use clap::Parser; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Cli { /// Path to the bitstream manifest #[arg(long = "bitstream-manifest", value_name = "FILE")] bitstream_manifest: PathBuf, } fn main() -> Result<()> { let cli = Cli::parse(); caliptra_bitstream_downloader::download_bitstream(&cli.bitstream_manifest)?; Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/file-header-fix/src/main.rs
ci-tools/file-header-fix/src/main.rs
// Licensed under the Apache-2.0 license use std::{ fs::File, io::{BufRead, BufReader, Error, ErrorKind}, path::{Path, PathBuf}, }; const REQUIRED_TEXT: &str = "Licensed under the Apache-2.0 license"; const EXTENSIONS: &[&str] = &["rs", "h", "c", "cpp", "cc", "toml", "sh", "py", "ld", "go"]; const IGNORED_PATHS: &[&str] = &[ // BSD-licensed "./sw-emulator/compliance-test/target-files/link.ld", "./runtime/dpe", "./hw-latest/fpga/caliptra_build", "./hw/fpga/caliptra_build", "./hw/fpga/petalinux_project", "./hw/1.0/rtl", "./hw/latest/rtl", "./hw/latest/caliptra-ss", "./hw/latest/i3c-core-rtl", "./ci-tools/fpga-boss/image/mnt", "./ci-tools/fpga-image/out", ]; const IGNORED_DIRS: &[&str] = &[".git", "caliptra-rtl", "out", "target"]; fn add_path(path: &Path) -> impl Fn(Error) -> Error + Copy + '_ { move |e: Error| Error::new(e.kind(), format!("{path:?}: {e}")) } fn check_file_contents(path: &Path, contents: impl BufRead) -> Result<(), Error> { const N: usize = 3; let wrap_err = add_path(path); for line in contents.lines().take(N) { if line.map_err(wrap_err)?.contains(REQUIRED_TEXT) { return Ok(()); } } Err(Error::new( ErrorKind::Other, format!("File {path:?} doesn't contain {REQUIRED_TEXT:?} in the first {N} lines"), )) } fn check_file(path: &Path) -> Result<(), Error> { let wrap_err = add_path(path); check_file_contents(path, BufReader::new(File::open(path).map_err(wrap_err)?)) } fn fix_file(path: &Path) -> Result<(), Error> { let wrap_err = add_path(path); let mut contents = Vec::from(match path.extension().and_then(|s| s.to_str()) { Some("rs" | "h" | "c" | "cpp" | "cc" | "go") => format!("// {REQUIRED_TEXT}\n"), Some("toml" | "sh" | "py") => format!("# {REQUIRED_TEXT}\n"), Some("ld") => format!("/* {REQUIRED_TEXT} */\n"), other => { return Err(std::io::Error::new( ErrorKind::Other, format!("Unknown extension {other:?}"), )) } }); let mut prev_contents = std::fs::read(path).map_err(wrap_err)?; if prev_contents.first() != Some(&b'\n') { contents.push(b'\n'); } contents.append(&mut prev_contents); std::fs::write(path, contents)?; Ok(()) } fn find_files(dir: &Path, result: &mut Vec<PathBuf>) -> Result<(), Error> { let wrap_err = add_path(dir); for file in std::fs::read_dir(dir).map_err(wrap_err)? { let file = file.map_err(wrap_err)?; let file_path = &file.path(); let wrap_err = add_path(file_path); let file_type = file.file_type().map_err(wrap_err)?; if let Some(file_path) = file_path.to_str() { if IGNORED_PATHS.contains(&file_path) { continue; } } if file_type.is_dir() { if let Some(file_name) = file.file_name().to_str() { if IGNORED_DIRS.contains(&file_name) { continue; } } find_files(file_path, result)?; } if let Some(Some(extension)) = file.path().extension().map(|s| s.to_str()) { if file_type.is_file() && EXTENSIONS.contains(&extension) { result.push(file_path.into()); } } } Ok(()) } fn main() { let args: Vec<_> = std::env::args().skip(1).collect(); let pwd = Path::new("."); let check_only = if args == ["--check"] { true } else if args.is_empty() { false } else { println!("Usage: file-header-fix [--check]"); std::process::exit(1); }; let mut files = Vec::new(); find_files(pwd, &mut files).unwrap(); files.sort(); let mut failed = false; for file in files.iter() { if !check_only && check_file(file).is_err() { fix_file(file).unwrap(); } if let Err(e) = check_file(file) { println!("{e}"); failed = true; } } if failed { println!("To fix, run \"ci-tools/file-header-fix.sh\" from the repo root."); std::process::exit(2); } } #[cfg(test)] mod test { use crate::*; #[test] fn test_check_success() { check_file_contents( Path::new("foo/bar.rs"), "# Licensed under the Apache-2.0 license".as_bytes(), ) .unwrap(); check_file_contents( Path::new("foo/bar.rs"), "/*\n * Licensed under the Apache-2.0 license\n */".as_bytes(), ) .unwrap(); } #[test] fn test_check_failures() { assert_eq!( check_file_contents(Path::new("foo/bar.rs"), "int main()\n {\n // foobar\n".as_bytes()).unwrap_err().to_string(), "File \"foo/bar.rs\" doesn't contain \"Licensed under the Apache-2.0 license\" in the first 3 lines"); assert_eq!( check_file_contents(Path::new("bar/foo.sh"), "".as_bytes()).unwrap_err().to_string(), "File \"bar/foo.sh\" doesn't contain \"Licensed under the Apache-2.0 license\" in the first 3 lines"); let err = check_file_contents(Path::new("some/invalid_utf8_file"), [0x80].as_slice()) .unwrap_err(); assert_eq!(err.kind(), ErrorKind::InvalidData); assert!(err.to_string().contains("some/invalid_utf8_file")); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/file-header-fix/tests/integration_test.rs
ci-tools/file-header-fix/tests/integration_test.rs
// Licensed under the Apache-2.0 license use std::{ env::temp_dir, fs, path::{Path, PathBuf}, process::Stdio, }; const PROGRAM_BIN: &str = env!("CARGO_BIN_EXE_caliptra-file-header-fix"); #[test] fn test_usage() { let out = std::process::Command::new(PROGRAM_BIN) .arg("--help") .stderr(Stdio::inherit()) .output() .unwrap(); assert_eq!(out.status.code(), Some(1)); assert_eq!( std::str::from_utf8(&out.stdout), Ok("Usage: file-header-fix [--check]\n") ); } #[test] fn test_check_only_failure() { let tmp_dir = TmpDir::new("caliptra-file-header-fix-test-check-only-failure").unwrap(); tmp_dir.write("ignore.txt", "Hi!"); tmp_dir.write("scripts/foo.sh", "echo Hi\n"); tmp_dir.write("hello.rs", "// Licensed under the Apache-2.0 license.\n"); tmp_dir.write("foo.rs", "#![no_std]\n"); let out = std::process::Command::new(PROGRAM_BIN) .current_dir(&tmp_dir.0) .arg("--check") .stderr(Stdio::inherit()) .output() .unwrap(); assert_eq!(out.status.code(), Some(2)); assert_eq!(std::str::from_utf8(&out.stdout), Ok( "File \"./foo.rs\" doesn't contain \"Licensed under the Apache-2.0 license\" in the first 3 lines\n\ File \"./scripts/foo.sh\" doesn't contain \"Licensed under the Apache-2.0 license\" in the first 3 lines\n\ To fix, run \"ci-tools/file-header-fix.sh\" from the repo root.\n")); // Make sure it didn't rewrite assert_eq!(tmp_dir.read("foo.rs"), "#![no_std]\n"); } #[test] fn test_check_only_success() { let tmp_dir = TmpDir::new("caliptra-file-header-fix-test-check-only-success").unwrap(); tmp_dir.write("ignore.txt", "Hi!"); tmp_dir.write("scripts/foo.sh", "# Licensed under the Apache-2.0 license"); tmp_dir.write("hello.rs", "/* Licensed under the Apache-2.0 license.\n */"); tmp_dir.write("foo.rs", "// Licensed under the Apache-2.0 license"); let out = std::process::Command::new(PROGRAM_BIN) .current_dir(&tmp_dir.0) .arg("--check") .stderr(Stdio::inherit()) .output() .unwrap(); assert_eq!(std::str::from_utf8(&out.stdout), Ok("")); assert_eq!(out.status.code(), Some(0)); // Make sure it didn't rewrite assert_eq!( tmp_dir.read("hello.rs"), "/* Licensed under the Apache-2.0 license.\n */" ); } #[test] fn test_fix() { let tmp_dir = TmpDir::new("caliptra-file-header-fix-test").unwrap(); tmp_dir.write("ignore.txt", "Hi!"); tmp_dir.write("target/bar/foo.rs", "Ignore Me!"); tmp_dir.write("hello.rs", "/* Licensed under the Apache-2.0 license. */\n"); tmp_dir.write("foo.rs", "#![no_std]\n"); tmp_dir.write("main.rs", "\nfn main() {}\n"); tmp_dir.write("include/empty.h", ""); tmp_dir.write( "scripts/foo.sh", "# Licensed under the Fishy Proprietary License v6.66", ); let out = std::process::Command::new(PROGRAM_BIN) .current_dir(&tmp_dir.0) .stderr(Stdio::inherit()) .output() .unwrap(); assert_eq!(std::str::from_utf8(&out.stdout), Ok("")); assert_eq!(out.status.code(), Some(0)); // .txt should be ignored assert_eq!(tmp_dir.read("ignore.txt"), "Hi!"); // target/ directories should be ignored assert_eq!(tmp_dir.read("target/bar/foo.rs"), "Ignore Me!"); // formatting should not have been changed assert_eq!( tmp_dir.read("hello.rs"), "/* Licensed under the Apache-2.0 license. */\n" ); // License prepended with extra newline assert_eq!( tmp_dir.read("foo.rs"), "// Licensed under the Apache-2.0 license\n\ \n\ #![no_std]\n" ); // License prepended without extra newline assert_eq!( tmp_dir.read("main.rs"), "// Licensed under the Apache-2.0 license\n\ \n\ fn main() {}\n" ); assert_eq!( tmp_dir.read("include/empty.h"), "// Licensed under the Apache-2.0 license\n\n" ); // code reviewers should notice the file has two licenses assert_eq!(tmp_dir.read("scripts/foo.sh"), "# Licensed under the Apache-2.0 license\n\ \n\ # Licensed under the Fishy Proprietary License v6.66"); } struct TmpDir(pub PathBuf); impl TmpDir { fn new(name: &str) -> std::io::Result<Self> { let dir = temp_dir().join(name); fs::create_dir(&dir)?; Ok(Self(dir)) } fn read(&self, path: impl AsRef<Path>) -> String { std::fs::read_to_string(self.0.join(path)).unwrap() } fn write(&self, path: impl AsRef<Path>, contents: &str) { let path = self.0.join(path); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).unwrap(); } std::fs::write(path, contents).unwrap(); } } impl Drop for TmpDir { fn drop(&mut self) { fs::remove_dir_all(&self.0).ok(); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/test-matrix/src/html.rs
ci-tools/test-matrix/src/html.rs
// Licensed under the Apache-2.0 license use std::fmt::Write; use octocrab::models::workflows::Run; use serde::Serialize; use std::fmt::Debug; use tinytemplate::{format_unescaped, TinyTemplate}; use crate::{RunInfo, TestMatrix}; // These types are exposed to the HTML template: #[derive(Serialize)] struct TemplateContext<'a> { pub matrix: &'a TestMatrix, pub javascript: &'static str, pub style: &'static str, pub run: &'a Run, pub run_info: RunInfo, pub run_infos: Vec<MaybeSelected<&'a RunInfo>>, } /// Wraps any serializable with a struct with a "selected" field. Intended to be consumed by /// templates when there are list of items and one of them is special. #[derive(Debug, Serialize)] struct MaybeSelected<T: Serialize> { pub selected: bool, pub value: T, } impl<'a, T: Serialize + PartialEq> MaybeSelected<&'a T> { /// Wrap every item in `all`, setting the `selected` field to true for any items that are /// equal to `selected`. fn select(selected: &'a T, all: &'a [T]) -> Vec<Self> { let mut result = vec![]; for val in all { result.push(MaybeSelected { selected: *val == *selected, value: val, }); } result } } /// Generate HTML for a particular test run. pub fn format(run: &Run, toc: &[RunInfo], matrix: &TestMatrix) -> String { let mut tt = TinyTemplate::new(); tt.add_template("matrix", include_str!("html/matrix.html")) .unwrap(); tt.add_template("index", include_str!("html/index.html")) .unwrap(); tt.add_formatter("testcase_cell_style", |val, out| { let mut status = val .get("status") .and_then(|s| s.as_str()) .unwrap_or_default(); if status.is_empty() { status = "na"; } out.write_str(&status.to_ascii_lowercase())?; Ok(()) }); tt.add_formatter("format_unescaped", format_unescaped); tt.add_formatter("testcase_cell_text", |val, out| { let status = val.get("status").and_then(|s| s.as_str()); let duration = val .get("duration") .and_then(|d| d.as_number()) .and_then(|d| d.as_f64()); match (status, duration) { (Some("Passed"), Some(duration)) => write!(out, "{:.1}s", duration), (Some("Passed"), _) => write!(out, "PASS"), (Some("Failed"), _) => write!(out, "FAIL"), (Some("Ignored"), _) => write!(out, "SKIP"), _ => write!(out, "n/a"), }?; Ok(()) }); let this_run_info = RunInfo::from_run(run); tt.render( "index", &TemplateContext { matrix, javascript: include_str!("html/matrix.js"), style: include_str!("html/style.css"), run, run_info: this_run_info.clone(), run_infos: MaybeSelected::select(&this_run_info, toc), }, ) .unwrap() }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/test-matrix/src/junit.rs
ci-tools/test-matrix/src/junit.rs
// Licensed under the Apache-2.0 license use std::fmt::Write; use serde::Deserialize; use serde_xml_rs as serde_xml; use crate::TestCaseStatus; #[derive(Debug, Deserialize, PartialEq)] pub struct TestSuites { pub name: String, #[serde(default)] #[serde(rename = "testsuite")] pub test_suites: Vec<TestSuite>, } impl TestSuites { pub fn from_xml(xml: &str) -> Result<Self, serde_xml::Error> { serde_xml_rs::from_str(xml) } } #[derive(Debug, Deserialize, PartialEq)] pub struct TestSuite { pub name: String, #[serde(default)] #[serde(rename = "testcase")] pub test_cases: Vec<TestCase>, } #[derive(Debug, Deserialize, PartialEq)] pub struct Skipped { #[serde(default)] pub message: String, } #[derive(Debug, Deserialize, PartialEq)] pub struct Error { #[serde(rename = "type")] #[serde(default)] pub ty: String, #[serde(default)] pub message: String, } #[derive(Debug, Deserialize, PartialEq)] pub struct TestCase { pub name: String, pub time: f64, #[serde(rename = "system-out")] pub system_out: String, #[serde(rename = "system-err")] pub system_err: String, #[serde(default)] pub skipped: Option<Skipped>, #[serde(default)] #[serde(rename = "error")] pub errors: Vec<Error>, #[serde(default)] #[serde(rename = "failure")] pub failures: Vec<Error>, } impl TestCase { pub fn status(&self) -> TestCaseStatus { if self.errors.is_empty() && self.failures.is_empty() { if self.skipped.is_some() { // NOTE: nexttest doesn't seem to use this; ignored tests aren't // recorded in the XML at all (but are in the test metadata // JSON). TestCaseStatus::Ignored } else { TestCaseStatus::Passed } } else { TestCaseStatus::Failed } } pub fn output_truncated(&self) -> String { let mut result = String::new(); let label_output = !self.system_out.is_empty() && !self.system_err.is_empty(); if label_output { writeln!(&mut result, "stdout:").unwrap(); } write_truncated_output(&mut result, &self.system_out, 12288).unwrap(); if label_output { writeln!(&mut result, "\n\nstderr:").unwrap(); } write_truncated_output(&mut result, &self.system_err, 12288).unwrap(); result } } fn write_truncated_output( mut w: impl std::fmt::Write, s: &str, max_size: usize, ) -> std::fmt::Result { if s.len() > max_size { writeln!(w, "Truncated {} bytes from beginning", s.len() - max_size)?; w.write_str(&s[(s.len() - max_size)..]) } else { w.write_str(s) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/test-matrix/src/main.rs
ci-tools/test-matrix/src/main.rs
// Licensed under the Apache-2.0 license use std::{ collections::BTreeMap, error::Error, io::{Cursor, Read}, path::Path, }; use nextest_metadata::TestListSummary; use octocrab::{ etag::Etagged, models::workflows::Run, params::actions::ArchiveFormat, Octocrab, Page, }; use serde::Serialize; use zip::result::ZipError; mod html; mod junit; async fn all_items<T: for<'de> serde::de::Deserialize<'de>>( octocrab: &Octocrab, etagged: Etagged<Page<T>>, ) -> Result<Vec<T>, octocrab::Error> { let mut result = vec![]; let Some(mut page) = etagged.value else { panic!("etagged.value was not set; using api incorrectly?"); }; loop { result.extend(page.items); page = match octocrab.get_page(&page.next).await? { Some(next_page) => next_page, None => break, } } Ok(result) } fn zip_extract_file( zip: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, ) -> Result<Vec<u8>, ZipError> { let mut result = vec![]; zip.by_name(name)?.read_to_end(&mut result)?; Ok(result) } #[derive(Debug, serde::Serialize)] pub struct TestMatrix { pub rows: Vec<TestSuite>, pub columns: Vec<String>, } fn get_at_index_mut<T: Default>(vec: &mut Vec<T>, index: usize) -> &mut T { if index >= vec.len() { vec.resize_with(index + 1, Default::default); } &mut vec[index] } #[derive(Debug, serde::Serialize)] pub struct TestSuite { pub name: String, pub rows: Vec<TestCaseRow>, } impl TestMatrix { fn new(mut runs: Vec<TestRun>) -> Result<Self, Box<dyn Error + 'static>> { runs.sort_by(|a, b| a.name.cmp(&b.name)); let mut columns = vec![]; let mut row_map: BTreeMap<String, BTreeMap<String, TestCaseRow>> = BTreeMap::new(); let runs_len = runs.len(); for (run_index, run) in runs.into_iter().enumerate() { columns.push(run.name); for (suite_name, suite) in run.test_list.rust_suites { let suite_map = row_map.entry(suite_name.to_string()).or_default(); for (test_case_name, test_case) in suite.test_cases { let row = suite_map .entry(test_case_name.clone()) .or_insert_with(|| TestCaseRow { name: test_case_name, cells: vec![None; runs_len], }); *get_at_index_mut(&mut row.cells, run_index) = Some(TestCaseCell { status: if test_case.ignored { TestCaseStatus::Ignored } else { TestCaseStatus::Unknown }, output: Default::default(), duration: Default::default(), }); } } for suite in run.junit_suites.test_suites { let suite_map = row_map .get_mut(&suite.name) .ok_or_else(|| format!("Unknown suite in junit file: {}", suite.name))?; for test_case in suite.test_cases { let row = suite_map.get_mut(&test_case.name).ok_or_else(|| { format!("Unknown test-case in junit file: {}", test_case.name) })?; let cell = get_at_index_mut(&mut row.cells, run_index) .as_mut() .ok_or_else(|| { format!( "Unknown test-case for this run in junit file: {}", test_case.name ) })?; cell.status = test_case.status(); cell.output = test_case.output_truncated(); cell.duration = test_case.time; } } } let rows: Vec<_> = row_map .into_iter() .map(|(name, rows)| TestSuite { name, rows: rows.into_values().collect(), }) .collect(); Ok(Self { rows, columns }) } } #[derive(Debug, Default, serde::Serialize)] pub struct TestCaseRow { pub name: String, pub cells: Vec<Option<TestCaseCell>>, } #[derive(Copy, Clone, Debug, serde::Serialize)] pub enum TestCaseStatus { Passed, Failed, Ignored, Unknown, } #[derive(Clone, Debug, serde::Serialize)] pub struct TestCaseCell { pub status: TestCaseStatus, pub output: String, pub duration: f64, } struct TestRun { name: String, // The metadata about the tests to run (includes tests that were ignored) test_list: TestListSummary, // The results of the tests that were run (doesn't include ignored tests) junit_suites: junit::TestSuites, } impl TestRun { fn from_zip_bytes(name: String, bytes: &[u8]) -> Result<TestRun, Box<dyn Error>> { let mut archive = zip::ZipArchive::new(Cursor::new(bytes))?; let json = zip_extract_file(&mut archive, "nextest-list.json")?; let json = String::from_utf8(json)?; let test_list = nextest_metadata::TestListSummary::parse_json(json)?; let junit_xml = String::from_utf8(zip_extract_file(&mut archive, "junit.xml")?)?; let junit_suites = junit::TestSuites::from_xml(&junit_xml)?; Ok(TestRun { name, test_list, junit_suites, }) } } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct RunInfo { pub id: String, pub display_name: String, } impl RunInfo { fn from_run(run: &Run) -> Self { RunInfo { id: run.created_at.format("%F-%H%M%S").to_string(), display_name: run.created_at.format("%F %H:%M:%S").to_string(), } } } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { let www_out = std::env::var("CPTRA_WWW_OUT") .expect("CPTRA_WWW_OUT env variable is required (directory to write html)"); let token = std::env::var("GITHUB_TOKEN").expect("GITHUB_TOKEN env variable is required"); const ORG: &str = "chipsalliance"; const REPO: &str = "caliptra-sw"; let octocrab = Octocrab::builder().personal_token(token).build()?; let release_runs = octocrab .workflows(ORG, REPO) .list_runs("nightly-release.yml") .branch("main") .send() .await?; const NUM_RUNS: usize = 6; let run_infos: Vec<RunInfo> = release_runs .items .iter() .take(NUM_RUNS) .map(RunInfo::from_run) .collect(); for (index, run) in release_runs.into_iter().take(NUM_RUNS).enumerate() { let artifacts = all_items( &octocrab, octocrab .actions() .list_workflow_run_artifacts(ORG, REPO, run.id) .send() .await?, ) .await?; let mut test_runs = vec![]; for artifact in artifacts { if artifact.name.starts_with("caliptra-test-results") { let test_run_name = &artifact.name["caliptra-test-results-".len()..]; let artifact_zip = octocrab .actions() .download_artifact(ORG, REPO, artifact.id, ArchiveFormat::Zip) .await?; test_runs .push(TestRun::from_zip_bytes(test_run_name.into(), &artifact_zip).unwrap()); } } let matrix = TestMatrix::new(test_runs).unwrap(); let html = html::format(&run, &run_infos, &matrix); std::fs::write( Path::new(&www_out).join(format!("run-{}.html", RunInfo::from_run(&run).id)), &html, ) .unwrap(); if index == 0 { std::fs::write(Path::new(&www_out).join("index.html"), &html).unwrap(); } } Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ci-tools/test-printer/src/main.rs
ci-tools/test-printer/src/main.rs
// Licensed under the Apache-2.0 license use serde::Deserialize; use std::fs; use clap::Parser; #[derive(Parser)] #[clap(author, version, about, long_about = None)] struct Args { /// The path to the junit.xml file #[clap(short, long)] xml_path: String, } #[derive(Debug, Deserialize, Default)] struct TestSuites { #[serde(rename = "testsuite", default)] testsuites: Vec<TestSuite>, } #[derive(Debug, Deserialize, Default)] struct TestSuite { #[serde(rename = "@name", default)] name: String, #[serde(rename = "testcase", default)] testcases: Vec<TestCase>, } #[derive(Debug, Deserialize, Default)] struct TestCase { #[serde(rename = "@name", default)] name: String, #[serde(rename = "failure", default)] failure: Option<Failure>, #[serde(rename = "rerunFailure", default)] rerun_failures: Vec<RerunFailure>, } #[derive(Debug, Deserialize, Default)] struct Failure {} #[derive(Debug, Deserialize, Default)] struct RerunFailure {} enum TestStatus { Passed, Failed, Retried, } fn main() { let args = Args::parse(); let xml = fs::read_to_string(args.xml_path).expect("Unable to read junit.xml"); let testsuites: TestSuites = quick_xml::de::from_str(&xml).expect("Unable to parse XML"); println!("| Test Suite | Test | Status |"); println!("|---|---|---|"); for suite in testsuites.testsuites { for case in suite.testcases { let status = if case.failure.is_some() { TestStatus::Failed } else if !case.rerun_failures.is_empty() { TestStatus::Retried } else { TestStatus::Passed }; let status_icon = match status { TestStatus::Passed => "✅", TestStatus::Failed => "❌", TestStatus::Retried => "🔁", }; println!("| {} | {} | {} |", suite.name, case.name, status_icon); } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/src/lib.rs
ureg/src/lib.rs
/*++ Licensed under the Apache-2.0 license. --*/ //! # ureg register abstraction //! //! This crate contains traits and types used by MMIO register-access code //! generated by [`ureg-codegen`]. #![no_std] #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] mod opt_riscv; use core::{default::Default, marker::PhantomData, mem::MaybeUninit}; #[derive(Copy, Clone, Eq, PartialEq)] pub enum UintType { U8, U16, U32, U64, } pub trait Uint: Clone + Copy + Default + TryInto<u32> + TryFrom<u32> + private::Sealed { const TYPE: UintType; } mod private { pub trait Sealed {} } impl Uint for u8 { const TYPE: UintType = UintType::U8; } impl private::Sealed for u8 {} impl Uint for u16 { const TYPE: UintType = UintType::U16; } impl private::Sealed for u16 {} impl Uint for u32 { const TYPE: UintType = UintType::U32; } impl private::Sealed for u32 {} impl Uint for u64 { const TYPE: UintType = UintType::U64; } impl private::Sealed for u64 {} /// The root trait for metadata describing a MMIO register. /// /// Implementors of this trait should also consider implementing /// [`ReadableReg`], [`ReadableReg`], and [`ResettableReg`]. pub trait RegType { /// The raw type of the register: typically `u8`, `u16`, `u32`, or `u64`. type Raw: Uint; } /// A trait used to describe an MMIO register with a reset value. pub trait ResettableReg: RegType { /// The reset value of the register /// /// This is the value the register is expected to have after the peripheral /// has been reset. It is used as the initial value of the first closure /// parameter to [`RegRef::write`]. const RESET_VAL: Self::Raw; } /// A trait used to describe an MMIO register that can be read from. pub trait ReadableReg: RegType { type ReadVal: Copy + From<Self::Raw>; } /// A trait used to describe an MMIO register that can be written to. pub trait WritableReg: RegType { type WriteVal: Copy + From<Self::Raw> + Into<Self::Raw>; } /// A convenient RegType implementation intended for read-only 32-bit fields. /// /// The code-generator may use this type to cut down on the number of RegType /// implementations created, making it easier for the compiler to deduplicate /// generic functions that act on registers with the same field layout. pub struct ReadOnlyReg32<TReadVal: Copy + From<u32>> { phantom: PhantomData<TReadVal>, } impl<TReadVal: Copy + From<u32>> RegType for ReadOnlyReg32<TReadVal> { type Raw = u32; } impl<TReadVal: Copy + From<u32>> ReadableReg for ReadOnlyReg32<TReadVal> { type ReadVal = TReadVal; } /// A convenient RegType implementation intended for write-only 32-bit fields. /// /// The code-generator may use this type to cut down on the number of RegType /// implementations created, making it easier for the compiler to deduplicate /// generic functions that act on registers with the same field layout. pub struct WriteOnlyReg32<const RESET_VAL: u32, TWriteVal: Copy + From<u32> + Into<u32>> { phantom: PhantomData<TWriteVal>, } impl<const RESET_VAL: u32, TWriteVal: Copy + From<u32> + Into<u32>> RegType for WriteOnlyReg32<RESET_VAL, TWriteVal> { type Raw = u32; } impl<const RESET_VAL: u32, TWriteVal: Copy + From<u32> + Into<u32>> ResettableReg for WriteOnlyReg32<RESET_VAL, TWriteVal> { const RESET_VAL: Self::Raw = RESET_VAL; } impl<const RESET_VAL: u32, TWriteVal: Copy + From<u32> + Into<u32>> WritableReg for WriteOnlyReg32<RESET_VAL, TWriteVal> { type WriteVal = TWriteVal; } /// A convenient RegType implementation intended for read-write 32-bit fields. /// /// The code-generator may use this type to cut down on the number of RegType /// implementations created, making it easier for the compiler to deduplicate /// generic functions that act on registers with the same field layout. pub struct ReadWriteReg32< const RESET_VAL: u32, TReadVal: Copy + From<u32>, TWriteVal: Copy + From<u32> + Into<u32>, > { phantom: PhantomData<(TReadVal, TWriteVal)>, } impl<const RESET_VAL: u32, TReadVal: Copy + From<u32>, TWriteVal: Copy + From<u32> + Into<u32>> RegType for ReadWriteReg32<RESET_VAL, TReadVal, TWriteVal> { type Raw = u32; } impl<const RESET_VAL: u32, TReadVal: Copy + From<u32>, TWriteVal: Copy + From<u32> + Into<u32>> ReadableReg for ReadWriteReg32<RESET_VAL, TReadVal, TWriteVal> { type ReadVal = TReadVal; } impl<const RESET_VAL: u32, TReadVal: Copy + From<u32>, TWriteVal: Copy + From<u32> + Into<u32>> ResettableReg for ReadWriteReg32<RESET_VAL, TReadVal, TWriteVal> { const RESET_VAL: Self::Raw = RESET_VAL; } impl<const RESET_VAL: u32, TReadVal: Copy + From<u32>, TWriteVal: Copy + From<u32> + Into<u32>> WritableReg for ReadWriteReg32<RESET_VAL, TReadVal, TWriteVal> { type WriteVal = TWriteVal; } /// A trait for performing volatile reads from a pointer. On real /// systems, [`RealMmio`] is typically used to implement this trait, but other /// implementations may be used for testing or simulation. pub trait Mmio: Sized { /// Performs (or simulates) a volatile read from `src` and returns the read value. /// /// # Safety /// /// Same as [`core::ptr::read_volatile`]. unsafe fn read_volatile<T: Uint>(&self, src: *const T) -> T; /// # Safety /// /// Caller must ensure that the safety requirements of /// [`core::ptr::read_volatile`] are met for every location between src and /// `dst.add(LEN)`, and that src.add(LEN) does not wrap around the address /// space. /// /// Also, the caller must ensure that the safety requirements of /// [`core::ptr::write`] are met for every location between dst and /// `dst.add(LEN)`, and that dst.add(LEN) does not wrap around the address /// space. unsafe fn read_volatile_array<const LEN: usize, T: Uint>(&self, dst: *mut T, src: *mut T) { read_volatile_slice(self, dst, src, LEN); } } /// A trait for performing volatile writes (or reads via Mmio supertrait) to/from a /// pointer. On real systems, [`RealMmioMut`] is typically used to implement /// this trait, but other implementations may be used for testing or simulation. pub trait MmioMut: Mmio { /// Performs (or simulates) a volatile write of `src` to `dst`. /// /// # Safety /// /// Same as [`core::ptr::write_volatile`]. unsafe fn write_volatile<T: Uint>(&self, dst: *mut T, src: T); /// # Safety /// /// Caller must ensure that the safety requirements of /// [`core::ptr::write_volatile`] are met for every location between dst and /// `dst.add(LEN)`, and that dst.add(LEN) does not wrap around the address /// space. unsafe fn write_volatile_array<const LEN: usize, T: Uint>( &self, dst: *mut T, src: *const [T; LEN], ) { write_volatile_slice(self, dst, &*src); } } /// A zero-sized type that implements the Mmio trait with real reads from the /// provided pointer. #[derive(Clone, Copy, Default)] pub struct RealMmio<'a>(PhantomData<&'a ()>); impl Mmio for RealMmio<'_> { /// Performs a volatile read from `src` and returns the read value. /// /// # Safety /// /// Same as [`core::ptr::read_volatile`]. unsafe fn read_volatile<T: Clone + Copy>(&self, src: *const T) -> T { core::ptr::read_volatile(src) } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] unsafe fn read_volatile_array<const LEN: usize, T: Uint>(&self, dst: *mut T, src: *mut T) { opt_riscv::read_volatile_array::<LEN, T>(dst, src) } } /// A zero-sized type that implements the Mmio and MmioMut traits with real /// reads and writes from/to the provided pointer. #[derive(Clone, Copy, Default)] pub struct RealMmioMut<'a>(PhantomData<&'a mut ()>); impl Mmio for RealMmioMut<'_> { /// Performs a volatile read from `src` and returns the read value. /// /// # Safety /// /// Same as [`core::ptr::read_volatile`]. #[inline(always)] unsafe fn read_volatile<T: Clone + Copy>(&self, src: *const T) -> T { core::ptr::read_volatile(src) } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] unsafe fn read_volatile_array<const LEN: usize, T: Uint>(&self, dst: *mut T, src: *mut T) { opt_riscv::read_volatile_array::<LEN, T>(dst, src) } } impl MmioMut for RealMmioMut<'_> { /// Performs a volatile write of `src` to `dst`. /// /// # Safety /// /// Same as [`core::ptr::write_volatile`]. #[inline(always)] unsafe fn write_volatile<T: Clone + Copy>(&self, dst: *mut T, src: T) { core::ptr::write_volatile(dst, src); } #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] unsafe fn write_volatile_array<const LEN: usize, T: Uint>( &self, dst: *mut T, src: *const [T; LEN], ) { opt_riscv::write_volatile_array::<LEN, T>(dst, src) } } impl<TMmio: Mmio> Mmio for &TMmio { #[inline(always)] unsafe fn read_volatile<T: Uint>(&self, src: *const T) -> T { (*self).read_volatile(src) } unsafe fn read_volatile_array<const LEN: usize, T: Uint>(&self, dst: *mut T, src: *mut T) { (*self).read_volatile_array::<LEN, T>(dst, src) } } impl<TMmio: MmioMut> MmioMut for &TMmio { #[inline(always)] unsafe fn write_volatile<T: Uint>(&self, dst: *mut T, src: T) { (*self).write_volatile(dst, src) } #[inline(always)] unsafe fn write_volatile_array<const LEN: usize, T: Uint>( &self, dst: *mut T, src: *const [T; LEN], ) { (*self).write_volatile_array::<LEN, T>(dst, src) } } pub trait FromMmioPtr { /// The raw type of the register (typically `u8`, `u16`, `u32`, or `u64`) type TRaw: Clone + Copy; /// The Mmio implementation to use; typically RealMmio. type TMmio: Mmio; /// `Self::STRIDE * mem::size_of::<TRaw>()` is this number of bytes between /// the addresses of two Self instances adjacent in memory. const STRIDE: usize; /// Constructs a FromMmioPtr implementation from a raw register pointer and /// Mmio implementation /// /// Using an Mmio implementation other than RealMmio is primarily for /// tests or simulations. /// /// # Safety /// /// This function is unsafe because `ptr` may be used for loads or stores at any time /// during the lifetime of the returned value. The caller to new is responsible for ensuring that: /// /// * `ptr` is non-null /// * `ptr` is valid for loads and stores of `Self::STRIDE * mem::size_of::<Self::Raw>` /// bytes for the entire lifetime of the returned value. /// * `ptr` is properly aligned. unsafe fn from_ptr(ptr: *mut Self::TRaw, mmio: Self::TMmio) -> Self; } /// A reference to a strongly typed MMIO register. /// /// The `TReg` type parameter describes the properties of the register. /// In addition to implementing the `RegType` trait to describe the raw pointer /// type (typically `u8`, `u16, `u32`, or `u64), TReg should consider /// implementing the following traits: /// /// * `ReadableReg` for registers that can be read from. If `TReg` implements `ReadableReg`, /// `RegRef::read()` will be available. /// * `WritableReg` for registers that can be written to. If `TReg` implements `WritableReg`, /// `RegRef::modify()` will be available. /// * `ResettableReg` for registers that have a defined reset value. If `TReg` /// implements `ResettableReg` and `WritableReg`, `RegRef::write()` will be /// available. #[derive(Clone, Copy)] pub struct RegRef<TReg: RegType, TMmio: Mmio> { mmio: TMmio, pub ptr: *mut TReg::Raw, } impl<TReg: RegType, TMmio: Mmio> RegRef<TReg, TMmio> { /// Creates a new RegRef from a raw register pointer and Mmio implementation. /// /// Using an Mmio implentation other than RealMmio is primarily for /// tests or simulations in the build environment. /// /// # Safety /// /// The caller must fulfill the same requirements as `RegRef::new` #[inline(always)] pub unsafe fn new_with_mmio(ptr: *mut TReg::Raw, mmio: TMmio) -> Self { Self { mmio, ptr } } } impl<TReg: RegType, TMmio: Mmio + Default> RegRef<TReg, TMmio> { /// Creates a new RegRef from a raw register pointer. /// /// # Safety /// /// This function is unsafe because later (safe) calls to read() or write() /// will load or store from this pointer. The caller to new is responsible for ensuring that: /// /// * `ptr` is non-null /// * `ptr` is valid for loads and stores of `mem::size_of::<TReg::Raw>` /// bytes for the entire lifetime of this RegRef. /// * `ptr` is properly aligned. #[inline(always)] pub unsafe fn new(ptr: *mut TReg::Raw) -> Self { Self { mmio: Default::default(), ptr, } } /// Returns a pointer to the underlying MMIO register. /// /// # Safety /// /// This pointer can be used for volatile reads and writes at any time /// during the lifetime of Self. Callers are responsible for ensuring that /// their use doesn't conflict with other accesses to this MMIO register. #[inline(always)] pub fn ptr(&self) -> *mut TReg::Raw { self.ptr } } impl<TReg: RegType, TMmio: Mmio> FromMmioPtr for RegRef<TReg, TMmio> { type TRaw = TReg::Raw; type TMmio = TMmio; const STRIDE: usize = 1; #[inline(always)] unsafe fn from_ptr(ptr: *mut Self::TRaw, mmio: Self::TMmio) -> Self { Self { ptr, mmio } } } impl<TReg: ReadableReg, TMmio: Mmio> RegRef<TReg, TMmio> { /// Performs a volatile load from the underlying MMIO register. /// /// # Example /// /// ```no_run /// use ureg::{ReadableReg, RegRef, RealMmio, RegType}; /// // Note: these types are typically generated by ureg-codegen. /// struct ControlReg(); /// impl RegType for ControlReg { /// type Raw = u32; /// } /// impl ReadableReg for ControlReg { /// type ReadVal = ControlRegReadVal; /// } /// #[derive(Clone, Copy)] /// struct ControlRegReadVal(u32); /// impl From<u32> for ControlRegReadVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// impl ControlRegReadVal { /// pub fn enabled(&self) -> bool { /// (self.0 & 0x1) != 0 /// } /// pub fn tx_len(&self) -> u8 { /// ((self.0 >> 1) & 0xff) as u8 /// } /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn control(&self) -> RegRef<ControlReg, RealMmio> { return unsafe { RegRef::new(self.0.add(4)) } } /// } /// /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Loads from address 0x3002_00010 twice /// if regs.control().read().enabled() { /// println!("Active transaction of length {}", regs.control().read().tx_len()); /// } /// /// // Loads from address 0x3002_00010 once /// let control_reg_val = regs.control().read(); /// if control_reg_val.enabled() { /// println!("Active transaction of length {}", control_reg_val.tx_len()); /// } /// ``` #[inline(always)] pub fn read(&self) -> TReg::ReadVal { let raw = unsafe { self.mmio.read_volatile(self.ptr) }; TReg::ReadVal::from(raw) } } impl<TReg: ResettableReg + WritableReg, TMmio: MmioMut> RegRef<TReg, TMmio> { /// Performs a volatile write to the underlying MMIO register. /// /// The `f` closure is used to build the register value. It is /// immediately called with the reset value of the register, and returns /// the value that should be written to the register. /// /// # Example /// /// ```no_run /// use ureg::{ResettableReg, WritableReg, RealMmioMut, RegRef, RegType}; /// // Note: these types are typically generated by ureg-codegen. /// struct ControlReg(); /// impl RegType for ControlReg { /// type Raw = u32; /// } /// impl WritableReg for ControlReg { /// type WriteVal = ControlRegWriteVal; /// } /// impl ResettableReg for ControlReg { /// const RESET_VAL: u32 = 0x1fe; /// } /// #[derive(Clone, Copy)] /// struct ControlRegWriteVal(u32); /// impl ControlRegWriteVal { /// fn enabled(self, val: bool) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !0x1) | u32::from(val) << 0) /// } /// fn tx_len(self, val: u8) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !(0xff << 1)) | (u32::from(val) & 0xff) << 1) /// } /// } /// impl From<u32> for ControlRegWriteVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// impl From<ControlRegWriteVal> for u32 { /// fn from(val: ControlRegWriteVal) -> Self { /// val.0 /// } /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn control(&self) -> RegRef<ControlReg, RealMmioMut> { return unsafe { RegRef::new(self.0.add(4)) } } /// } /// /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Writes `0x1ff` to address 0x3002_0010 /// regs.control().write(|w| w.enabled(true)); /// /// // Writes `0x3` to address 0x3002_0010 /// regs.control().write(|w| w.enabled(true).tx_len(1)); /// /// ``` #[inline(always)] pub fn write(&self, f: impl FnOnce(TReg::WriteVal) -> TReg::WriteVal) { let val = TReg::WriteVal::from(TReg::RESET_VAL); let val = f(val); unsafe { self.mmio.write_volatile(self.ptr, val.into()) } } } impl<TReg: ReadableReg + WritableReg, TMmio: MmioMut> RegRef<TReg, TMmio> { /// Performs a load-modify-store with the underlying MMIO register. /// /// The `f` closure is used to build the register value. It is /// immediately called with the loaded value of the register converted to /// `TReg::WriteVal`, and the closure must return the value that should be /// written to the register. /// /// # Example /// /// ```no_run /// use ureg::{ReadableReg, ResettableReg, WritableReg, RealMmioMut, RegRef, RegType}; /// /// // Note: these types are typically generated by ureg-codegen. /// struct ControlReg(); /// impl RegType for ControlReg { /// type Raw = u32; /// } /// impl ReadableReg for ControlReg { /// type ReadVal = ControlRegReadVal; /// } /// impl WritableReg for ControlReg { /// type WriteVal = ControlRegWriteVal; /// } /// impl ResettableReg for ControlReg { /// const RESET_VAL: u32 = 0x1fe; /// } /// #[derive(Clone, Copy)] /// struct ControlRegReadVal(u32); /// impl From<u32> for ControlRegReadVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// #[derive(Clone, Copy)] /// struct ControlRegWriteVal(u32); /// impl ControlRegWriteVal { /// fn enabled(self, val: bool) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !0x1) | u32::from(val) << 0) /// } /// fn tx_len(self, val: u8) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !(0xff << 1)) | (u32::from(val) & 0xff) << 1) /// } /// } /// impl From<u32> for ControlRegWriteVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// impl From<ControlRegWriteVal> for u32 { /// fn from(val: ControlRegWriteVal) -> Self { /// val.0 /// } /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn control(&self) -> RegRef<ControlReg, RealMmioMut> { return unsafe { RegRef::new(self.0.add(4)) } } /// } /// /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Write `0x000` to 0x3002_0010 /// regs.control().write(|w| w.enabled(false).tx_len(0)); /// /// // Reads `0x000` from 0x3002_0010 and replaces it with `0x001` /// regs.control().modify(|w| w.enabled(true)); /// /// // Reads `0x001` from 0x3002_0010 and replaces it with `0x003` /// regs.control().modify(|w| w.tx_len(1)); /// /// // Reads `0x003` from 0x3002_0010 and replaces it with `0x002` /// regs.control().modify(|w| w.enabled(false)); /// /// ``` #[inline(always)] pub fn modify(&self, f: impl FnOnce(TReg::WriteVal) -> TReg::WriteVal) { let val = unsafe { self.mmio.read_volatile(self.ptr) }; let wval = TReg::WriteVal::from(val); let val = f(wval); unsafe { self.mmio.write_volatile(self.ptr, val.into()) } } /// Performs a load-modify-store with the underlying MMIO register. /// /// Same as [`RegRef::modify`], but the closure is also passed the read /// value as a parameter. /// /// # Example /// /// ```no_run /// use ureg::{ReadableReg, ResettableReg, WritableReg, RealMmioMut, RegRef, RegType}; /// /// // Note: these types are typically generated by ureg-codegen. /// struct ControlReg(); /// impl RegType for ControlReg { /// type Raw = u32; /// } /// impl ReadableReg for ControlReg { /// type ReadVal = ControlRegReadVal; /// } /// impl WritableReg for ControlReg { /// type WriteVal = ControlRegWriteVal; /// } /// impl ResettableReg for ControlReg { /// const RESET_VAL: u32 = 0x1fe; /// } /// #[derive(Clone, Copy)] /// struct ControlRegReadVal(u32); /// impl From<u32> for ControlRegReadVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// impl ControlRegReadVal { /// pub fn enabled(&self) -> bool { /// (self.0 & 0x1) != 0 /// } /// pub fn tx_len(&self) -> u8 { /// ((self.0 >> 1) & 0xff) as u8 /// } /// } /// #[derive(Clone, Copy)] /// struct ControlRegWriteVal(u32); /// impl ControlRegWriteVal { /// pub fn enabled(self, val: bool) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !0x1) | u32::from(val) << 0) /// } /// pub fn tx_len(self, val: u8) -> ControlRegWriteVal { /// ControlRegWriteVal((self.0 & !(0xff << 1)) | (u32::from(val) & 0xff) << 1) /// } /// } /// impl From<u32> for ControlRegWriteVal { /// fn from(val: u32) -> Self { /// Self(val) /// } /// } /// impl From<ControlRegWriteVal> for u32 { /// fn from(val: ControlRegWriteVal) -> Self { /// val.0 /// } /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn control(&self) -> RegRef<ControlReg, RealMmioMut> { return unsafe { RegRef::new(self.0.add(4)) } } /// } /// /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Toggles the least significant bit of 0x3002_0000, and leaves the others the same. /// regs.control().read_and_modify(|r, w| w.enabled(!r.enabled())); /// ``` #[inline(always)] pub fn read_and_modify(&self, f: impl FnOnce(TReg::ReadVal, TReg::WriteVal) -> TReg::WriteVal) { let val = unsafe { self.mmio.read_volatile(self.ptr) }; let rval = TReg::ReadVal::from(val); let wval = TReg::WriteVal::from(val); let val = f(rval, wval); unsafe { self.mmio.write_volatile(self.ptr, val.into()) } } } /// Represents an array of memory-mapped registers with a fixed-size stride. /// /// Can be used for arrays of [`RegRef`], [`Array`], or register blocks. pub struct Array<const LEN: usize, TItem: FromMmioPtr> { mmio: TItem::TMmio, ptr: *mut TItem::TRaw, } impl<const LEN: usize, TItem: FromMmioPtr<TMmio = TMmio>, TMmio: Mmio + Copy> Array<LEN, TItem> { /// Returns the item at `index`. /// /// # Panics /// /// Panics if `index` is out of bounds. #[inline(always)] pub fn at(&self, index: usize) -> TItem { if index >= LEN { panic!("register index out of bounds"); } unsafe { TItem::from_ptr(self.ptr.add(index * TItem::STRIDE), self.mmio) } } /// Returns the item at `index`, or None if `index` is out of bounds. #[inline(always)] pub fn get(&self, index: usize) -> Option<TItem> { if index >= LEN { None } else { unsafe { Some(TItem::from_ptr( self.ptr.add(index * TItem::STRIDE), self.mmio, )) } } } #[inline(always)] pub fn truncate<const NEW_LEN: usize>(&self) -> Array<NEW_LEN, TItem> { assert!(NEW_LEN <= LEN); Array { mmio: self.mmio, ptr: self.ptr, } } } impl<const LEN: usize, TMmio: Mmio + Default, TItem: FromMmioPtr<TMmio = TMmio>> Array<LEN, TItem> { /// Creates a new Array from a raw register pointer. /// /// # Safety /// /// This function is unsafe because `ptr` may be used for loads or stores at any time /// during the lifetime of the array. The caller is responsible for ensuring that: /// /// * `ptr` is non-null /// * `ptr` is valid for loads and stores of `LEN * TItem::STRIDE * mem::size_of::<TItem::Raw>` /// bytes for the entire lifetime of this array. /// * `ptr` is properly aligned. #[inline(always)] pub unsafe fn new(ptr: *mut TItem::TRaw) -> Self { Self { mmio: Default::default(), ptr, } } } impl<const LEN: usize, TItem: FromMmioPtr> Array<LEN, TItem> { /// Creates a new Array from a raw register pointer. /// /// # Safety /// /// This function is unsafe because `ptr` may be used for loads or stores at any time /// during the lifetime of the array. The caller is responsible for ensuring that: /// /// * `ptr` is non-null /// * `ptr` is valid for loads and stores of `LEN * TItem::STRIDE * mem::size_of::<TItem::Raw>` /// bytes for the entire lifetime of this array. /// * `ptr` is properly aligned. #[inline(always)] pub unsafe fn new_with_mmio(ptr: *mut TItem::TRaw, mmio: TItem::TMmio) -> Self { Self { mmio, ptr } } } impl<const LEN: usize, TRaw: Uint, TReg: ReadableReg<ReadVal = TRaw, Raw = TRaw>, TMmio: Mmio> Array<LEN, RegRef<TReg, TMmio>> { /// Reads the entire contents of the array from the underlying registers /// /// # Example /// /// ```no_run /// use ureg::{Array, ReadableReg, RealMmio, RegRef, RegType}; /// /// // Note: these types are typically generated by ureg-codegen. /// struct ValueReg(); /// impl RegType for ValueReg{ /// type Raw = u32; /// } /// impl ReadableReg for ValueReg { /// type ReadVal = u32; /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn value(&self) -> Array<4, RegRef<ValueReg, RealMmio>> { return unsafe { Array::new(self.0.add(16)) } } /// } /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Reads words from 0x3002_0040, 0x3002_0044, 0x3002_0048, then 0x3002_004c /// let value: [u32; 4] = regs.value().read(); /// ``` #[inline(always)] pub fn read(&self) -> [TReg::ReadVal; LEN] { let mut result: MaybeUninit<[TReg::ReadVal; LEN]> = MaybeUninit::uninit(); unsafe { self.mmio .read_volatile_array::<LEN, _>(result.as_mut_ptr() as *mut TReg::ReadVal, self.ptr); result.assume_init() } } #[inline(always)] pub fn ptr(self) -> *mut TReg::Raw { self.ptr } } #[inline(never)] unsafe fn read_volatile_slice<T: Uint, TMmio: Mmio>( mmio: &TMmio, dst: *mut T, src: *mut T, len: usize, ) { for i in 0..len { dst.add(i).write(mmio.read_volatile(src.add(i))); } } #[inline(never)] unsafe fn write_volatile_slice<T: Uint, TMmio: MmioMut>(mmio: &TMmio, dest: *mut T, val: &[T]) { #[allow(clippy::needless_range_loop)] for i in 0..val.len() { mmio.write_volatile(dest.add(i), val[i]); } } impl< const LEN: usize, TRaw: Uint, TReg: WritableReg<WriteVal = TRaw, Raw = TRaw>, TMmio: MmioMut, > Array<LEN, RegRef<TReg, TMmio>> { /// Writes the entire contents of the array to the underlying registers /// /// # Example /// /// ```no_run /// use ureg::{Array, WritableReg, RegRef, RealMmioMut, RegType}; /// /// // Note: these types are typically generated by ureg-codegen. /// struct ValueReg(); /// impl RegType for ValueReg{ /// type Raw = u32; /// } /// impl WritableReg for ValueReg { /// type WriteVal = u32; /// } /// struct RegisterBlock(*mut u32); /// impl RegisterBlock { /// fn value(&self) -> Array<4, RegRef<ValueReg, RealMmioMut>> { return unsafe { Array::new(self.0.add(16)) } } /// } /// let regs = RegisterBlock(0x3002_0000 as *mut u32); /// /// // Writes `0x10` to address `0x3002_0040`, `0x20` to `0x3002_0044`, /// // `0x30` to `0x3002_0048`, then `0x40` to `0x3002_004c` /// regs.value().write(&[0x10, 0x20, 0x30, 0x40]); /// ``` #[inline(always)] pub fn write(&self, val: &[TRaw; LEN]) { unsafe { self.mmio.write_volatile_array(self.ptr, val); } } /// Writes the entire contents of the `val` array pointer to the underlying /// registers. /// /// # Safety /// /// Caller must ensure that the safety requirements of /// [`core::ptr::read`] are met for every element of the `val array`, and that /// `val.add(1)` does not wrap around the address space. pub unsafe fn write_ptr(&self, val: *const [TRaw; LEN]) { self.mmio.write_volatile_array(self.ptr, val); } } impl<const LEN: usize, TItem: FromMmioPtr> FromMmioPtr for Array<LEN, TItem> { type TRaw = TItem::TRaw; type TMmio = TItem::TMmio; const STRIDE: usize = LEN * TItem::STRIDE; #[inline(always)] unsafe fn from_ptr(ptr: *mut Self::TRaw, mmio: Self::TMmio) -> Self { Self { ptr, mmio } } } #[cfg(test)] mod tests { use super::*; // To run inside the MIRI interpreter to detect undefined behavior in the // unsafe code, run with: // cargo +nightly miri test -p ureg --lib #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Pull { Down = 0, Up = 1, HiZ = 2, Default3 = 3, } impl Pull { fn down(&self) -> bool { *self == Self::Down } fn up(&self) -> bool { *self == Self::Up } fn hi_z(&self) -> bool { *self == Self::HiZ } } impl TryFrom<u32> for Pull { type Error = (); #[inline(always)] fn try_from(val: u32) -> Result<Self, ()> { match val { 0 => Ok(Pull::Down), 1 => Ok(Pull::Up), 2 => Ok(Pull::HiZ), 3 => Ok(Pull::Default3), _ => Err(()), } } } #[derive(Clone, Copy)] pub struct PullSelector(); impl PullSelector { pub fn down(self) -> Pull { Pull::Down } pub fn up(self) -> Pull { Pull::Up } pub fn hi_z(self) -> Pull { Pull::HiZ } } pub struct FifoReg(); impl RegType for FifoReg { type Raw = u32; } impl ReadableReg for FifoReg { type ReadVal = u32; } impl WritableReg for FifoReg { type WriteVal = u32; } impl ResettableReg for FifoReg { const RESET_VAL: u32 = 0; } pub struct ControlReg(); impl RegType for ControlReg { type Raw = u32; } impl ReadableReg for ControlReg { type ReadVal = ControlRegReadVal; } impl WritableReg for ControlReg { type WriteVal = ControlRegWriteVal; } impl ResettableReg for ControlReg { const RESET_VAL: u32 = 0; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ControlRegReadVal(u32); impl ControlRegReadVal { pub fn enabled(&self) -> bool { (self.0 & 0x1) != 0 } pub fn pull(&self) -> Pull { Pull::try_from((self.0 >> 1) & 0x3).unwrap() } } impl From<u32> for ControlRegReadVal { fn from(val: u32) -> Self { Self(val) } } #[derive(Clone, Copy)]
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/src/opt_riscv.rs
ureg/src/opt_riscv.rs
// Licensed under the Apache-2.0 license use crate::{RealMmio, RealMmioMut, Uint, UintType}; #[inline(always)] pub unsafe fn read_volatile_array<const LEN: usize, T: Uint>(dst: *mut T, src: *mut T) { match (T::TYPE, LEN) { (UintType::U32, 12) => copy_12words(dst as *mut u32, src as *const u32), (UintType::U32, 16) => copy_16words(dst as *mut u32, src as *const u32), _ => super::read_volatile_slice(&RealMmio::default(), dst, src, LEN), } } #[inline(always)] pub unsafe fn write_volatile_array<const LEN: usize, T: Uint>(dst: *mut T, src: *const [T; LEN]) { match (T::TYPE, LEN) { (UintType::U32, 12) => copy_12words(dst as *mut u32, src as *const u32), (UintType::U32, 16) => copy_16words(dst as *mut u32, src as *const u32), _ => super::write_volatile_slice(&RealMmioMut::default(), dst, &*src), } } #[inline(never)] unsafe fn copy_16words(dest: *mut u32, val: *const u32) { core::arch::asm!( "lw {tmp0}, 0({s})", "lw {tmp1}, 4({s})", "lw {tmp2}, 8({s})", "lw {tmp3}, 12({s})", "sw {tmp0}, 0({d})", "sw {tmp1}, 4({d})", "sw {tmp2}, 8({d})", "sw {tmp3}, 12({d})", "lw {tmp0}, 16({s})", "lw {tmp1}, 20({s})", "lw {tmp2}, 24({s})", "lw {tmp3}, 28({s})", "sw {tmp0}, 16({d})", "sw {tmp1}, 20({d})", "sw {tmp2}, 24({d})", "sw {tmp3}, 28({d})", "lw {tmp0}, 32({s})", "lw {tmp1}, 36({s})", "lw {tmp2}, 40({s})", "lw {tmp3}, 44({s})", "sw {tmp0}, 32({d})", "sw {tmp1}, 36({d})", "sw {tmp2}, 40({d})", "sw {tmp3}, 44({d})", "lw {tmp0}, 48({s})", "lw {tmp1}, 52({s})", "lw {tmp2}, 56({s})", "lw {tmp3}, 60({s})", "sw {tmp0}, 48({d})", "sw {tmp1}, 52({d})", "sw {tmp2}, 56({d})", "sw {tmp3}, 60({d})", s = in(reg) val, d = in(reg) dest, tmp0 = out(reg) _, tmp1 = out(reg) _, tmp2 = out(reg) _, tmp3 = out(reg) _, ); } #[inline(never)] unsafe fn copy_12words(dest: *mut u32, val: *const u32) { core::arch::asm!( "lw {tmp0}, 0({s})", "lw {tmp1}, 4({s})", "lw {tmp2}, 8({s})", "lw {tmp3}, 12({s})", "sw {tmp0}, 0({d})", "sw {tmp1}, 4({d})", "sw {tmp2}, 8({d})", "sw {tmp3}, 12({d})", "lw {tmp0}, 16({s})", "lw {tmp1}, 20({s})", "lw {tmp2}, 24({s})", "lw {tmp3}, 28({s})", "sw {tmp0}, 16({d})", "sw {tmp1}, 20({d})", "sw {tmp2}, 24({d})", "sw {tmp3}, 28({d})", "lw {tmp0}, 32({s})", "lw {tmp1}, 36({s})", "lw {tmp2}, 40({s})", "lw {tmp3}, 44({s})", "sw {tmp0}, 32({d})", "sw {tmp1}, 36({d})", "sw {tmp2}, 40({d})", "sw {tmp3}, 44({d})", s = in(reg) val, d = in(reg) dest, tmp0 = out(reg) _, tmp1 = out(reg) _, tmp2 = out(reg) _, tmp3 = out(reg) _, ); } #[cfg(test)] mod test { use super::*; // To test, run "cargo install cross", then "cross test --target riscv64gc-unknown-linux-gnu" #[test] fn test_read_volatile_array_12_u32() { let mut src: [u32; 12] = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, ]; let mut dest = [0x5555_5555_u32; 14]; unsafe { read_volatile_array::<12, u32>(dest.as_mut_ptr().add(1), src.as_mut_ptr() as *mut u32) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0x55555555 ] ); assert_eq!( src, [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, ], ); } #[test] fn test_read_volatile_array_12_u8() { let mut src: [u8; 12] = [ 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, ]; let mut dest = [0x55_u8; 14]; unsafe { read_volatile_array::<12, u8>(dest.as_mut_ptr().add(1), src.as_mut_ptr() as *mut u8) }; assert_eq!( dest, [0x55, 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0x55,] ); assert_eq!( src, [0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f,] ); } #[test] fn test_read_volatile_array_16_u32() { let mut src: [u32; 16] = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x3bfe2428, ]; let mut dest = [0x5555_5555; 18]; unsafe { read_volatile_array::<16, u32>(dest.as_mut_ptr().add(1), src.as_mut_ptr() as *mut u32) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x3bfe2428, 0x55555555 ] ); assert_eq!( src, [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x3bfe2428, ] ); } #[test] fn test_read_volatile_array_16_u8() { let mut src: [u8; 16] = [ 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0xc4, 0x4c, 0x6a, 0x28, ]; let mut dest = [0x55_u8; 18]; unsafe { read_volatile_array::<16, u8>(dest.as_mut_ptr().add(1), src.as_mut_ptr() as *mut u8) }; assert_eq!( dest, [ 0x55, 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0xc4, 0x4c, 0x6a, 0x28, 0x55, ] ); assert_eq!( src, [ 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0xc4, 0x4c, 0x6a, 0x28, ] ); } #[test] fn test_read_volatile_array_15_u32() { let mut src: [u32; 15] = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, ]; let mut dest = [0x5555_5555; 17]; unsafe { read_volatile_array::<15, u32>(dest.as_mut_ptr().add(1), src.as_mut_ptr() as *mut u32) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x55555555, ] ); assert_eq!( src, [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, ] ); } #[test] fn test_write_volatile_array_12_u32() { let src: [u32; 12] = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, ]; let mut dest = [0x5555_5555_u32; 14]; unsafe { write_volatile_array::<12, u32>(dest.as_mut_ptr().add(1), &src) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0x55555555 ] ) } #[test] fn test_write_volatile_array_12_u8() { let src: [u8; 12] = [ 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, ]; let mut dest = [0x55_u8; 14]; unsafe { write_volatile_array::<12, u8>(dest.as_mut_ptr().add(1), &src) }; assert_eq!( dest, [0x55, 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0x55,] ) } #[test] fn test_write_volatile_array_16_u32() { let src = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x3bfe2428, ]; let mut dest = [0x5555_5555; 18]; unsafe { write_volatile_array::<16, u32>(dest.as_mut_ptr().add(1), &src) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x3bfe2428, 0x55555555 ] ) } #[test] fn test_write_volatile_array_16_u8() { let src: [u8; 16] = [ 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0xc4, 0x4c, 0x6a, 0x28, ]; let mut dest = [0x55_u8; 18]; unsafe { write_volatile_array::<16, u8>(dest.as_mut_ptr().add(1), &src) }; assert_eq!( dest, [ 0x55, 0xe3, 0xc3, 0x63, 0xe7, 0x00, 0x87, 0x50, 0xdf, 0xda, 0xff, 0x76, 0x7f, 0xc4, 0x4c, 0x6a, 0x28, 0x55, ] ) } #[test] fn test_write_volatile_array_15_u32() { let src: [u32; 15] = [ 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, ]; let mut dest = [0x5555_5555; 17]; unsafe { write_volatile_array::<15, u32>(dest.as_mut_ptr().add(1), &src) }; assert_eq!( dest, [ 0x55555555, 0xcf3ae93b, 0x3a5f6465, 0x0bbcb2c1, 0xad82403e, 0xdc0454aa, 0x038b0e23, 0x27fc0139, 0x4fd1b300, 0x627ec17f, 0x9f58d0fc, 0x05f7b36c, 0x588179e2, 0xb039d6b4, 0x44e612a1, 0x46690857, 0x55555555, ] ) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/lib/codegen/src/lib.rs
ureg/lib/codegen/src/lib.rs
/*++ Licensed under the Apache-2.0 license. --*/ use std::{collections::HashMap, rc::Rc, str::FromStr}; use proc_macro2::{Ident, Literal, TokenStream}; use quote::{format_ident, quote}; use ureg_schema::{ Enum, EnumVariant, FieldType, Register, RegisterBlock, RegisterSubBlock, RegisterType, RegisterWidth, ValidatedRegisterBlock, }; fn tweak_keywords(s: &str) -> &str { match s { "as" => "as_", "break" => "break_", "const" => "const_", "continue" => "continue_", "crate" => "crate_", "else" => "else_", "fn" => "fn_", "for" => "for_", "if" => "if_", "impl" => "impl_", "in" => "in_", "let" => "let_", "loop" => "loop_", "match" => "match_", "mod" => "mod_", "move" => "move_", "mut" => "mut_", "pub" => "pub_", "ref" => "ref_", "return" => "return_", "self" => "self_", "Self" => "Self_", "static" => "static_", "struct" => "struct_", "super" => "super_", "trait" => "trait_", "true" => "true_", "type" => "type_", "unsafe" => "unsafe_", "use" => "use_", "where" => "where_", "while" => "while_", "async" => "async_", "await" => "await_", "dyn" => "dyn_", "abstract" => "abstract_", "become" => "become_", "box" => "box_", "do" => "do_", "final" => "final_", "macro" => "macro_", "override" => "override_", "priv" => "priv_", "typeof" => "typeof_", "unsized" => "unsized_", "virtual" => "virtual_", "yield" => "yield_", s => s, } } fn snake_ident(name: &str) -> Ident { let mut result = String::new(); if let Some(c) = name.chars().next() { if c.is_ascii_digit() { result.push('_'); } } let mut prev = None; for c in name.chars() { if c.is_ascii_whitespace() || c.is_ascii_punctuation() { if prev != Some('_') { result.push('_'); } prev = Some('_'); continue; } if let Some(prev) = prev { if (prev.is_ascii_lowercase() || prev.is_ascii_digit()) && c.is_ascii_uppercase() { result.push('_'); } } prev = Some(c); result.push(c.to_ascii_lowercase()); } result = result.replace("i3_c", "i3c_").replace("__", "_"); // hack for I3C format_ident!("{}", tweak_keywords(result.trim_end_matches('_'))) } #[cfg(test)] mod snake_ident_tests { use crate::*; #[test] fn test_snake_ident() { assert_eq!("_8_bits", snake_ident("8 bits").to_string()); assert_eq!("_16_bits", snake_ident("16_Bits").to_string()); assert_eq!("_16_bits", snake_ident("16Bits").to_string()); assert_eq!("_16bits", snake_ident("16bits").to_string()); assert_eq!("foo_bar_baz", snake_ident("fooBarBaz").to_string()); assert_eq!("foo_bar_baz", snake_ident("FooBarBaz").to_string()); assert_eq!("foo_bar_baz", snake_ident("foo bar baz").to_string()); assert_eq!("foo_bar_baz", snake_ident("foo_bar_baz").to_string()); assert_eq!("foo_bar_baz", snake_ident("FOO BAR BAZ").to_string()); assert_eq!("foo_bar_baz", snake_ident("FOO_BAR_BAZ").to_string()); assert_eq!("foo_bar_baz", snake_ident("FOO BAR BAZ.").to_string()); assert_eq!("foo_bar_baz", snake_ident("FOO BAR.BAZ.").to_string()); assert_eq!("foo_bar_baz", snake_ident("FOO BAR..BAZ.").to_string()); assert_eq!("fn_", snake_ident("fn").to_string()); assert_eq!("fn_", snake_ident("FN").to_string()); } } fn camel_ident(name: &str) -> Ident { let mut result = String::new(); if let Some(c) = name.chars().next() { if c.is_ascii_digit() { result.push('_'); } } let mut upper_next = true; for c in name.chars() { if c.is_ascii_punctuation() || c.is_ascii_whitespace() { upper_next = true; } else { result.push(if upper_next { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }); upper_next = false; } } format_ident!("{}", tweak_keywords(&result)) } #[cfg(test)] mod camel_ident_tests { use crate::*; #[test] fn test_camel_ident() { assert_eq!("_8Bits", camel_ident("8 bits").to_string()); assert_eq!("_16Bits", camel_ident("16_bits").to_string()); assert_eq!("FooBarBaz", camel_ident("foo bar baz").to_string()); assert_eq!("FooBarBaz", camel_ident("foo_bar_baz").to_string()); assert_eq!("FooBarBaz", camel_ident("FOO BAR BAZ").to_string()); assert_eq!("FooBarBaz", camel_ident("FOO_BAR_BAZ").to_string()); assert_eq!("FooBarBaz", camel_ident("FOO BAR BAZ.").to_string()); assert_eq!("FooBarBaz", camel_ident("FOO BAR.BAZ.").to_string()); assert_eq!("Self_", camel_ident("self").to_string()); } } fn generate_enum(e: &Enum) -> TokenStream { let mut variant_tokens = TokenStream::new(); let mut accessor_tokens = TokenStream::new(); let mut from_u32_tokens = TokenStream::new(); let mut variant_map: HashMap<u32, &EnumVariant> = e .variants .iter() .map(|variant| (variant.value, variant)) .collect(); for i in 0..(1u32 << e.bit_width) { let variant = variant_map.remove(&i); let variant_ident = match variant { Some(variant) => camel_ident(&variant.name), None => format_ident!("Reserved{}", i), }; let variant_value = Literal::u32_unsuffixed(i); variant_tokens.extend(quote! { #variant_ident = #variant_value, }); from_u32_tokens.extend(quote! { #variant_value => Ok(Self::#variant_ident), }); if let Some(variant) = variant { let accessor_ident = snake_ident(&variant.name); accessor_tokens.extend(quote! { #[inline(always)] pub fn #accessor_ident(&self) -> bool { *self == Self::#variant_ident } }); } } let total_count = hex_literal(1u64 << e.bit_width); // unwrap is safe because this came from a ValidatedRegisterBlock let enum_name = camel_ident(e.name.as_ref().unwrap()); quote! { #[derive(Clone, Copy, Eq, PartialEq)] #[repr(u32)] pub enum #enum_name { #variant_tokens } impl #enum_name { #accessor_tokens } impl TryFrom<u32> for #enum_name { type Error = (); #[inline(always)] fn try_from(val: u32) -> Result<#enum_name, ()> { if val < #total_count { // This transmute is safe because the check above ensures // that the value has a corresponding enum variant, and the // enum is using repr(u32). Ok(unsafe { core::mem::transmute::<u32, #enum_name>(val) } ) } else { Err(()) } } } impl From<#enum_name> for u32 { fn from(val: #enum_name) -> Self { val as u32 } } } } fn generate_enum_selector(e: &Enum) -> TokenStream { let enum_name = camel_ident(e.name.as_ref().unwrap()); let mut selector_tokens = TokenStream::new(); for variant in e.variants.iter() { let selector_ident = snake_ident(&variant.name); let variant_ident = camel_ident(&variant.name); selector_tokens.extend(quote! { #[inline(always)] pub fn #selector_ident(&self) -> super::#enum_name { super::#enum_name::#variant_ident } }); } let selector_name = format_ident!("{}Selector", enum_name); quote! { pub struct #selector_name(); impl #selector_name { #selector_tokens } } } fn generate_enums<'a>(enums: impl Iterator<Item = &'a Enum>) -> TokenStream { let mut enum_tokens = TokenStream::new(); let mut selector_tokens = TokenStream::new(); let mut enums: Vec<_> = enums.collect(); enums.sort_by_key(|e| &e.name); for e in enums { enum_tokens.extend(generate_enum(e)); selector_tokens.extend(generate_enum_selector(e)); } quote! { #enum_tokens pub mod selector { #selector_tokens } } } #[cfg(test)] mod generate_enums_test { use ureg_schema::EnumVariant; use crate::*; #[test] fn test_generate_enums() { assert_eq!( generate_enums( [Enum { name: Some("Pull DIR".into()), bit_width: 2, variants: vec![ EnumVariant { name: "down".to_string(), value: 0 }, EnumVariant { name: "UP".to_string(), value: 1 }, EnumVariant { name: "Hi Z".to_string(), value: 2 }, ] }] .iter() ) .to_string(), quote! { #[derive (Clone , Copy , Eq , PartialEq)] #[repr(u32)] pub enum PullDir { Down = 0, Up = 1, HiZ = 2, Reserved3 = 3, } impl PullDir { #[inline(always)] pub fn down(&self) -> bool { *self == Self::Down } #[inline(always)] pub fn up(&self) -> bool { *self == Self::Up } #[inline(always)] pub fn hi_z(&self) -> bool { *self == Self::HiZ } } impl TryFrom<u32> for PullDir { type Error = (); #[inline (always)] fn try_from(val : u32) -> Result<PullDir, ()> { if val < 4 { Ok(unsafe { core::mem::transmute::<u32, PullDir>(val) }) } else { Err (()) } } } impl From<PullDir> for u32 { fn from(val : PullDir) -> Self { val as u32 } } pub mod selector { pub struct PullDirSelector(); impl PullDirSelector { #[inline(always)] pub fn down(&self) -> super::PullDir { super::PullDir::Down } #[inline(always)] pub fn up(&self) -> super::PullDir { super::PullDir::Up } #[inline(always)] pub fn hi_z(&self) -> super::PullDir { super::PullDir::HiZ } } } } .to_string() ); } } fn hex_literal(val: u64) -> Literal { if val > 9 { Literal::from_str(&format! {"0x{val:x}"}).unwrap() } else { Literal::u64_unsuffixed(val) } } fn read_val_ident(reg_type: &RegisterType) -> Ident { format_ident!("{}ReadVal", camel_ident(reg_type.name.as_ref().unwrap())) } fn write_val_ident(reg_type: &RegisterType) -> Ident { format_ident!("{}WriteVal", camel_ident(reg_type.name.as_ref().unwrap())) } fn generate_register(reg: &RegisterType) -> TokenStream { let read_val_ident = read_val_ident(reg); let write_val_ident = write_val_ident(reg); let raw_type = format_ident!("{}", reg.width.rust_primitive_name()); let mut read_val_tokens = TokenStream::new(); let mut write_val_tokens = TokenStream::new(); for field in reg.fields.iter() { let field_ident = snake_ident(&field.name); let position = Literal::u64_unsuffixed(field.position.into()); let mask = if field.width == 64 { hex_literal(u64::MAX) } else { hex_literal((1u64 << field.width) - 1) }; let access_expr = quote! { (self.0 >> #position) & #mask }; let comment = &field.comment.replace("<br>", "\n"); if field.ty.can_read() { if !comment.is_empty() { read_val_tokens.extend(quote! { #[doc = #comment] }) } read_val_tokens.extend(quote! { #[inline(always)] }); if let Some(ref enum_type) = field.enum_type { let enum_type_ident = camel_ident(enum_type.name.as_ref().unwrap()); read_val_tokens.extend(quote! { pub fn #field_ident(&self) -> super::enums::#enum_type_ident { super::enums::#enum_type_ident::try_from(#access_expr).unwrap() } }); } else if field.width == 1 { read_val_tokens.extend(quote! { pub fn #field_ident(&self) -> bool { (#access_expr) != 0 } }); } else { read_val_tokens.extend(quote! { pub fn #field_ident(&self) -> #raw_type { #access_expr } }); } } if field.ty.can_write() { if !comment.is_empty() { write_val_tokens.extend(quote! { #[doc = #comment] }) } write_val_tokens.extend(quote! { #[inline(always)] }); if let Some(ref enum_type) = field.enum_type { let enum_type_ident = camel_ident(enum_type.name.as_ref().unwrap()); let enum_selector_type = format_ident!("{}Selector", enum_type_ident); write_val_tokens.extend(quote! { pub fn #field_ident(self, f: impl FnOnce(super::enums::selector::#enum_selector_type) -> super::enums::#enum_type_ident) -> Self { Self((self.0 & !(#mask << #position)) | (#raw_type::from(f(super::enums::selector::#enum_selector_type())) << #position)) } }); } else if field.width == 1 { write_val_tokens.extend(quote! { pub fn #field_ident(self, val: bool) -> Self { Self((self.0 & !(#mask << #position)) | (#raw_type::from(val) << #position)) } }); } else { write_val_tokens.extend(quote! { pub fn #field_ident(self, val: #raw_type) -> Self { Self((self.0 & !(#mask << #position)) | ((val & #mask) << #position)) } }); } } if field.ty == FieldType::W1C && field.width == 1 { let field_clear_ident = format_ident!("{}_clear", field_ident); write_val_tokens.extend(quote! { #[doc = #comment] #[inline(always)] pub fn #field_clear_ident(self) -> Self { Self(self.0 | (1 << #position)) } }); } if field.ty == FieldType::W1S && field.width == 1 { let field_set_ident = format_ident!("{}_set", field_ident); write_val_tokens.extend(quote! { #[doc = #comment] #[inline(always)] pub fn #field_set_ident(self) -> Self { Self(self.0 | (1 << #position)) } }); } } let mut result = TokenStream::new(); if !read_val_tokens.is_empty() { let modify_fn_tokens = if !write_val_tokens.is_empty() { quote! { /// Construct a WriteVal that can be used to modify the contents of this register value. #[inline(always)] pub fn modify(self) -> #write_val_ident { #write_val_ident(self.0) } } } else { quote! {} }; result.extend(quote! { #[derive(Clone, Copy)] pub struct #read_val_ident(#raw_type); impl #read_val_ident{ #read_val_tokens #modify_fn_tokens } impl From<#raw_type> for #read_val_ident { #[inline(always)] fn from(val: #raw_type) -> Self { Self(val) } } impl From<#read_val_ident> for #raw_type { #[inline(always)] fn from(val: #read_val_ident) -> #raw_type { val.0 } } }); } if !write_val_tokens.is_empty() { result.extend(quote! { #[derive(Clone, Copy)] pub struct #write_val_ident(#raw_type); impl #write_val_ident{ #write_val_tokens } impl From<#raw_type> for #write_val_ident { #[inline(always)] fn from(val: #raw_type) -> Self { Self(val) } } impl From<#write_val_ident> for #raw_type { #[inline(always)] fn from(val: #write_val_ident) -> #raw_type { val.0 } } }); } result } fn generate_register_types<'a>(regs: impl Iterator<Item = &'a RegisterType>) -> TokenStream { let mut regs: Vec<_> = regs.collect(); regs.sort_by_key(|e| &e.name); let mut tokens = TokenStream::new(); for reg in regs { if !has_single_32_bit_field(reg) { tokens.extend(generate_register(reg)); } } tokens } fn has_single_32_bit_field(t: &RegisterType) -> bool { t.fields.len() == 1 && t.fields[0].enum_type.is_none() && t.fields[0].position == 0 && t.fields[0].width == 32 } fn read_write_types(t: &RegisterType, options: &OptionsInternal) -> (TokenStream, TokenStream) { // TODO: This should be using #reg_raw_type instead of u32 if has_single_32_bit_field(t) { (quote! { u32 }, quote! { u32 }) } else { if let Some(extern_type) = options.extern_types.get(t) { return ( extern_type.read_val_type.clone(), extern_type.write_val_type.clone(), ); } let read_type = read_val_ident(t); let write_type = write_val_ident(t); let module_path = &options.module_path; ( quote! { #module_path::regs::#read_type }, quote! { #module_path::regs::#write_type }, ) } } fn generate_array_type( mut remaining_dimensions: impl Iterator<Item = u64>, reg_type_tokens: TokenStream, ) -> TokenStream { match remaining_dimensions.next() { Some(array_dimension) => { let array_dimension = Literal::u64_unsuffixed(array_dimension); let inner = generate_array_type(remaining_dimensions, reg_type_tokens); quote! { ureg::Array<#array_dimension, #inner> } } None => reg_type_tokens, } } fn generate_block_registers( registers: &[Rc<Register>], raw_ptr_type: &Ident, meta_tokens: &mut TokenStream, block_tokens: &mut TokenStream, meta_prefix: &str, options: &OptionsInternal, ) { for reg in registers.iter() { let reg_raw_type = format_ident!("{}", reg.ty.width.rust_primitive_name()); let reg_name = snake_ident(&reg.name); let mut reg_meta_name = format_ident!("{}{}", meta_prefix, camel_ident(&reg.name)); if registers.len() == 1 && camel_ident(&reg.name) == meta_prefix { reg_meta_name = camel_ident(&reg.name); } let ty = reg.ty.as_ref(); let default_val = hex_literal(reg.default_val); let (read_type, write_type) = read_write_types(ty, options); let ptr_offset = hex_literal(reg.offset); let can_read = ty.fields.iter().any(|f| f.ty.can_read()); let can_write = ty.fields.iter().any(|f| f.ty.can_write()); let can_clear = ty.fields.iter().any(|f| f.ty.can_clear()); let can_set = ty.fields.iter().any(|f| f.ty.can_set()); let needs_write = can_write || can_clear || can_set; if ty.width == RegisterWidth::_32 && can_read && !needs_write { meta_tokens.extend(quote! { pub type #reg_meta_name = ureg::ReadOnlyReg32<#read_type>; }); } else if ty.width == RegisterWidth::_32 && !can_read && needs_write { meta_tokens.extend(quote! { pub type #reg_meta_name = ureg::WriteOnlyReg32<#default_val, #write_type>; }); } else if ty.width == RegisterWidth::_32 && can_read && needs_write { meta_tokens.extend(quote! { pub type #reg_meta_name = ureg::ReadWriteReg32<#default_val, #read_type, #write_type>; }); } else { meta_tokens.extend(quote! { #[derive(Clone, Copy)] pub struct #reg_meta_name(); impl ureg::RegType for #reg_meta_name { type Raw = #reg_raw_type; } }); if can_read { meta_tokens.extend(quote! { impl ureg::ReadableReg for #reg_meta_name { type ReadVal = #read_type; } }); } if can_write || can_clear || can_set { meta_tokens.extend(quote! { impl ureg::WritableReg for #reg_meta_name { type WriteVal = #write_type; } }); meta_tokens.extend(quote! { impl ureg::ResettableReg for #reg_meta_name { const RESET_VAL: Self::Raw = #default_val; } }); } } let module_path = &options.module_path; let read_type_str = read_type .to_string() .replace(' ', "") .replace("crate::", ""); let write_type_str = write_type .to_string() .replace(' ', "") .replace("crate::", ""); let comment = format!( "{}\n\nRead value: [`{read_type_str}`]; Write value: [`{write_type_str}`]", reg.comment.replace("<br>", "\n") ); let result_type = generate_array_type( reg.array_dimensions.iter().cloned(), quote! { ureg::RegRef<#module_path::meta::#reg_meta_name, &TMmio> }, ); let constructor = if reg.array_dimensions.is_empty() { quote! { ureg::RegRef::new_with_mmio } } else { quote! { ureg::Array::new_with_mmio } }; block_tokens.extend(quote!{ #[doc = #comment] #[inline(always)] pub fn #reg_name(&self) -> #result_type { unsafe { #constructor(self.ptr.wrapping_add(#ptr_offset / core::mem::size_of::<#raw_ptr_type>()), core::borrow::Borrow::borrow(&self.mmio)) } } }); } } #[derive(Clone)] pub struct ExternType { read_val_type: TokenStream, write_val_type: TokenStream, } pub struct OptionsInternal { module_path: TokenStream, is_root_module: bool, // TODO: This should probably be a const reference extern_types: HashMap<Rc<RegisterType>, ExternType>, } #[derive(Default)] pub struct Options { /// If the generated code is not at the base of the crate, this should /// be set to the prefix. pub module: TokenStream, pub extern_types: HashMap<Rc<RegisterType>, ExternType>, } impl Options { fn compile(self) -> OptionsInternal { if self.module.is_empty() { OptionsInternal { module_path: quote! {crate}, is_root_module: true, extern_types: self.extern_types, } } else { let module = self.module; OptionsInternal { module_path: quote! {crate::#module}, is_root_module: false, extern_types: self.extern_types, } } } } pub fn build_extern_types( block: &ValidatedRegisterBlock, module: TokenStream, extern_types: &mut HashMap<Rc<RegisterType>, ExternType>, ) { for ty in block.block().declared_register_types.iter() { if ty.name.is_none() { continue; } let read_val_ident = read_val_ident(ty); let write_val_ident = write_val_ident(ty); extern_types.insert( ty.clone(), ExternType { read_val_type: quote! { #module::regs::#read_val_ident }, write_val_type: quote! { #module::regs::#write_val_ident }, }, ); } } fn block_is_empty(block: &ValidatedRegisterBlock) -> bool { block.block().registers.is_empty() && block.block().instances.is_empty() && block.block().sub_blocks.is_empty() } fn block_max_register_width(block: &RegisterBlock) -> RegisterWidth { let a = block.registers.iter().map(|r| r.ty.width).max(); let b = block .sub_blocks .iter() .map(|sb| block_max_register_width(sb.block())) .max(); match (a, b) { (Some(a), Some(b)) => a.max(b), (Some(a), None) => a, (None, Some(b)) => b, (None, None) => RegisterWidth::default(), } } pub fn generate_code(block: &ValidatedRegisterBlock, options: Options) -> TokenStream { let options = options.compile(); let enum_tokens = generate_enums(block.enum_types().values().map(AsRef::as_ref)); let mut reg_tokens = generate_register_types( block .register_types() .values() .filter(|t| !options.extern_types.contains_key(*t)) .map(AsRef::as_ref), ); reg_tokens.extend(generate_register_types( block .block() .declared_register_types .iter() .map(AsRef::as_ref), )); let mut subblock_type_tokens = TokenStream::new(); let mut block_inner_tokens = TokenStream::new(); let mut meta_tokens = TokenStream::new(); let mut block_tokens = TokenStream::new(); let mut instance_type_tokens = TokenStream::new(); let mut subblock_instance_type_tokens = TokenStream::new(); if !block_is_empty(block) { let max_reg_width = block_max_register_width(block.block()); let raw_ptr_type = format_ident!("{}", max_reg_width.rust_primitive_name()); for instance in block.block().instances.iter() { let name_camel = camel_ident(&instance.name); let addr = hex_literal(instance.address.into()); // TODO: Should this be unsafe? instance_type_tokens.extend(quote! { /// A zero-sized type that represents ownership of this /// peripheral, used to get access to a Register lock. Most /// programs create one of these in unsafe code near the top of /// main(), and pass it to the driver responsible for managing /// all access to the hardware. pub struct #name_camel { // Ensure the only way to create this is via Self::new() _priv: (), } impl #name_camel { pub const PTR: *mut #raw_ptr_type = #addr as *mut #raw_ptr_type; /// # Safety /// /// Caller must ensure that all concurrent use of this /// peripheral in the firmware is done so in a compatible /// way. The simplest way to enforce this is to only call /// this function once. #[inline(always)] pub unsafe fn new() -> Self { Self{ _priv: (), } } /// Returns a register block that can be used to read /// registers from this peripheral, but cannot write. #[inline(always)] pub fn regs(&self) -> RegisterBlock<ureg::RealMmio> { RegisterBlock{ ptr: Self::PTR, mmio: core::default::Default::default(), } } /// Return a register block that can be used to read and /// write this peripheral's registers. #[inline(always)] pub fn regs_mut(&mut self) -> RegisterBlock<ureg::RealMmioMut> { RegisterBlock{ ptr: Self::PTR, mmio: core::default::Default::default(), } } } }); } generate_block_registers( &block.block().registers, &raw_ptr_type, &mut meta_tokens, &mut block_inner_tokens, "", &options, ); for sb in block.block().sub_blocks.iter() { generate_subblock_code( sb, raw_ptr_type.clone(), &options, &mut block_inner_tokens, &mut subblock_type_tokens, &mut subblock_instance_type_tokens, &mut meta_tokens, ); } block_tokens = quote! { #[allow(dead_code)] #[derive(Clone, Copy)] pub struct RegisterBlock<TMmio: ureg::Mmio + core::borrow::Borrow<TMmio>>{ ptr: *mut #raw_ptr_type, mmio: TMmio, } impl<TMmio: ureg::Mmio + core::default::Default> RegisterBlock<TMmio> { /// # Safety /// /// The caller is responsible for ensuring that ptr is valid for /// volatile reads and writes at any of the offsets in this register /// block. #[inline(always)] pub unsafe fn new(ptr: *mut #raw_ptr_type) -> Self { Self{ ptr, mmio: core::default::Default::default(), } } } impl<TMmio: ureg::Mmio> RegisterBlock<TMmio> { /// # Safety /// /// The caller is responsible for ensuring that ptr is valid for /// volatile reads and writes at any of the offsets in this register /// block. #[inline(always)] pub unsafe fn new_with_mmio(ptr: *mut #raw_ptr_type, mmio: TMmio) -> Self { Self{ ptr, mmio, } } #block_inner_tokens } } } let no_std_header = if options.is_root_module { quote! { #![no_std] } } else { // You can't set no_std in a module quote! {} }; quote! { #no_std_header #![allow(clippy::doc_lazy_continuation)] #![allow(clippy::erasing_op)] #![allow(clippy::identity_op)] #instance_type_tokens #block_tokens #subblock_type_tokens #subblock_instance_type_tokens pub mod regs { //! Types that represent the values held by registers. #reg_tokens } pub mod enums { //! Enumerations used by some register fields. #enum_tokens } pub mod meta { //! Additional metadata needed by ureg. #meta_tokens } } } #[allow(clippy::too_many_arguments)] fn generate_subblock_code( sb: &RegisterSubBlock,
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/lib/systemrdl/src/lib.rs
ureg/lib/systemrdl/src/lib.rs
/*++ Licensed under the Apache-2.0 license. --*/ mod error; pub use error::Error; use ureg::{RegisterSubBlock, RegisterType}; use std::rc::Rc; use caliptra_systemrdl::{self as systemrdl, Value}; use caliptra_systemrdl::{ComponentType, ScopeType}; use systemrdl::{AccessType, InstanceRef, ParentScope, RdlError}; use ureg_schema::{self as ureg, FieldType, RegisterField, RegisterWidth}; use ureg_schema::{RegisterBlock, RegisterBlockInstance}; fn unpad_description(desc: &str) -> String { let ltrim = desc .lines() .skip(1) .filter(|l| !l.trim().is_empty()) .map(|l| l.find(|c| c != ' ')) .min() .flatten() .unwrap_or(0); let mut lines = vec![]; for l in desc.lines() { let trim_start = usize::min(ltrim, l.find(|c| c != ' ').unwrap_or(0)); lines.push(&l[trim_start..]); } while let Some(line) = lines.last() { if !line.trim().is_empty() { break; } lines.pop(); } lines.join("\n") } fn get_property_opt<T: TryFrom<systemrdl::Value, Error = RdlError<'static>>>( scope: &systemrdl::Scope, name: &'static str, ) -> Result<Option<T>, Error> { scope.property_val_opt::<T>(name).map_err(Error::RdlError) } fn expect_instance_type(scope: systemrdl::ParentScope, ty: ScopeType) -> Result<(), Error> { if scope.scope.ty != ty { Err(Error::UnexpectedScopeType { expected: ty, actual: scope.scope.ty, }) } else { Ok(()) } } fn translate_access_type(ty: systemrdl::AccessType) -> Result<ureg::FieldType, Error> { match ty { systemrdl::AccessType::Rw => Ok(ureg::FieldType::RW), systemrdl::AccessType::R => Ok(ureg::FieldType::RO), systemrdl::AccessType::W => Ok(ureg::FieldType::WO), systemrdl::AccessType::Rw1 => Ok(ureg::FieldType::RW), systemrdl::AccessType::W1 => Ok(ureg::FieldType::WO), systemrdl::AccessType::Na => Err(Error::AccessTypeNaUnsupported), } } fn field_width(field: &systemrdl::Instance) -> Result<u64, Error> { if field.dimension_sizes.is_empty() { return Ok(field .scope .property_val_opt("fieldwidth") .ok() .flatten() .unwrap_or(1u64)); } if field.dimension_sizes.len() > 1 { return Err(Error::FieldsCannotHaveMultipleDimensions); } Ok(field.dimension_sizes[0]) } fn translate_enum(name: &str, enm: systemrdl::ParentScope) -> Result<ureg::Enum, Error> { let wrap_err = |err: Error| Error::EnumError { enum_name: name.into(), err: Box::new(err), }; expect_instance_type(enm, ComponentType::Enum.into()).map_err(wrap_err)?; let mut variants = vec![]; let mut width = 0; for variant in enm.scope.instances.iter() { let wrap_err = |err: Error| { wrap_err(Error::EnumVariantError { variant_name: variant.name.clone(), err: Box::new(err), }) }; if variant.scope.ty != ComponentType::EnumVariant.into() { continue; } let Some(reset) = variant.reset else { return Err(wrap_err(Error::ValueNotDefined)); }; width = u64::max(width, reset.w()); variants.push(ureg::EnumVariant { name: variant.name.clone(), value: reset.val() as u32, }) } Ok(ureg::Enum { name: Some(name.to_string()), variants, bit_width: width as u8, }) } fn translate_field(iref: systemrdl::InstanceRef) -> Result<ureg::RegisterField, Error> { let wrap_err = |err: Error| Error::FieldError { field_name: iref.instance.name.clone(), err: Box::new(err), }; expect_instance_type(iref.scope, ComponentType::Field.into()).map_err(wrap_err)?; let inst = iref.instance; let access_ty: AccessType = get_property_opt(&inst.scope, "sw")?.unwrap_or_default(); let enum_type = if let Ok(Some(systemrdl::EnumReference(eref))) = inst.scope.property_val_opt("encode") { if let Some(enm) = iref.scope.lookup_typedef(&eref) { Some(Rc::new(translate_enum(&eref, enm).map_err(wrap_err)?)) } else { None } } else { None }; let description: String = inst .scope .property_val_opt("desc") .unwrap() .unwrap_or_default(); let result = ureg::RegisterField { name: inst.name.clone(), ty: translate_access_type(access_ty).map_err(wrap_err)?, default_val: inst.reset.map(|b| b.val()).unwrap_or_default(), comment: unpad_description(&description), enum_type, position: inst .offset .ok_or(Error::OffsetNotDefined) .map_err(wrap_err)? as u8, width: field_width(inst).map_err(wrap_err)? as u8, }; Ok(result) } fn translate_register( iref: systemrdl::InstanceRef, default_offset: Option<u64>, ) -> Result<ureg::Register, Error> { let wrap_err = |err: Error| Error::RegisterError { register_name: iref.instance.name.clone(), err: Box::new(err), }; expect_instance_type(iref.scope, ComponentType::Reg.into()).map_err(wrap_err)?; let inst = iref.instance; let description: String = inst .scope .property_val_opt("desc") .unwrap() .unwrap_or_default(); if inst.reset.is_some() { return Err(wrap_err(Error::ResetValueOnRegisterUnsupported)); } let ty = translate_register_ty(inst.type_name.clone(), iref.scope)?; let result = ureg_schema::Register { name: inst.name.clone(), offset: { match (inst.offset, default_offset) { (Some(explicit), _) => explicit, (None, Some(next)) => next, (None, None) => return Err(wrap_err(Error::OffsetNotDefined)), } }, default_val: ty.fields.iter().fold(0, |reset, field| { let width_mask = (1 << field.width) - 1; reset | ((field.default_val & width_mask) << field.position) }), comment: unpad_description(&description), array_dimensions: inst.dimension_sizes.clone(), ty, }; Ok(result) } // Translates a memory into a register array fn translate_mem(iref: systemrdl::InstanceRef, start_offset: u64) -> Result<ureg::Register, Error> { let wrap_err = |err: Error| Error::RegisterError { register_name: iref.instance.name.clone(), err: Box::new(err), }; expect_instance_type(iref.scope, ComponentType::Mem.into()).map_err(wrap_err)?; let inst = iref.instance; let description: String = inst .scope .property_val_opt("desc") .unwrap() .unwrap_or_default(); if inst.reset.is_some() { return Err(wrap_err(Error::ResetValueOnRegisterUnsupported)); } let mut ty = RegisterType { name: inst.type_name.clone(), fields: vec![], width: RegisterWidth::_32, }; if let Some(Value::U64(memwidth)) = iref.instance.scope.properties.get("memwidth") { ty.width = match *memwidth { 8 => RegisterWidth::_8, 16 => RegisterWidth::_16, 32 => RegisterWidth::_32, 64 => RegisterWidth::_64, 128 => RegisterWidth::_128, _ => return Err(wrap_err(Error::UnsupportedRegWidth(*memwidth))), } }; let mut double = 1; if ty.width == RegisterWidth::_128 { // hack: convert to four u32s ty.width = RegisterWidth::_32; double = 4; } else if ty.width == RegisterWidth::_64 { // hack: convert to two u32s ty.width = RegisterWidth::_32; double = 2; } let entries = match iref.instance.scope.properties.get("mementries") { Some(Value::U64(mementries)) => *mementries * double, _ => return Err(wrap_err(Error::ValueNotDefined)), }; let access_type = match iref.instance.scope.properties.get("sw") { Some(Value::AccessType(AccessType::Rw)) => FieldType::RW, Some(Value::AccessType(AccessType::Rw1)) => FieldType::RW, Some(Value::AccessType(AccessType::R)) => FieldType::RO, Some(Value::AccessType(AccessType::W)) => FieldType::WO, Some(Value::AccessType(AccessType::W1)) => FieldType::WO, _ => FieldType::RW, }; ty.fields.push(RegisterField { name: "single".to_string(), ty: access_type, default_val: 0, comment: "".to_string(), enum_type: None, position: 0, width: (ty.width.in_bytes() * 8) as u8, }); let result = ureg_schema::Register { name: inst.name.clone(), offset: inst.offset.unwrap_or(start_offset), default_val: 0, comment: unpad_description(&description), array_dimensions: vec![entries], ty: Rc::new(ty), }; Ok(result) } fn translate_register_ty( type_name: Option<String>, scope: ParentScope, ) -> Result<Rc<ureg_schema::RegisterType>, Error> { let wrap_err = |err: Error| { if let Some(ref type_name) = type_name { Error::RegisterTypeError { register_type_name: type_name.clone(), err: Box::new(err), } } else { err } }; let regwidth = match get_property_opt(scope.scope, "regwidth").map_err(wrap_err)? { Some(8) => ureg_schema::RegisterWidth::_8, Some(16) => ureg_schema::RegisterWidth::_16, Some(32) => ureg_schema::RegisterWidth::_32, Some(64) => ureg_schema::RegisterWidth::_64, Some(128) => ureg_schema::RegisterWidth::_128, Some(other) => return Err(wrap_err(Error::UnsupportedRegWidth(other))), None => ureg_schema::RegisterWidth::_32, }; let mut fields = vec![]; for field in scope.instance_iter() { match translate_field(field).map_err(wrap_err) { Ok(field) => fields.push(field), Err(err) => { if matches!(err.root_cause(), Error::AccessTypeNaUnsupported) { continue; } else { return Err(err); } } } } Ok(Rc::new(ureg_schema::RegisterType { name: type_name, fields, width: regwidth, })) } pub fn translate_types(scope: systemrdl::ParentScope) -> Result<Vec<Rc<RegisterType>>, Error> { let mut result = vec![]; for (name, subscope) in scope.type_iter() { if subscope.scope.ty == ComponentType::Reg.into() { result.push(translate_register_ty(Some(name.into()), subscope)?); } } Ok(result) } /// Calculates size of the register block. fn calculate_reg_size(block: &RegisterBlock) -> Option<u64> { block .registers .iter() .map(|r| r.offset + r.ty.width.in_bytes() * r.array_dimensions.iter().product::<u64>()) .max() } fn calculate_mem_size(iref: systemrdl::InstanceRef) -> u64 { let bits = match iref.instance.scope.properties.get("memwidth") { Some(Value::U64(memwidth)) => *memwidth, _ => 32, }; let entries = match iref.instance.scope.properties.get("mementries") { Some(Value::U64(mementries)) => *mementries, _ => panic!("No mementries found for memory"), }; bits / 8 * entries } fn next_multiple_of(x: u64, mult: u64) -> u64 { assert!(mult > 0); if x % mult == 0 { x } else { x + (mult - x % mult) } } fn translate_block(iref: InstanceRef, top: bool) -> Result<RegisterBlock, Error> { let wrap_err = |err: Error| Error::BlockError { block_name: iref.instance.name.clone(), err: Box::new(err), }; let inst = iref.instance; let mut block = RegisterBlock { name: inst.name.clone(), ..Default::default() }; if let Some(addr) = inst.offset { block.instances.push(RegisterBlockInstance { name: inst.name.clone(), address: u32::try_from(addr).map_err(|_| wrap_err(Error::AddressTooLarge(addr)))?, }); } for (name, ty) in iref.scope.type_iter() { if ty.scope.ty == ComponentType::Reg.into() { block .declared_register_types .push(translate_register_ty(Some(name.into()), ty).map_err(wrap_err)?); } } let mut next_offset = Some(0u64); for child in iref.scope.instance_iter() { let parent_offset = if top { 0 } else { iref.instance.offset.unwrap_or_default() }; if child.instance.scope.ty == ComponentType::Reg.into() { let r = Rc::new(translate_register(child, next_offset).map_err(wrap_err)?); block.registers.push(r.clone()); next_offset = Some(r.offset + r.ty.width.in_bytes() * r.array_dimensions.iter().product::<u64>()); } else if child.instance.scope.ty == ComponentType::Mem.into() { let mem_size = calculate_mem_size(child); let start_offset = child .instance .offset .map(|o| parent_offset + o) .or(next_offset.map(|o| { // align according to RDL spec // TODO: when we upgrade Rust we can use o.next_multple_of() next_multiple_of(o, mem_size.next_power_of_two()) })) .expect("Offset not defined for memory and could not calculate automatically"); next_offset = Some(start_offset + calculate_mem_size(child)); block.registers.push(Rc::new( translate_mem(child, start_offset).map_err(wrap_err)?, )); } else if child.instance.scope.ty == ComponentType::RegFile.into() { let next_block = translate_block(child, false)?; let next_block_size = calculate_reg_size(&next_block); let start_offset = child .instance .offset .map(|o| parent_offset + o) .or(next_offset.map(|o| { if let Some(size) = next_block_size { // align according to RDL spec // TODO: when we upgrade Rust we can use o.next_multple_of() next_multiple_of(o, size.next_power_of_two()) } else { o } })) .expect( "Offset not defined for register file and could not calculate automatically", ); next_offset = calculate_reg_size(&next_block).map(|size| start_offset + size); block.sub_blocks.push(RegisterSubBlock::Single { block: next_block, start_offset, }); } else if child.instance.scope.ty == ComponentType::Signal.into() { // ignore next_offset = None; } else { panic!("Unknown component scope {:?}", child.instance.scope.ty); } } Ok(block) } pub fn translate_addrmap(addrmap: systemrdl::ParentScope) -> Result<Vec<RegisterBlock>, Error> { expect_instance_type(addrmap, ComponentType::AddrMap.into())?; let mut blocks = vec![]; for iref in addrmap.instance_iter() { blocks.push(translate_block(iref, true)?); } Ok(blocks) } #[cfg(test)] mod next_multiple_of_tests { use super::*; #[test] fn test_next_multiple_of() { assert_eq!(0, next_multiple_of(0, 3)); assert_eq!(3, next_multiple_of(1, 3)); assert_eq!(3, next_multiple_of(2, 3)); assert_eq!(3, next_multiple_of(3, 3)); assert_eq!(6, next_multiple_of(4, 3)); for i in 1..128 { assert_eq!(128, next_multiple_of(i, 128)); assert_eq!(256, next_multiple_of(128 + i, 128)); } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/lib/systemrdl/src/error.rs
ureg/lib/systemrdl/src/error.rs
/*++ Licensed under the Apache-2.0 license. --*/ use std::fmt::Display; use caliptra_systemrdl as systemrdl; #[derive(Clone, Debug, Eq, PartialEq)] pub enum Error { UnexpectedScopeType { expected: systemrdl::ScopeType, actual: systemrdl::ScopeType, }, AddressTooLarge(u64), OffsetNotDefined, WidthNotDefined, ValueNotDefined, FieldsCannotHaveMultipleDimensions, UnsupportedRegWidth(u64), AccessTypeNaUnsupported, ResetValueOnRegisterUnsupported, RdlError(systemrdl::RdlError<'static>), BlockError { block_name: String, err: Box<Error>, }, FieldError { field_name: String, err: Box<Error>, }, RegisterError { register_name: String, err: Box<Error>, }, RegisterTypeError { register_type_name: String, err: Box<Error>, }, EnumError { enum_name: String, err: Box<Error>, }, EnumVariantError { variant_name: String, err: Box<Error>, }, } impl Error { pub fn root_cause(&self) -> &Error { match self { Self::BlockError { err, .. } => err.root_cause(), Self::FieldError { err, .. } => err.root_cause(), Self::RegisterError { err, .. } => err.root_cause(), Self::RegisterTypeError { err, .. } => err.root_cause(), Self::EnumError { err, .. } => err.root_cause(), Self::EnumVariantError { err, .. } => err.root_cause(), err => err, } } } impl std::error::Error for Error {} impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::UnexpectedScopeType { expected, actual } => { write!(f, "Expect scope of type {expected:?} but was {actual:?}") } Self::AddressTooLarge(addr) => write!(f, "Address {addr:#x?} too large"), Self::OffsetNotDefined => write!(f, "offset was not defined"), Self::WidthNotDefined => write!(f, "width was not defined"), Self::ValueNotDefined => write!(f, "value was not defined"), Self::FieldsCannotHaveMultipleDimensions => { write!(f, "fields cannot have multiple dimensions") } Self::UnsupportedRegWidth(w) => write!(f, "Unsupported register width {w}"), Self::AccessTypeNaUnsupported => write!(f, "AccessType 'na' is not supported"), Self::ResetValueOnRegisterUnsupported => { write!(f, "reset value on register is unsupported") } Self::RdlError(err) => write!(f, "systemrdl error: {err}"), Self::BlockError { block_name, err } => write!(f, "block {block_name:?} {err}"), Self::FieldError { field_name, err } => write!(f, "field {field_name:?} {err}"), Self::RegisterError { register_name, err } => { write!(f, "register {register_name:?} {err}") } Self::RegisterTypeError { register_type_name, err, } => { write!(f, "reg_type {register_type_name:?} {err}") } Self::EnumError { enum_name, err } => write!(f, "enum {enum_name:?} {err}"), Self::EnumVariantError { variant_name, err } => { write!(f, "variant {variant_name:?} {err}") } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/lib/schema/src/lib.rs
ureg/lib/schema/src/lib.rs
/*++ Licensed under the Apache-2.0 license. --*/ use std::{ collections::{HashMap, HashSet}, rc::Rc, }; mod validate; #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct RegisterField { pub name: String, pub ty: FieldType, pub default_val: u64, pub comment: String, /// Describes any enumeration variants this field might have. pub enum_type: Option<Rc<Enum>>, /// The position of the field in the register, starting from the least /// significant bit. pub position: u8, /// The width of the field in bits pub width: u8, } impl RegisterField { /// A mask of the bits of this field. pub fn mask(&self) -> u64 { ((1u64 << self.width) - 1) << self.position } } #[cfg(test)] mod registerfield_tests { use super::*; #[test] fn test_mask() { assert_eq!( RegisterField { position: 0, width: 1, ..Default::default() } .mask(), 0x00000001 ); assert_eq!( RegisterField { position: 0, width: 2, ..Default::default() } .mask(), 0x00000003 ); assert_eq!( RegisterField { position: 0, width: 3, ..Default::default() } .mask(), 0x00000007 ); assert_eq!( RegisterField { position: 1, width: 3, ..Default::default() } .mask(), 0x0000000e ); assert_eq!( RegisterField { position: 8, width: 3, ..Default::default() } .mask(), 0x00000700 ); assert_eq!( RegisterField { position: 28, width: 4, ..Default::default() } .mask(), 0xf0000000 ); assert_eq!( RegisterField { position: 31, width: 1, ..Default::default() } .mask(), 0x80000000 ); } } /// Represents an memory-mapped I/O register. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Register { pub name: String, pub default_val: u64, pub comment: String, /// The offset of the register from the start of the register block. pub offset: u64, pub array_dimensions: Vec<u64>, pub ty: Rc<RegisterType>, } #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct RegisterType { /// The optional name of the register type pub name: Option<String>, pub width: RegisterWidth, /// The bit fields of the register. pub fields: Vec<RegisterField>, } impl RegisterType { /// Returns true if the types are equal except comments. fn equals_except_comment(&self, other: &RegisterType) -> bool { if self.name != other.name || self.width != other.width { return false; } if self.fields.len() != other.fields.len() { return false; } for i in 0..self.fields.len() { let mut a = self.fields[i].clone(); let mut b = other.fields[i].clone(); a.comment = "".to_string(); b.comment = "".to_string(); if a != b { return false; } } true } } #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub enum FieldType { #[default] /// Read/Write RW, /// Read-only RO, /// Write-only WO, /// Write to clear all bits WC, /// ? WRC, /// Write 1 to clear a bit, write 0 for no effect. W1C, /// Write 1 to set a bit, write 0 for no effect, W1S, } impl FieldType { pub fn can_read(&self) -> bool { match *self { FieldType::RO => true, FieldType::RW => true, FieldType::WO => false, FieldType::WC => false, FieldType::WRC => false, FieldType::W1C => true, FieldType::W1S => true, } } pub fn can_write(&self) -> bool { match *self { FieldType::RO => false, FieldType::RW => true, FieldType::WO => true, FieldType::WC => false, FieldType::WRC => false, FieldType::W1C => false, FieldType::W1S => false, } } pub fn can_clear(&self) -> bool { match *self { FieldType::RO => false, FieldType::RW => false, FieldType::WO => false, FieldType::WC => false, FieldType::WRC => false, FieldType::W1C => true, FieldType::W1S => false, } } pub fn can_set(&self) -> bool { match *self { FieldType::RO => false, FieldType::RW => false, FieldType::WO => false, FieldType::WC => false, FieldType::WRC => false, FieldType::W1C => false, FieldType::W1S => true, } } } #[derive(Clone, Debug, Eq, PartialEq)] pub enum RegisterSubBlock { Single { block: RegisterBlock, start_offset: u64, }, Array { block: RegisterBlock, start_offset: u64, stride: u64, len: usize, }, } impl RegisterSubBlock { pub fn block(&self) -> &RegisterBlock { match self { Self::Single { block, .. } => block, Self::Array { block, .. } => block, } } pub fn block_mut(&mut self) -> &mut RegisterBlock { match self { Self::Single { block, .. } => block, Self::Array { block, .. } => block, } } pub fn start_offset(&self) -> u64 { match self { Self::Single { start_offset, .. } => *start_offset, Self::Array { start_offset, .. } => *start_offset, } } } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct RegisterBlock { pub name: String, pub registers: Vec<Rc<Register>>, pub instances: Vec<RegisterBlockInstance>, pub sub_blocks: Vec<RegisterSubBlock>, // Register types that are "owned" by this block (but might be used by other register blocks) pub declared_register_types: Vec<Rc<RegisterType>>, } impl RegisterBlock { pub fn remove_enums(&mut self, register_fields: &[(&str, &str)]) { let mut selector: HashMap<&str, HashSet<&str>> = HashMap::new(); for (register_name, field_name) in register_fields.iter() { selector .entry(register_name) .or_default() .insert(field_name); } for reg in self.registers.iter_mut() { if let Some(selected_fields) = selector.get(reg.name.as_str()) { let reg = Rc::make_mut(reg); let reg_ty = Rc::make_mut(&mut reg.ty); for field in reg_ty.fields.iter_mut() { if selected_fields.contains(field.name.as_str()) { field.enum_type = None; } } } } } pub fn rename_enum_variants(&mut self, renames: &[(&str, &str)]) { let rename_map: HashMap<&str, &str> = renames.iter().cloned().collect(); for reg in self.registers.iter_mut() { let reg = Rc::make_mut(reg); let reg_ty = Rc::make_mut(&mut reg.ty); for field in reg_ty.fields.iter_mut() { if let Some(ref mut e) = field.enum_type { let e = Rc::make_mut(e); for variant in e.variants.iter_mut() { if let Some(new_name) = rename_map.get(variant.name.as_str()) { variant.name = new_name.to_string(); } } } } } } pub fn rename_fields(&mut self, renames: &[(&str, &str, &str)]) { let mut selector: HashMap<&str, HashMap<&str, &str>> = HashMap::new(); for (register_name, old_field_name, new_field_name) in renames.iter() { selector .entry(register_name) .or_default() .insert(old_field_name, new_field_name); } for reg in self.registers.iter_mut() { if let Some(selected_fields) = selector.get(reg.name.as_str()) { let reg = Rc::make_mut(reg); let reg_ty = Rc::make_mut(&mut reg.ty); for field in reg_ty.fields.iter_mut() { if let Some(new_field_name) = selected_fields.get(field.name.as_str()) { field.name = new_field_name.to_string(); } } } } } pub fn replace_field_comments(&mut self, replacements: &[(&str, &str)]) { let map: HashMap<&str, &str> = replacements.iter().cloned().collect(); for reg in self.registers.iter_mut() { let reg = Rc::make_mut(reg); let reg_ty = Rc::make_mut(&mut reg.ty); for field in reg_ty.fields.iter_mut() { if let Some(new_comment) = map.get(field.comment.as_str()) { field.comment = new_comment.to_string(); } } } } } pub use validate::ValidatedRegisterBlock; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct RegisterBlockInstance { pub name: String, pub address: u32, } #[derive(Clone, Copy, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)] pub enum RegisterWidth { _8 = 8, _16 = 16, #[default] _32 = 32, _64 = 64, _128 = 128, } impl RegisterWidth { pub fn in_bytes(self) -> u64 { match self { RegisterWidth::_8 => 1, RegisterWidth::_16 => 2, RegisterWidth::_32 => 4, RegisterWidth::_64 => 8, RegisterWidth::_128 => 16, } } pub fn rust_primitive_name(self) -> &'static str { match self { RegisterWidth::_8 => "u8", RegisterWidth::_16 => "u16", RegisterWidth::_32 => "u32", RegisterWidth::_64 => "u64", RegisterWidth::_128 => "u128", } } } #[derive(Clone, Debug, Default, Eq, PartialEq, Hash)] pub struct EnumVariant { pub name: String, pub value: u32, } #[derive(Clone, Debug, Default, Eq, PartialEq, Hash)] pub struct Enum { pub name: Option<String>, pub variants: Vec<EnumVariant>, pub bit_width: u8, } fn collect_used_reg_types(block: &RegisterBlock, used_types: &mut HashSet<Rc<RegisterType>>) { for reg in block.registers.iter() { used_types.insert(reg.ty.clone()); } for sb in block.sub_blocks.iter() { collect_used_reg_types(sb.block(), used_types); } } pub fn filter_unused_types(blocks: &mut [&mut ValidatedRegisterBlock]) { let mut used_types = HashSet::new(); for block in blocks.iter() { collect_used_reg_types(block.block(), &mut used_types); } for block in blocks.iter_mut() { block.filter_register_types(|ty| used_types.contains(ty)); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/ureg/lib/schema/src/validate.rs
ureg/lib/schema/src/validate.rs
/*++ Licensed under the Apache-2.0 license. --*/ use crate::Enum; use crate::EnumVariant; use crate::Register; use crate::RegisterBlock; use crate::RegisterField; use crate::RegisterSubBlock; use crate::RegisterType; use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; use std::collections::HashSet; use std::error::Error; use std::fmt::Display; use std::hash::Hash; use std::hash::Hasher; use std::rc::Rc; #[derive(Debug)] pub enum ValidationError { RegisterOffsetCollision { block_name: String, reg_name: String, offset: u64, }, BadArrayDimension { block_name: String, reg_name: String, }, DuplicateRegisterName { block_name: String, reg_name: String, }, DuplicateRegisterTypeName { block_name: String, reg_type_name: String, }, DuplicateEnumName { block_name: String, enum_name: String, }, DuplicateEnumVariantName { block_name: String, enum_name: String, variant_name: String, }, DuplicateEnumVariantValue { block_name: String, enum_name: String, variant_value: u32, variant_name0: String, variant_name1: String, }, } impl Display for ValidationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ValidationError::RegisterOffsetCollision { block_name, reg_name, offset, } => { write!( f, "Register offset collision at {block_name}::{reg_name} offset 0x{offset:x}" ) } ValidationError::BadArrayDimension { block_name, reg_name, } => { write!( f, "Bad array dimension at {block_name}::{reg_name}; can't be 0" ) } ValidationError::DuplicateRegisterName { block_name, reg_name, } => { write!(f, "Duplicate register {block_name}::{reg_name}") } ValidationError::DuplicateRegisterTypeName { block_name, reg_type_name, } => { write!(f, "Duplicate register type {block_name}::{reg_type_name}") } ValidationError::DuplicateEnumName { block_name, enum_name, } => { write!(f, "Duplicate enum name {block_name}::{enum_name}") } ValidationError::DuplicateEnumVariantName { block_name, enum_name, variant_name, } => { write!( f, "Duplicate enum variants with name {block_name}::{enum_name}::{variant_name}" ) } ValidationError::DuplicateEnumVariantValue { block_name, enum_name, variant_value, variant_name0, variant_name1, } => { write!(f, "Duplicate enum variants with value {variant_value}: {block_name}::{enum_name}::{{{variant_name0},{variant_name1}}}") } } } } impl Error for ValidationError { fn source(&self) -> Option<&(dyn Error + 'static)> { None } } #[derive(Debug)] pub struct ValidatedRegisterBlock { block: RegisterBlock, register_types: HashMap<String, Rc<RegisterType>>, enum_types: HashMap<String, Rc<Enum>>, } impl ValidatedRegisterBlock { pub fn block(&self) -> &RegisterBlock { &self.block } pub fn register_types(&self) -> &HashMap<String, Rc<RegisterType>> { &self.register_types } pub fn enum_types(&self) -> &HashMap<String, Rc<Enum>> { &self.enum_types } pub fn transform(&mut self, t: impl FnOnce(&mut ValidatedRegisterBlockTransformer)) { t(&mut ValidatedRegisterBlockTransformer(self)); self.update_enum_references(); self.update_reg_type_references(); self.update_enum_name_keys(); } fn update_enum_references(&mut self) { for reg_type in self.register_types.values_mut() { let reg_type = Rc::make_mut(reg_type); for field in reg_type.fields.iter_mut() { if let Some(ref enum_type) = field.enum_type { if let Some(ref name) = enum_type.name { field.enum_type = self.enum_types.get(name.as_str()).cloned(); } } } } } fn update_reg_type_references(&mut self) { for reg in self.block.registers.iter_mut() { let reg = Rc::make_mut(reg); if let Some(ref name) = reg.ty.name { reg.ty = self.register_types.get(name).unwrap().clone(); } } } fn update_enum_name_keys(&mut self) { // Clippy is wrong here; collect is required to keep the // the borrow checker happy (the loop cannot erase elements from // self.enum_types while self.enum_types is borrowed) #[allow(clippy::needless_collect)] let all_enums: Vec<(String, Rc<Enum>)> = self .enum_types .iter() .map(|(key, val)| (key.clone(), val.clone())) .collect(); for (key, val) in all_enums.into_iter() { if val.name.as_ref() != Some(&key) { self.enum_types.remove(&key); if let Some(new_name) = &val.name { if let Some(old_enum) = self.enum_types.insert(new_name.clone(), val.clone()) { panic!( "Enum collision with name {:?} {:?} vs {:?}", old_enum.name, old_enum, val ); } } } } } pub fn filter_register_types(&mut self, mut pred: impl FnMut(&Rc<RegisterType>) -> bool) { self.block.declared_register_types = self .block .declared_register_types .drain(..) .filter(&mut pred) .collect(); self.register_types = self .register_types .drain() .filter(|(_, ty)| pred(ty)) .collect(); } pub fn extract_subblock_array( &mut self, block_name: &str, register_prefixes: &[&str], type_index: usize, ) { struct MyRegInstance { index: usize, reg: Rc<Register>, } let register_prefixes: HashSet<String> = register_prefixes .iter() .cloned() .map(str::to_ascii_lowercase) .collect(); let mut instances_by_name: HashMap<String, Vec<MyRegInstance>> = HashMap::new(); self.block.registers.retain_mut(|reg| { let reg_name = reg .name .trim_end_matches(|c: char| c.is_ascii_digit()) .to_ascii_lowercase(); if !register_prefixes.contains(&reg_name) { // Keep this register in self.registers return true; } let Ok(index) = reg.name[reg_name.len()..].parse::<usize>() else { return true; }; let reg_name = reg_name.trim_start_matches(block_name); instances_by_name .entry(reg_name.to_string()) .or_default() .push(MyRegInstance { index, reg: reg.clone(), }); // Remove this register from self.registers, as it will be part // of the new subblock array false }); struct MyRegisterSpec { name: String, default_val: u64, min_offset: u64, stride: u64, count: usize, array_dimensions: Vec<u64>, ty: Rc<RegisterType>, comment: String, } let mut reg_specs: Vec<MyRegisterSpec> = instances_by_name .into_iter() .map(|(name, mut instances)| { instances.sort_by_key(|reg_inst| reg_inst.index); let stride = instances[1].reg.offset - instances[0].reg.offset; for (prev_inst, next_inst) in instances.iter().zip(instances[1..].iter()) { if next_inst.reg.offset - prev_inst.reg.offset != stride { panic!("Stride not consistent for register {:?}", name); } if next_inst.reg.default_val != prev_inst.reg.default_val { panic!("default_val not consistent for register {:?}", name); } if next_inst.reg.array_dimensions != prev_inst.reg.array_dimensions { panic!("array_dimensions not consistent for register {:?}", name); } } MyRegisterSpec { name, default_val: instances[0].reg.default_val, min_offset: instances .iter() .map(|reg_inst| reg_inst.reg.offset) .min() .unwrap(), stride, count: instances.len(), array_dimensions: instances[0].reg.array_dimensions.clone(), ty: instances[type_index].reg.ty.clone(), comment: instances[type_index].reg.comment.clone(), } }) .collect(); reg_specs.sort_by_key(|reg| reg.min_offset); let start_offset = reg_specs[0].min_offset; let block_array = RegisterSubBlock::Array { start_offset, stride: reg_specs[0].stride, len: reg_specs[0].count, block: RegisterBlock { name: block_name.to_string(), registers: reg_specs .into_iter() .map(|reg_spec| { Rc::new(Register { name: reg_spec.name.to_string(), default_val: reg_spec.default_val, comment: reg_spec.comment, array_dimensions: reg_spec.array_dimensions, offset: reg_spec.min_offset - start_offset, ty: reg_spec.ty, }) }) .collect(), ..Default::default() }, }; self.block.sub_blocks.push(block_array); } } pub struct ValidatedRegisterBlockTransformer<'a>(&'a mut ValidatedRegisterBlock); impl ValidatedRegisterBlockTransformer<'_> { pub fn add_enum_type(&mut self, e: Rc<Enum>) { if let Some(ref name) = e.name { if !self.0.enum_types.contains_key(name) { self.0.enum_types.insert(name.clone(), e); } } } // Replaces enums with the same name as the supplied enum. pub fn replace_enum_types(&mut self, enums: Vec<Rc<Enum>>) { for e in enums.into_iter() { if let Some(ref name) = e.name { self.0.enum_types.insert(name.clone(), e); } } } /// Finds enums with the exact same variants as the supplied enum, and /// renames them all to be the same as the supplied enum. pub fn rename_enums(&mut self, enums: Vec<Rc<Enum>>) { let mut hash = HashMap::<Enum, Rc<Enum>>::new(); for e in enums.into_iter() { let nameless_enum = Enum { name: None, ..(*e).clone() }; hash.insert(nameless_enum, e.clone()); } // Clippy is wrong here; collect is required to keep the // the borrow checker happy (the loop cannot modify // self.enum_types while self.enum_types is borrowed) #[allow(clippy::needless_collect)] let all_enums: Vec<Rc<Enum>> = self.0.enum_types.values().cloned().collect(); for e in all_enums.into_iter() { let nameless_enum = Enum { name: None, ..(*e).clone() }; if let Some(renamed_enum) = hash.get(&nameless_enum) { // Unwrap is safe because all enum names in a validate register block must be Some. self.0 .enum_types .insert(e.name.clone().unwrap(), renamed_enum.clone()); // We have to go through the hash-map at the end and replace all the names } } } pub fn remove_enum_types(&mut self, names: &[&str]) { for name in names.iter().cloned() { self.0.enum_types.remove(name); } } pub fn set_register_enum(&mut self, register_type: &str, field_name: &str, e: Rc<Enum>) { let enum_name = e.name.clone().unwrap(); self.0.enum_types.insert(enum_name, e.clone()); let reg_ty = self .0 .register_types .get_mut(register_type) .unwrap_or_else(|| panic!("Unknown register type {}", register_type)); let reg_ty = Rc::make_mut(reg_ty); for field in reg_ty.fields.iter_mut() { if field.name == field_name { field.enum_type = Some(e); return; } } panic!("Could not find field {field_name} in register type {register_type}"); } } fn common_with_placeholders(reg_names: &[&str]) -> (String, i64) { let shortest_len = match reg_names.iter().map(|s| s.len()).min() { Some(l) => l, None => return ("".into(), 0), }; let mut common_chars: Vec<Option<char>> = reg_names[0][0..shortest_len].chars().map(Some).collect(); for reg_name in reg_names[1..].iter() { for (a, b) in reg_name[0..shortest_len] .chars() .zip(common_chars.iter_mut()) { if Some(a) != *b { *b = None; } } } while common_chars.last() == Some(&None) { common_chars.pop(); } let x_char = if common_chars.iter().any(|c| { if let Some(c) = c { c.is_ascii_uppercase() } else { false } }) { 'X' } else { 'x' }; let score = common_chars .iter() .map(|c| i64::from(c.is_some())) .sum::<i64>() - 1; ( common_chars.iter().map(|c| c.unwrap_or(x_char)).collect(), score, ) } fn shortest_prefix<'a>(reg_names: &[&'a str]) -> &'a str { let mut iter = reg_names.iter().cloned(); if let Some(mut first) = iter.next() { for reg_name in iter { let common_len = reg_name .as_bytes() .iter() .zip(first.as_bytes()) .take_while(|t| t.0 == t.1) .count(); first = &first[0..common_len]; } first } else { "" } } fn shortest_suffix<'a>(reg_names: &[&'a str]) -> &'a str { let mut iter = reg_names.iter().cloned(); if let Some(mut first) = iter.next() { for reg_name in iter { let common_len = reg_name .as_bytes() .iter() .rev() .zip(first.as_bytes().iter().rev()) .take_while(|t| t.0 == t.1) .count(); first = &first[first.len() - common_len..]; } first } else { "" } } fn compute_common_name<'a>(reg_names: &'a [&'a str]) -> Option<String> { let shortest_prefix = shortest_prefix(reg_names); let shortest_suffix = shortest_suffix(reg_names); let mut options = vec![ (shortest_prefix.to_string(), shortest_prefix.len() as i64), (shortest_suffix.to_string(), shortest_suffix.len() as i64), common_with_placeholders(reg_names), ]; options.sort_by_key(|(_, score)| *score); options .pop() .map(|(name, _)| name) .and_then(|s| if s.is_empty() { None } else { Some(s) }) } fn hash_u64(v: &impl Hash) -> u64 { let mut h = DefaultHasher::new(); v.hash(&mut h); h.finish() } fn validate_enum(block_name: &str, e: &Enum) -> Result<(), ValidationError> { let mut variants_by_val: HashMap<u32, &EnumVariant> = HashMap::new(); let mut variants_by_name: HashMap<&str, &EnumVariant> = HashMap::new(); for variant in e.variants.iter() { if let Some(existing) = variants_by_val.insert(variant.value, variant) { return Err(ValidationError::DuplicateEnumVariantValue { block_name: block_name.into(), enum_name: e.name.clone().unwrap_or_else(|| "?".into()), variant_value: variant.value, variant_name0: existing.name.clone(), variant_name1: variant.name.clone(), }); } if let Some(existing) = variants_by_name.insert(&variant.name, variant) { return Err(ValidationError::DuplicateEnumVariantName { block_name: block_name.into(), enum_name: e.name.clone().unwrap_or_else(|| "?".into()), variant_name: existing.name.clone(), }); } } Ok(()) } fn is_meaningless_field_name(name: &str) -> bool { matches!(name.to_ascii_lowercase().as_str(), "val" | "value") } fn determine_enum_name(reg: &Register, field: &RegisterField) -> String { if reg.ty.fields.len() == 1 && is_meaningless_field_name(&field.name) { reg.name.clone() } else { field.name.clone() } } fn determine_enum_name_from_reg_ty(reg_ty: &RegisterType, field: &RegisterField) -> String { if reg_ty.fields.len() == 1 && is_meaningless_field_name(&field.name) { if let Some(ref reg_ty_name) = reg_ty.name { return reg_ty_name.into(); } } field.name.clone() } fn all_regs(regs: &[Rc<Register>], sub_blocks: &[RegisterSubBlock]) -> Vec<Rc<Register>> { let mut all_regs_vec: Vec<Rc<Register>> = regs.to_vec(); for sub in sub_blocks.iter() { all_regs_vec.extend(all_regs( sub.block().registers.as_slice(), sub.block().sub_blocks.as_slice(), )); } all_regs_vec } impl RegisterBlock { pub fn validate_and_dedup(mut self) -> Result<ValidatedRegisterBlock, ValidationError> { self.sort_by_offset(); let mut enum_types: HashMap<String, Rc<Enum>> = HashMap::new(); { let mut enum_names = HashMap::<Rc<Enum>, HashSet<String>>::new(); for reg in all_regs(&self.registers, &self.sub_blocks) { for field in reg.ty.fields.iter() { if let Some(ref e) = field.enum_type { enum_names .entry(e.clone()) .or_default() .insert(determine_enum_name(&reg, field)); } } } let mut new_enums: HashMap<Rc<Enum>, Rc<Enum>> = HashMap::new(); for (e, names) in enum_names.into_iter() { let names: Vec<&str> = names.iter().map(|n| n.as_str()).collect(); let name = e.name.clone().unwrap_or(match compute_common_name(&names) { Some(name) => name, None => { format!("Enum{:016x}", hash_u64(&e)) } }); new_enums.insert( e.clone(), Rc::new(Enum { name: Some(name), ..(*e).clone() }), ); } for reg_ty in self.declared_register_types.iter() { for field in reg_ty.fields.iter() { if let Some(ref e) = field.enum_type { let name = determine_enum_name_from_reg_ty(reg_ty, field); if e.name.is_some() { new_enums.insert(e.clone(), e.clone()); } else { new_enums.insert( e.clone(), Rc::new(Enum { name: Some(name), ..(**e).clone() }), ); } } } } self.clean_array_dimensions_field_enums(&mut new_enums)?; for e in new_enums.into_values() { let enum_name = e.name.clone().unwrap(); if enum_types.contains_key(&enum_name) { return Err(ValidationError::DuplicateEnumName { block_name: self.name, enum_name, }); } validate_enum(&self.name, &e)?; enum_types.insert(enum_name, e); } }; let mut regs_by_type = HashMap::<Rc<RegisterType>, Vec<Rc<Register>>>::new(); let mut used_names = HashSet::new(); let mut next_free_offset = 0; for reg in self.registers.iter() { if reg.offset < next_free_offset { return Err(ValidationError::RegisterOffsetCollision { block_name: self.name, reg_name: reg.name.clone(), offset: reg.offset, }); } next_free_offset = reg.offset + reg.ty.width.in_bytes(); if !used_names.insert(reg.name.clone()) { return Err(ValidationError::DuplicateRegisterName { block_name: self.name, reg_name: reg.name.clone(), }); } } for reg in all_regs(&self.registers, &self.sub_blocks) { regs_by_type .entry(reg.ty.clone()) .or_default() .push(reg.clone()); } let mut new_types = HashMap::<Rc<RegisterType>, Rc<RegisterType>>::new(); for (reg_type, regs) in regs_by_type.into_iter() { if reg_type.fields.is_empty() { continue; } let mut new_type = (*reg_type).clone(); let reg_names: Vec<&str> = regs.iter().map(|r| r.name.as_str()).collect(); if new_type.name.is_none() { new_type.name = compute_common_name(&reg_names); } if new_type.name.is_none() { new_type.name = Some(format!("Field{:016x}", hash_u64(&new_type))); } new_types.insert(reg_type, Rc::new(new_type)); } // Replace the old duplicate register types with the new shared types self.replace_register_types(&new_types); let mut register_types: HashMap<String, Rc<RegisterType>> = HashMap::new(); for reg_type in new_types.into_values() { let reg_type_name = reg_type.name.clone().unwrap(); if let Some(existing_reg_type) = register_types.get(&reg_type_name) { if existing_reg_type.equals_except_comment(&reg_type) { // skip continue; } println!("Duplicate: {:#?} vs {:#?}", existing_reg_type, reg_type); return Err(ValidationError::DuplicateRegisterTypeName { block_name: self.name, reg_type_name, }); } register_types.insert(reg_type_name, reg_type); } Ok(ValidatedRegisterBlock { block: self, register_types, enum_types, }) } fn clean_array_dimensions_field_enums( &mut self, new_enums: &mut HashMap<Rc<Enum>, Rc<Enum>>, ) -> Result<(), ValidationError> { for reg in self.registers.iter_mut() { Self::clean_array_dimensions_field_enums_one(&self.name, reg, new_enums)?; } for block in self.sub_blocks.iter_mut() { block .block_mut() .clean_array_dimensions_field_enums(new_enums)?; } Ok(()) } fn clean_array_dimensions_field_enums_one( block_name: &str, reg: &mut Rc<Register>, new_enums: &mut HashMap<Rc<Enum>, Rc<Enum>>, ) -> Result<(), ValidationError> { let reg = Rc::make_mut(reg); let ty = Rc::make_mut(&mut reg.ty); reg.array_dimensions.retain(|d| *d != 1); if reg.array_dimensions.contains(&0) { return Err(ValidationError::BadArrayDimension { block_name: block_name.to_owned(), reg_name: reg.name.clone(), }); } for field in ty.fields.iter_mut() { if let Some(ref mut e) = field.enum_type { if let Some(new_e) = new_enums.get(e) { *e = new_e.clone(); } } } Ok(()) } fn replace_register_types(&mut self, new_types: &HashMap<Rc<RegisterType>, Rc<RegisterType>>) { for reg in self.registers.iter_mut() { if let Some(new_type) = new_types.get(&reg.ty) { Rc::make_mut(reg).ty = new_type.clone(); } } for reg_type in self.declared_register_types.iter_mut() { if let Some(new_type) = new_types.get(reg_type) { *reg_type = new_type.clone(); } } for block in self.sub_blocks.iter_mut() { block.block_mut().replace_register_types(new_types); } } fn sort_by_offset(&mut self) { self.registers.sort_by_key(|reg| reg.offset); self.sub_blocks .sort_by_key(|sub_array| sub_array.start_offset()); for sb in self.sub_blocks.iter_mut() { sb.block_mut().sort_by_offset(); } } } #[cfg(test)] mod compute_reg_type_name_tests { use super::*; #[test] fn test() { assert_eq!( compute_common_name(&["UART0", "UART1", "UART10"]), Some("UART".into()) ); assert_eq!(compute_common_name(&["UART0"]), Some("UART0".into())); assert_eq!( compute_common_name(&["DIEPTCTL", "DOEPTCTL"]), Some("DXEPTCTL".into()) ); assert_eq!( compute_common_name(&["dieptctl", "doeptctl"]), Some("dxeptctl".into()) ); assert_eq!( compute_common_name(&["DIEPTCTL0", "DIEPTCTL1", "DOEPTCTL0", "DOEPTCTL1"]), Some("DXEPTCTL".into()) ); assert_eq!( compute_common_name(&["PROG_LB0_POST_OVRD", "LB0_POST_OVRD"]), Some("LB0_POST_OVRD".into()) ); } }
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/build.rs
hw-model/build.rs
// Licensed under the Apache-2.0 license fn main() { println!( "cargo:rustc-env=OPENOCD_SYSFSGPIO_ADAPTER_CFG=../../../hw/fpga/openocd_sysfsgpio_adapter.cfg" ); println!("cargo:rustc-env=OPENOCD_TAP_CFG=../../../hw/fpga/openocd_ss.cfg"); }
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/mcu_boot_status.rs
hw-model/src/mcu_boot_status.rs
/*++ Licensed under the Apache-2.0 license. File Name: boot_status.rs Abstract: MCU ROM boot status codes. --*/ use bitflags::bitflags; const ROM_INITIALIZATION_BASE: u16 = 1; const LIFECYCLE_MANAGEMENT_BASE: u16 = 65; const OTP_FUSE_OPERATIONS_BASE: u16 = 129; const CALIPTRA_SETUP_BASE: u16 = 193; const FIRMWARE_LOADING_BASE: u16 = 257; const FIELD_ENTROPY_BASE: u16 = 321; const BOOT_FLOW_BASE: u16 = 385; /// Status codes used by MCU ROM to log boot progress. #[repr(u16)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum McuRomBootStatus { // ROM Initialization Statuses RomStarted = ROM_INITIALIZATION_BASE, McuMemoryMapInitialized = ROM_INITIALIZATION_BASE + 1, StrapsLoaded = ROM_INITIALIZATION_BASE + 2, McuRegistersInitialized = ROM_INITIALIZATION_BASE + 3, SocManagerInitialized = ROM_INITIALIZATION_BASE + 4, MciInitialized = ROM_INITIALIZATION_BASE + 5, ResetReasonDetected = ROM_INITIALIZATION_BASE + 6, // Lifecycle Management Statuses LifecycleControllerInitialized = LIFECYCLE_MANAGEMENT_BASE, LifecycleTransitionStarted = LIFECYCLE_MANAGEMENT_BASE + 1, LifecycleTransitionComplete = LIFECYCLE_MANAGEMENT_BASE + 2, LifecycleTokenBurningStarted = LIFECYCLE_MANAGEMENT_BASE + 3, LifecycleTokenBurningComplete = LIFECYCLE_MANAGEMENT_BASE + 4, // OTP and Fuse Operations OtpControllerInitialized = OTP_FUSE_OPERATIONS_BASE, FusesReadFromOtp = OTP_FUSE_OPERATIONS_BASE + 1, WatchdogConfigured = OTP_FUSE_OPERATIONS_BASE + 2, // Caliptra Setup Statuses CaliptraBootGoAsserted = CALIPTRA_SETUP_BASE, I3cInitialized = CALIPTRA_SETUP_BASE + 1, CaliptraReadyForFuses = CALIPTRA_SETUP_BASE + 2, AxiUsersConfigured = CALIPTRA_SETUP_BASE + 3, FusesPopulatedToCaliptra = CALIPTRA_SETUP_BASE + 4, FuseWriteComplete = CALIPTRA_SETUP_BASE + 5, CaliptraReadyForMailbox = CALIPTRA_SETUP_BASE + 6, // Firmware Loading Statuses RiDownloadFirmwareCommandSent = FIRMWARE_LOADING_BASE, RiDownloadFirmwareComplete = FIRMWARE_LOADING_BASE + 1, FlashRecoveryFlowStarted = FIRMWARE_LOADING_BASE + 2, FlashRecoveryFlowComplete = FIRMWARE_LOADING_BASE + 3, FirmwareReadyDetected = FIRMWARE_LOADING_BASE + 4, FirmwareValidationComplete = FIRMWARE_LOADING_BASE + 5, CaliptraRuntimeReady = FIRMWARE_LOADING_BASE + 6, // Field Entropy Programming FieldEntropyProgrammingStarted = FIELD_ENTROPY_BASE, FieldEntropyPartition0Complete = FIELD_ENTROPY_BASE + 1, FieldEntropyPartition1Complete = FIELD_ENTROPY_BASE + 2, FieldEntropyPartition2Complete = FIELD_ENTROPY_BASE + 3, FieldEntropyPartition3Complete = FIELD_ENTROPY_BASE + 4, FieldEntropyProgrammingComplete = FIELD_ENTROPY_BASE + 5, // Boot Flow Completion ColdBootFlowStarted = BOOT_FLOW_BASE, ColdBootFlowComplete = BOOT_FLOW_BASE + 1, WarmResetFlowStarted = BOOT_FLOW_BASE + 2, WarmResetFlowComplete = BOOT_FLOW_BASE + 3, FirmwareUpdateFlowStarted = BOOT_FLOW_BASE + 4, FirmwareUpdateFlowComplete = BOOT_FLOW_BASE + 5, HitlessUpdateFlowStarted = BOOT_FLOW_BASE + 6, HitlessUpdateFlowComplete = BOOT_FLOW_BASE + 7, } impl From<McuRomBootStatus> for u16 { /// Converts to this type from the input type. fn from(status: McuRomBootStatus) -> u16 { status as u16 } } pub struct McuBootMilestones(u16); bitflags! { impl McuBootMilestones: u16 { const ROM_STARTED = 0b1 << 0; const CPTRA_BOOT_GO_ASSERTED = 0b1 << 1; const CPTRA_FUSES_WRITTEN = 0b1 << 2; const RI_DOWNLOAD_COMPLETED = 0b1 << 3; const FLASH_RECOVERY_FLOW_COMPLETED = 0b1 << 4; const COLD_BOOT_FLOW_COMPLETE = 0b1 << 5; const WARM_RESET_FLOW_COMPLETE = 0b1 << 6; const FIRMWARE_BOOT_FLOW_COMPLETE = 0b1 << 7; } } impl From<u16> for McuBootMilestones { fn from(value: u16) -> McuBootMilestones { McuBootMilestones(value) } } impl From<McuBootMilestones> for u16 { fn from(value: McuBootMilestones) -> u16 { value.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/src/lib.rs
hw-model/src/lib.rs
// Licensed under the Apache-2.0 license use api::CaliptraApiError; use caliptra_api as api; use caliptra_api::mailbox::MailboxReq; use caliptra_api::SocManager; use caliptra_api_types as api_types; use caliptra_emu_bus::{Bus, Event}; use core::panic; use std::path::PathBuf; use std::str::FromStr; use std::sync::mpsc; use std::{ error::Error, fmt::Display, io::{stdout, ErrorKind, Write}, }; use caliptra_hw_model_types::{ ErrorInjectionMode, EtrngResponse, HexBytes, HexSlice, RandomEtrngResponses, RandomNibbles, DEFAULT_CPTRA_OBF_KEY, DEFAULT_CSR_HMAC_KEY, }; use zerocopy::{FromBytes, FromZeros, IntoBytes}; use caliptra_emu_periph::MailboxRequester; use caliptra_registers::mbox; use caliptra_registers::mbox::enums::{MboxFsmE, MboxStatusE}; use caliptra_registers::soc_ifc::regs::{ CptraItrngEntropyConfig0WriteVal, CptraItrngEntropyConfig1WriteVal, }; use rand::{rngs::StdRng, SeedableRng}; use sha2::Digest; mod bmc; mod fpga_regs; pub mod jtag; pub mod keys; pub mod lcc; pub mod mmio; mod model_emulated; pub mod openocd; pub mod otp_digest; pub mod otp_provision; mod recovery; pub mod xi3c; mod bus_logger; #[cfg(feature = "verilator")] mod model_verilated; #[cfg(feature = "fpga_realtime")] mod model_fpga_realtime; #[cfg(feature = "fpga_subsystem")] mod mcu_boot_status; #[cfg(feature = "fpga_subsystem")] mod model_fpga_subsystem; mod output; mod rv32_builder; pub use api::mailbox::mbox_write_fifo; pub use api_types::{DbgManufServiceRegReq, DeviceLifecycle, Fuses, SecurityState, U4}; pub use caliptra_emu_bus::BusMmio; pub use caliptra_emu_cpu::{CodeRange, ImageInfo, StackInfo, StackRange}; pub use output::ExitStatus; pub use output::Output; pub use model_emulated::ModelEmulated; #[cfg(feature = "verilator")] pub use model_verilated::ModelVerilated; use ureg::MmioMut; #[cfg(feature = "fpga_realtime")] pub use model_fpga_realtime::ModelFpgaRealtime; #[cfg(feature = "fpga_realtime")] pub use model_fpga_realtime::OpenOcdError; #[cfg(feature = "fpga_subsystem")] pub use keys::{DEFAULT_LIFECYCLE_RAW_TOKEN, DEFAULT_MANUF_DEBUG_UNLOCK_RAW_TOKEN}; #[cfg(feature = "fpga_subsystem")] pub use model_fpga_subsystem::ModelFpgaSubsystem; #[cfg(feature = "fpga_subsystem")] pub use model_fpga_subsystem::XI3CWrapper; /// Ideally, general-purpose functions would return `impl HwModel` instead of /// `DefaultHwModel` to prevent users from calling functions that aren't /// available on all HwModel implementations. Unfortunately, rust-analyzer /// (used by IDEs) can't fully resolve associated types from `impl Trait`, so /// such functions should use `DefaultHwModel` until they fix that. Users should /// treat `DefaultHwModel` as if it were `impl HwModel`. #[cfg(all( not(feature = "verilator"), not(feature = "fpga_realtime"), not(feature = "fpga_subsystem") ))] pub type DefaultHwModel = ModelEmulated; #[cfg(feature = "verilator")] pub type DefaultHwModel = ModelVerilated; #[cfg(feature = "fpga_realtime")] pub type DefaultHwModel = ModelFpgaRealtime; #[cfg(feature = "fpga_subsystem")] pub type DefaultHwModel = ModelFpgaSubsystem; pub const DEFAULT_APB_PAUSER: u32 = 0x01; pub type ModelCallback = Box<dyn FnOnce(&mut DefaultHwModel)>; pub struct OcpLockState { pub mek: [u8; 64], } /// Constructs an HwModel based on the cargo features and environment /// variables. Most test cases that need to construct a HwModel should use this /// function over HwModel::new_unbooted(). /// /// The model returned by this function does not have any fuses programmed and /// is not yet ready to execute code in the microcontroller. Most test cases /// should use [`new`] instead. pub fn new_unbooted(params: InitParams) -> Result<DefaultHwModel, Box<dyn Error>> { let summary = params.summary(); DefaultHwModel::new_unbooted(params).inspect(|hw| { println!( "Using hardware-model {} trng={:?}", hw.type_name(), hw.trng_mode() ); println!("{summary:#?}"); }) } /// Constructs an HwModel based on the cargo features and environment variables, /// and boot it to the point where CPU execution can occur. This includes /// programming the fuses, initializing the boot_fsm state machine, and /// (optionally) uploading firmware. Most test cases that need to construct a /// HwModel should use this function over [`HwModel::new()`] and /// [`crate::new_unbooted`]. pub fn new( init_params: InitParams, boot_params: BootParams, ) -> Result<DefaultHwModel, Box<dyn Error>> { DefaultHwModel::new(init_params, boot_params) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum TrngMode { // soc_ifc_reg.CPTRA_HW_CONFIG.iTRNG_en will be true. // When running with the verlated hw-model, the itrng compile-time feature // must be enabled or initialization will fail. Internal, // soc_ifc_reg.CPTRA_HW_CONFIG.iTRNG_en will be false. // When running with the verlated hw-model, the itrng compile-time feature // must be disabled or initialization will fail. External, } impl TrngMode { pub fn resolve(mode: Option<Self>) -> Self { if let Some(mode) = mode { mode } else if cfg!(feature = "itrng") { TrngMode::Internal } else { TrngMode::External } } } const EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES: u64 = 40_000_000; // 40 million cycles pub struct SubsystemInitParams<'a> { // Optionally, provide MCU ROM; otherwise use the pre-built ROM image, if needed pub mcu_rom: Option<&'a [u8]>, // Consume MCU UART log with Caliptra UART log pub enable_mcu_uart_log: bool, // Whether or not to set the RMA / scrap Physical Presence Detection signal. pub rma_or_scrap_ppd: bool, // Raw unlock token cSHAKE128 hash. pub raw_unlock_token_hash: [u32; 4], // Number of public key hashes for production debug unlock levels. // Note: does not have to match number of keypairs in prod_dbg_unlock_keypairs above if default // OTP settings are used. pub num_prod_dbg_unlock_pk_hashes: u32, // Offset of public key hashes in PROD_DEBUG_UNLOCK_PK_HASH_REG register bank for production debug unlock. pub prod_dbg_unlock_pk_hashes_offset: u32, } impl Default for SubsystemInitParams<'_> { fn default() -> Self { Self { mcu_rom: Default::default(), enable_mcu_uart_log: Default::default(), rma_or_scrap_ppd: Default::default(), raw_unlock_token_hash: [0xf0930a4d, 0xde8a30e6, 0xd1c8cbba, 0x896e4a11], num_prod_dbg_unlock_pk_hashes: Default::default(), prod_dbg_unlock_pk_hashes_offset: Default::default(), } } } pub struct InitParams<'a> { // Fuse settings pub fuses: Fuses, // The contents of the boot ROM pub rom: &'a [u8], // The initial contents of the DCCM SRAM pub dccm: &'a [u8], // The initial contents of the ICCM SRAM pub iccm: &'a [u8], pub log_writer: Box<dyn std::io::Write>, pub security_state: SecurityState, pub dbg_manuf_service: DbgManufServiceRegReq, pub subsystem_mode: bool, pub ocp_lock_en: bool, pub uds_fuse_row_granularity_64: bool, pub otp_dai_idle_bit_offset: u32, pub otp_direct_access_cmd_reg_offset: u32, // Keypairs for production debug unlock levels, from low to high // ECC384 and MLDSA87 keypairs (in hardware format i.e. little-endian) pub prod_dbg_unlock_keypairs: Vec<(&'a [u8; 96], &'a [u8; 2592])>, // Whether or not to set the debug_intent signal. pub debug_intent: bool, // Whether or not to set the BootFSM break signal. pub bootfsm_break: bool, // The silicon obfuscation key passed to caliptra_top. pub cptra_obf_key: [u32; 8], // The silicon csr hmac key passed to caliptra_top. pub csr_hmac_key: [u32; 16], // 4-bit nibbles of raw entropy to feed into the internal TRNG (ENTROPY_SRC // peripheral). pub itrng_nibbles: Box<dyn Iterator<Item = u8> + Send>, // Pre-conditioned TRNG responses to return over the soc_ifc CPTRA_TRNG_DATA // registers in response to requests via CPTRA_TRNG_STATUS pub etrng_responses: Box<dyn Iterator<Item = EtrngResponse> + Send>, // When None, use the itrng compile-time feature to decide which mode to use. pub trng_mode: Option<TrngMode>, // If true (and the HwModel supports it), initialize the SRAM with random // data. This will likely result in a ECC double-bit error if the CPU // attempts to read uninitialized memory. pub random_sram_puf: bool, // A trace path to use. If None, the CPTRA_TRACE_PATH environment variable // will be used pub trace_path: Option<PathBuf>, // Information about the stack Caliptra is using. When set the emulator will check if the stack // overflows. pub stack_info: Option<StackInfo>, pub soc_user: MailboxRequester, // Initial contents of the test SRAM pub test_sram: Option<&'a [u8]>, // Subsystem initialization parameters. pub ss_init_params: SubsystemInitParams<'a>, /// ROM Mailbox Handler callback /// Some tests need to access the ROM mailbox, and then continue booting to RT pub rom_callback: Option<ModelCallback>, } impl Default for InitParams<'_> { fn default() -> Self { let seed = std::env::var("CPTRA_TRNG_SEED") .ok() .and_then(|s| u64::from_str(&s).ok()); let itrng_nibbles: Box<dyn Iterator<Item = u8> + Send> = if let Some(seed) = seed { Box::new(RandomNibbles(StdRng::seed_from_u64(seed))) } else { Box::new(RandomNibbles(StdRng::from_entropy())) }; let etrng_responses: Box<dyn Iterator<Item = EtrngResponse> + Send> = if let Some(seed) = seed { Box::new(RandomEtrngResponses(StdRng::seed_from_u64(seed))) } else { Box::new(RandomEtrngResponses::new_from_stdrng()) }; Self { fuses: Default::default(), rom: Default::default(), dccm: Default::default(), iccm: Default::default(), log_writer: Box::new(stdout()), security_state: *SecurityState::default() .set_device_lifecycle(DeviceLifecycle::Unprovisioned), dbg_manuf_service: Default::default(), subsystem_mode: false, ocp_lock_en: cfg!(feature = "ocp-lock"), uds_fuse_row_granularity_64: true, otp_dai_idle_bit_offset: 30, otp_direct_access_cmd_reg_offset: 0x80, prod_dbg_unlock_keypairs: Default::default(), debug_intent: false, bootfsm_break: false, cptra_obf_key: DEFAULT_CPTRA_OBF_KEY, csr_hmac_key: DEFAULT_CSR_HMAC_KEY, itrng_nibbles, etrng_responses, trng_mode: Some(if cfg!(feature = "itrng") { TrngMode::Internal } else { TrngMode::External }), random_sram_puf: true, trace_path: None, stack_info: None, soc_user: MailboxRequester::SocUser(1u32), test_sram: None, ss_init_params: Default::default(), rom_callback: None, } } } impl InitParams<'_> { fn summary(&self) -> InitParamsSummary { InitParamsSummary { rom_sha384: sha2::Sha384::digest(self.rom).into(), obf_key: self.cptra_obf_key, security_state: self.security_state, hmac_csr_key: self.csr_hmac_key, debug_locked: self.security_state.debug_locked(), } } } pub struct InitParamsSummary { rom_sha384: [u8; 48], obf_key: [u32; 8], hmac_csr_key: [u32; 16], security_state: SecurityState, debug_locked: bool, } impl std::fmt::Debug for InitParamsSummary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("InitParamsSummary") .field("rom_sha384", &HexBytes(&self.rom_sha384)) .field("obf_key", &HexSlice(&self.obf_key)) .field("hmac_csr_key", &HexSlice(&self.hmac_csr_key)) .field("security_state", &self.security_state) .field("debug_locked", &self.debug_locked) .finish() } } fn trace_path_or_env(trace_path: Option<PathBuf>) -> Option<PathBuf> { if let Some(trace_path) = trace_path { return Some(trace_path); } std::env::var("CPTRA_TRACE_PATH").ok().map(PathBuf::from) } #[derive(Clone)] pub struct BootParams<'a> { pub fw_image: Option<&'a [u8]>, pub initial_dbg_manuf_service_reg: u32, pub initial_repcnt_thresh_reg: Option<CptraItrngEntropyConfig1WriteVal>, pub initial_adaptp_thresh_reg: Option<CptraItrngEntropyConfig0WriteVal>, pub valid_axi_user: Vec<u32>, pub wdt_timeout_cycles: u64, // SoC manifest passed via the recovery interface pub soc_manifest: Option<&'a [u8]>, // MCU firmware image passed via the recovery interface pub mcu_fw_image: Option<&'a [u8]>, } impl Default for BootParams<'_> { fn default() -> Self { Self { fw_image: Default::default(), initial_dbg_manuf_service_reg: Default::default(), initial_repcnt_thresh_reg: Default::default(), initial_adaptp_thresh_reg: Default::default(), valid_axi_user: vec![0, 1, 2, 3, 4], wdt_timeout_cycles: EXPECTED_CALIPTRA_BOOT_TIME_IN_CYCLES, soc_manifest: Default::default(), mcu_fw_image: Default::default(), } } } #[derive(Debug, Eq, PartialEq)] pub enum ModelError { MailboxCmdFailed(u32), UnableToSetPauser, UnableToLockMailbox, BufferTooLargeForMailbox, UploadFirmwareUnexpectedResponse, UnknownCommandStatus(u32), NotReadyForFwErr, ReadyForFirmwareTimeout { cycles: u32, }, ProvidedIccmTooLarge, ProvidedDccmTooLarge, UnexpectedMailboxFsmStatus { expected: u32, actual: u32, }, UploadMeasurementResponseError, UnableToReadMailbox, MailboxNoResponseData, MailboxReqTypeTooSmall, MailboxRespTypeTooSmall, MailboxUnexpectedResponseLen { expected_min: u32, expected_max: u32, actual: u32, }, MailboxRespInvalidChecksum { expected: u32, actual: u32, }, MailboxRespInvalidFipsStatus(u32), MailboxTimeout, ReadBufferTooSmall, FuseDoneNotSet, FusesAlreadyInitialized, StashMeasurementFailed, SubsystemSramError, } impl From<CaliptraApiError> for ModelError { fn from(error: CaliptraApiError) -> Self { match error { CaliptraApiError::UnableToLockMailbox => ModelError::UnableToLockMailbox, CaliptraApiError::UnableToReadMailbox => ModelError::UnableToReadMailbox, CaliptraApiError::BufferTooLargeForMailbox => ModelError::BufferTooLargeForMailbox, CaliptraApiError::UnknownCommandStatus(code) => ModelError::UnknownCommandStatus(code), CaliptraApiError::MailboxTimeout => ModelError::MailboxTimeout, CaliptraApiError::MailboxCmdFailed(code) => ModelError::MailboxCmdFailed(code), CaliptraApiError::UnexpectedMailboxFsmStatus { expected, actual } => { ModelError::UnexpectedMailboxFsmStatus { expected, actual } } CaliptraApiError::MailboxRespInvalidFipsStatus(status) => { ModelError::MailboxRespInvalidFipsStatus(status) } CaliptraApiError::MailboxRespInvalidChecksum { expected, actual } => { ModelError::MailboxRespInvalidChecksum { expected, actual } } CaliptraApiError::MailboxRespTypeTooSmall => ModelError::MailboxRespTypeTooSmall, CaliptraApiError::MailboxReqTypeTooSmall => ModelError::MailboxReqTypeTooSmall, CaliptraApiError::MailboxNoResponseData => ModelError::MailboxNoResponseData, CaliptraApiError::MailboxUnexpectedResponseLen { expected_min, expected_max, actual, } => ModelError::MailboxUnexpectedResponseLen { expected_min, expected_max, actual, }, CaliptraApiError::UploadFirmwareUnexpectedResponse => { ModelError::UploadFirmwareUnexpectedResponse } CaliptraApiError::UploadMeasurementResponseError => { ModelError::UploadMeasurementResponseError } caliptra_api::CaliptraApiError::ReadBuffTooSmall => ModelError::ReadBufferTooSmall, caliptra_api::CaliptraApiError::FuseDoneNotSet => ModelError::FuseDoneNotSet, caliptra_api::CaliptraApiError::FusesAlreadyIniitalized => { ModelError::FusesAlreadyInitialized } caliptra_api::CaliptraApiError::StashMeasurementFailed => { ModelError::StashMeasurementFailed } caliptra_api::CaliptraApiError::UnableToSetPauser => ModelError::UnableToSetPauser, } } } impl Error for ModelError {} impl Display for ModelError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ModelError::MailboxCmdFailed(err) => write!(f, "Mailbox command failed. fw_err={err}"), ModelError::UnableToLockMailbox => write!(f, "Unable to lock mailbox"), ModelError::BufferTooLargeForMailbox => write!(f, "Buffer too large for mailbox"), ModelError::UploadFirmwareUnexpectedResponse => { write!(f, "Received unexpected response after uploading firmware") } ModelError::UnknownCommandStatus(status) => write!( f, "Received unknown command status from mailbox peripheral: 0x{status:x}" ), ModelError::NotReadyForFwErr => write!(f, "Not ready for firmware"), ModelError::ReadyForFirmwareTimeout { cycles } => write!( f, "Ready-for-firmware signal not received after {cycles} cycles" ), ModelError::ProvidedDccmTooLarge => write!(f, "Provided DCCM image too large"), ModelError::ProvidedIccmTooLarge => write!(f, "Provided ICCM image too large"), ModelError::UnexpectedMailboxFsmStatus { expected, actual } => write!( f, "Expected mailbox FSM status to be {expected}, was {actual}" ), ModelError::UploadMeasurementResponseError => { write!(f, "Error in response after uploading measurement") } ModelError::UnableToReadMailbox => write!(f, "Unable to read mailbox regs"), ModelError::MailboxNoResponseData => { write!(f, "Expected response data but none was found") } ModelError::MailboxReqTypeTooSmall => { write!(f, "Mailbox request type too small to contain header") } ModelError::MailboxRespTypeTooSmall => { write!(f, "Mailbox response type too small to contain header") } ModelError::MailboxUnexpectedResponseLen { expected_min, expected_max, actual, } => { write!( f, "Expected mailbox response lenth min={expected_min} max={expected_max}, was {actual}" ) } ModelError::MailboxRespInvalidChecksum { expected, actual } => { write!( f, "Mailbox response had invalid checksum: expected {expected}, was {actual}" ) } ModelError::MailboxRespInvalidFipsStatus(status) => { write!( f, "Mailbox response had non-success FIPS status: 0x{status:x}" ) } ModelError::MailboxTimeout => { write!(f, "Mailbox timed out in busy state") } ModelError::ReadBufferTooSmall => { write!(f, "Cant read mailbox because read buffer too small") } ModelError::FuseDoneNotSet => { write!(f, "Fuse Wr Done bit not set") } ModelError::FusesAlreadyInitialized => { write!(f, "Fuses already initialized") } ModelError::StashMeasurementFailed => { write!(f, "Stash measurement request failed") } ModelError::UnableToSetPauser => { write!(f, "Valid PAUSER locked") } ModelError::SubsystemSramError => { write!(f, "Writing to MCU SRAM failed") } } } } pub struct MailboxRequest { pub cmd: u32, pub data: Vec<u8>, } pub struct MailboxRecvTxn<'a, TModel: HwModel> { model: &'a mut TModel, pub req: MailboxRequest, } impl<Model: HwModel> MailboxRecvTxn<'_, Model> { pub fn respond_success(self) { self.complete(MboxStatusE::CmdComplete); } pub fn respond_failure(self) { self.complete(MboxStatusE::CmdFailure); } pub fn respond_with_data(self, data: &[u8]) -> Result<(), ModelError> { let mbox = self.model.soc_mbox(); let mbox_fsm_ps = mbox.status().read().mbox_fsm_ps(); if !mbox_fsm_ps.mbox_execute_soc() { return Err(ModelError::UnexpectedMailboxFsmStatus { expected: MboxFsmE::MboxExecuteSoc as u32, actual: mbox_fsm_ps as u32, }); } mbox_write_fifo(&mbox, data)?; drop(mbox); self.complete(MboxStatusE::DataReady); Ok(()) } fn complete(self, status: MboxStatusE) { self.model .soc_mbox() .status() .write(|w| w.status(|_| status)); // mbox_fsm_ps isn't updated immediately after execute is cleared (!?), // so step an extra clock cycle to wait for fm_ps to update self.model.step(); } } fn mbox_read_fifo(mbox: mbox::RegisterBlock<impl MmioMut>) -> Vec<u8> { let dlen = mbox.dlen().read() as usize; let mut buf = vec![0; dlen]; buf.resize(dlen, 0); let _ = caliptra_api::mailbox::mbox_read_fifo(mbox, buf.as_mut_slice()); buf } /// Firmware Load Command Opcode const FW_LOAD_CMD_OPCODE: u32 = 0x4657_4C44; /// The download firmware from recovery interface Opcode const RI_DOWNLOAD_FIRMWARE_OPCODE: u32 = 0x5249_4644; /// Stash Measurement Command Opcode. const STASH_MEASUREMENT_CMD_OPCODE: u32 = 0x4D45_4153; // Represents a emulator or simulation of the caliptra hardware, to be called // from tests. Typically, test cases should use [`crate::new()`] to create a model // based on the cargo features (and any model-specific environment variables). pub trait HwModel: SocManager { type TBus<'a>: Bus where Self: 'a; /// Create a model. Most high-level tests should use [`new()`] /// instead. fn new_unbooted(params: InitParams) -> Result<Self, Box<dyn Error>> where Self: Sized; /// Create a model, and boot it to the point where CPU execution can /// occur. This includes programming the fuses, initializing the /// boot_fsm state machine, and (optionally) uploading firmware. fn new(init_params: InitParams, boot_params: BootParams) -> Result<Self, Box<dyn Error>> where Self: Sized, { let init_params_summary = init_params.summary(); let mut hw: Self = HwModel::new_unbooted(init_params)?; let hw_rev_id = hw.soc_ifc().cptra_hw_rev_id().read(); println!( "Using hardware-model {} trng={:?} hw_rev_id={{cptra_generation=0x{:04x}, soc_stepping_id={:04x}}}", hw.type_name(), hw.trng_mode(), hw_rev_id.cptra_generation(), hw_rev_id.soc_stepping_id() ); println!("{init_params_summary:#?}"); hw.boot(boot_params)?; Ok(hw) } fn boot(&mut self, boot_params: BootParams) -> Result<(), Box<dyn Error>> where Self: Sized, { HwModel::init_fuses(self); self.soc_ifc() .cptra_dbg_manuf_service_reg() .write(|_| boot_params.initial_dbg_manuf_service_reg); self.soc_ifc() .cptra_wdt_cfg() .at(0) .write(|_| boot_params.wdt_timeout_cycles as u32); self.soc_ifc() .cptra_wdt_cfg() .at(1) .write(|_| (boot_params.wdt_timeout_cycles >> 32) as u32); if let Some(reg) = boot_params.initial_repcnt_thresh_reg { self.soc_ifc() .cptra_i_trng_entropy_config_1() .write(|_| reg); } if let Some(reg) = boot_params.initial_adaptp_thresh_reg { self.soc_ifc() .cptra_i_trng_entropy_config_0() .write(|_| reg); } // Set up the PAUSER as valid for the mailbox (using index 0) self.setup_mailbox_users(boot_params.valid_axi_user.as_slice()) .map_err(ModelError::from)?; writeln!(self.output().logger(), "writing to cptra_bootfsm_go")?; self.soc_ifc().cptra_bootfsm_go().write(|w| w.go(true)); self.step(); if let Some(fw_image) = boot_params.fw_image { const MAX_WAIT_CYCLES: u32 = 20_000_000; let mut cycles = 0; while !self.ready_for_fw() { // If GENERATE_IDEVID_CSR was set then we need to clear cptra_dbg_manuf_service_reg // once the CSR is ready to continue making progress. // // Generally the CSR should be read from the mailbox at this point, but to // accommodate test cases that ignore the CSR mailbox, we will ignore it here. if self.soc_ifc().cptra_flow_status().read().idevid_csr_ready() { self.soc_ifc().cptra_dbg_manuf_service_reg().write(|_| 0); } self.step(); cycles += 1; if cycles > MAX_WAIT_CYCLES { return Err(ModelError::ReadyForFirmwareTimeout { cycles }.into()); } } writeln!(self.output().logger(), "ready_for_fw is high")?; self.cover_fw_image(fw_image); let subsystem_mode = self.soc_ifc().cptra_hw_config().read().subsystem_mode_en(); writeln!( self.output().logger(), "mode {}", if subsystem_mode { "subsystem" } else { "passive" } )?; if subsystem_mode { self.upload_firmware_rri( fw_image, boot_params.soc_manifest, boot_params.mcu_fw_image, )?; } else { self.upload_firmware(fw_image)?; } } Ok(()) } /// The type name of this model fn type_name(&self) -> &'static str; /// The TRNG mode used by this model. fn trng_mode(&self) -> TrngMode; /// Trigger a warm reset and advance the boot fn warm_reset_flow(&mut self) -> Result<(), Box<dyn Error>> where Self: Sized, { // Store non-persistent config regs set at boot let dbg_manuf_service_reg = self.soc_ifc().cptra_dbg_manuf_service_reg().read(); let i_trng_entropy_config_1: u32 = self.soc_ifc().cptra_i_trng_entropy_config_1().read().into(); let i_trng_entropy_config_0: u32 = self.soc_ifc().cptra_i_trng_entropy_config_0().read().into(); // Store mbox pausers let mut valid_pausers: Vec<u32> = Vec::new(); for i in 0..caliptra_api::soc_mgr::NUM_PAUSERS { // Only store if locked if self .soc_ifc() .cptra_mbox_axi_user_lock() .at(i) .read() .lock() { valid_pausers.push( self.soc_ifc() .cptra_mbox_axi_user_lock() .at(i) .read() .into(), ); } } // Perform the warm reset self.warm_reset(); // Write back stored values and let boot progress // Fuse values will remain, just re-set fuse done self.soc_ifc().cptra_fuse_wr_done().write(|w| w.done(true)); self.soc_ifc() .cptra_dbg_manuf_service_reg() .write(|_| dbg_manuf_service_reg); self.soc_ifc() .cptra_i_trng_entropy_config_1() .write(|_| i_trng_entropy_config_1.into()); self.soc_ifc() .cptra_i_trng_entropy_config_0() .write(|_| i_trng_entropy_config_0.into()); // Re-set the valid pausers self.setup_mailbox_users(valid_pausers.as_slice()) .map_err(ModelError::from)?; // Continue boot writeln!(self.output().logger(), "writing to cptra_bootfsm_go")?; self.soc_ifc().cptra_bootfsm_go().write(|w| w.go(true)); self.step(); Ok(()) } /// The APB bus from the SoC to Caliptra /// /// WARNING: Reading or writing to this bus may involve the Caliptra /// microcontroller executing a few instructions fn apb_bus(&mut self) -> Self::TBus<'_>; /// Step execution ahead one clock cycle. fn step(&mut self); /// Any UART-ish output written by the microcontroller will be available here. fn output(&mut self) -> &mut Output; /// Execute until the result of `predicate` becomes true. fn step_until(&mut self, mut predicate: impl FnMut(&mut Self) -> bool) { while !predicate(self) { self.step(); } } /// Toggle reset pins and wait for ready_for_fuses fn warm_reset(&mut self) { // To be overridden by HwModel implementations that support this panic!("warm_reset unimplemented"); } /// Toggle reset/pwrgood pins and wait for ready_for_fuses fn cold_reset(&mut self) { // To be overridden by HwModel implementations that support this panic!("cold_reset unimplemented"); } /// Returns true if the microcontroller has signalled that it is ready for /// firmware to be written to the mailbox. For RTL implementations, this /// should come via a caliptra_top wire rather than an APB register. fn ready_for_fw(&self) -> bool; /// Initializes the fuse values and locks them in until the next reset. This /// function can only be called during early boot, shortly after the model /// is created with `new_unbooted()`. /// /// # Panics /// /// If the cptra_fuse_wr_done has already been written, or the /// hardware prevents cptra_fuse_wr_done from being set. fn init_fuses(&mut self) { println!("Initializing fuses"); let fuses = self.fuses().clone(); if let Err(e) = caliptra_api::SocManager::init_fuses(self, &fuses) { panic!( "{}", format!("Fuse initializaton error: {}", ModelError::from(e)) ); } } fn step_until_exit_success(&mut self) -> std::io::Result<()> { self.copy_output_until_exit_success(std::io::Sink::default()) } fn copy_output_until_exit_success( &mut self, mut w: impl std::io::Write, ) -> std::io::Result<()> { loop { if !self.output().peek().is_empty() { w.write_all(self.output().take(usize::MAX).as_bytes())?; } match self.output().exit_status() { Some(ExitStatus::Passed) => return Ok(()), Some(ExitStatus::Failed) => { return Err(std::io::Error::new( ErrorKind::Other, "firmware exited with failure", )) } None => {} } self.step(); } } fn step_until_exit_failure(&mut self) -> std::io::Result<()> { loop { match self.output().exit_status() { Some(ExitStatus::Failed) => return Ok(()), Some(ExitStatus::Passed) => { return Err(std::io::Error::new( ErrorKind::Other,
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/fpga_regs.rs
hw-model/src/fpga_regs.rs
// Licensed under the Apache-2.0 license. #![allow(dead_code)] use tock_registers::registers::{ReadOnly, ReadWrite, WriteOnly}; use tock_registers::{register_bitfields, register_structs}; register_bitfields! { u32, pub Control [ CptraPwrgood OFFSET(0) NUMBITS(1) [], CptraSsRstB OFFSET(1) NUMBITS(1) [], CptraObfUdsSeedVld OFFSET(2) NUMBITS(1) [], CptraObfFieldEntropyVld OFFSET(3) NUMBITS(1) [], RsvdDbgLocked OFFSET(4) NUMBITS(1) [], RsvdDeviceLifecycle OFFSET(5) NUMBITS(2) [], BootfsmBrkpoint OFFSET(7) NUMBITS(1) [], ScanMode OFFSET(8) NUMBITS(1) [], SsDebugIntent OFFSET(16) NUMBITS(1) [], I3cAxiUserIdFiltering OFFSET(17) NUMBITS(1) [], OcpLockEn OFFSET(18) NUMBITS(1) [], LcAllowRmaOrScrapOnPpd OFFSET(19) NUMBITS(1) [], FipsZeroizationPpd OFFSET(20) NUMBITS(1) [], AxiReset OFFSET(31) NUMBITS(1) [], ], pub MciError [ MciErrorFatal OFFSET(0) NUMBITS(1) [], MciErrorNonFatal OFFSET(1) NUMBITS(1) [], ], pub McuConfig [ McuNoRomConfig OFFSET(0) NUMBITS(1) [], CptraSsMciBootSeqBrkpointI OFFSET(1) NUMBITS(1) [], CptraSsLcAllowRmaOnPpdI OFFSET(2) NUMBITS(1) [], CptraSsLcCtrlScanRstNiI OFFSET(3) NUMBITS(1) [], CptraSsLcEsclateScrapState0I OFFSET(4) NUMBITS(1) [], CptraSsLcEsclateScrapState1I OFFSET(5) NUMBITS(1) [], ], pub Status [ CptraErrorFatal OFFSET(0) NUMBITS(1) [], CptraErrorNonFatal OFFSET(1) NUMBITS(1) [], ReadyForFuses OFFSET(2) NUMBITS(1) [], ReadyForFwPush OFFSET(3) NUMBITS(1) [], ReadyForRuntime OFFSET(4) NUMBITS(1) [], MailboxDataAvail OFFSET(5) NUMBITS(1) [], MailboxFlowDone OFFSET(6) NUMBITS(1) [], ], pub FifoStatus [ Empty OFFSET(0) NUMBITS(1) [], Full OFFSET(1) NUMBITS(1) [], ], pub ItrngFifoStatus [ Empty OFFSET(0) NUMBITS(1) [], Full OFFSET(1) NUMBITS(1) [], Reset OFFSET(2) NUMBITS(1) [], ], pub FifoData [ NextChar OFFSET(0) NUMBITS(8) [], CharValid OFFSET(8) NUMBITS(1) [], ], } register_structs! { pub FifoRegs { (0x0 => pub log_fifo_data: ReadOnly<u32, FifoData::Register>), (0x4 => pub log_fifo_status: ReadOnly<u32, FifoStatus::Register>), (0x8 => pub itrng_fifo_data: ReadWrite<u32>), (0xc => pub itrng_fifo_status: ReadWrite<u32, ItrngFifoStatus::Register>), (0x10 => pub dbg_fifo_data_pop: ReadOnly<u32, FifoData::Register>), (0x14 => pub dbg_fifo_data_push: WriteOnly<u32, FifoData::Register>), (0x18 => pub dbg_fifo_status: ReadOnly<u32, FifoStatus::Register>), (0x1c => @END), }, pub WrapperRegs { (0x0 => pub fpga_magic: ReadOnly<u32>), (0x4 => pub fpga_version: ReadOnly<u32>), (0x8 => pub control: ReadWrite<u32, Control::Register>), (0xc => pub status: ReadOnly<u32, Status::Register>), (0x10 => pub arm_user: ReadWrite<u32>), (0x14 => pub itrng_divisor: ReadWrite<u32>), (0x18 => pub cycle_count: ReadOnly<u32>), (0x1c => _reserved0), (0x30 => pub generic_input_wires: [ReadWrite<u32>; 2]), (0x38 => pub generic_output_wires: [ReadOnly<u32>; 2]), (0x40 => pub cptra_obf_key: [ReadWrite<u32>; 8]), (0x60 => pub cptra_csr_hmac_key: [ReadWrite<u32>; 16]), (0xa0 => pub cptra_obf_uds_seed: [ReadWrite<u32>; 16]), (0xe0 => pub cptra_obf_field_entropy: [ReadWrite<u32>; 8]), (0x100 => pub lsu_user: ReadWrite<u32>), (0x104 => pub ifu_user: ReadWrite<u32>), (0x108 => pub dma_axi_user: ReadWrite<u32>), (0x10c => pub soc_config_user: ReadWrite<u32>), (0x110 => pub sram_config_user: ReadWrite<u32>), (0x114 => pub mcu_reset_vector: ReadWrite<u32>), (0x118 => pub mci_error: ReadOnly<u32, MciError::Register>), (0x11c => pub mcu_config: ReadWrite<u32, McuConfig::Register>), (0x120 => pub uds_seed_base_addr: ReadWrite<u32>), (0x124 => pub prod_debug_unlock_auth_pk_hash_reg_bank_offset: ReadWrite<u32>), (0x128 => pub num_of_prod_debug_unlock_auth_pk_hashes: ReadWrite<u32>), (0x12c => pub mci_generic_input_wires: [ReadWrite<u32>; 2]), (0x134 => pub mci_generic_output_wires: [ReadOnly<u32>; 2]), (0x13c => pub ss_key_release_base_addr: ReadOnly<u32>), (0x140 => pub ss_key_release_key_size: ReadOnly<u32>), (0x144 => pub ss_external_staging_area_base_addr: ReadOnly<u32>), (0x148 => pub cptra_ss_mcu_ext_int: ReadWrite<u32>), (0x14c => pub cptr_ss_raw_unlock_token_hash: [ReadWrite<u32>; 4]), (0x15c => _reserved1), (0x200 => pub ocp_lock_key_release_reg: [ReadWrite<u32>; 16]), (0x240 => @END), } }
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/model_verilated.rs
hw-model/src/model_verilated.rs
// Licensed under the Apache-2.0 license use crate::bus_logger::{BusLogger, LogFile, NullBus}; use crate::trace_path_or_env; use crate::EtrngResponse; use crate::{HwModel, SocManager, TrngMode}; use caliptra_api_types::Fuses; use caliptra_emu_bus::Bus; use caliptra_emu_bus::BusMmio; use caliptra_emu_bus::Event; use caliptra_emu_types::{RvAddr, RvData, RvSize}; use caliptra_hw_model_types::ErrorInjectionMode; use caliptra_verilated::{AhbTxnType, CaliptraVerilated}; use std::cell::{Cell, RefCell}; use std::ffi::OsStr; use std::io::Write; use std::mpsc; use std::path::{Path, PathBuf}; use std::rc::Rc; use crate::Output; const DEFAULT_AXI_PAUSER: u32 = 0x1; // How many clock cycles before emitting a TRNG nibble const TRNG_DELAY: u32 = 4; pub struct VerilatedApbBus<'a> { model: &'a mut ModelVerilated, } impl<'a> Bus for VerilatedApbBus<'a> { fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, caliptra_emu_bus::BusError> { if addr & 0x3 != 0 { return Err(caliptra_emu_bus::BusError::LoadAddrMisaligned); } let result = Ok(self.model.v.apb_read_u32(self.model.soc_axi_pauser, addr)); self.model .log .borrow_mut() .log_read("SoC", size, addr, result); self.model.process_trng(); result } fn write( &mut self, size: RvSize, addr: RvAddr, val: RvData, ) -> Result<(), caliptra_emu_bus::BusError> { if addr & 0x3 != 0 { return Err(caliptra_emu_bus::BusError::StoreAddrMisaligned); } if size != RvSize::Word { return Err(caliptra_emu_bus::BusError::StoreAccessFault); } self.model .v .apb_write_u32(self.model.soc_axi_pauser, addr, val); self.model .log .borrow_mut() .log_write("SoC", size, addr, val, Ok(())); self.model.process_trng(); Ok(()) } } // Like EtrngResponse, but with an absolute time struct AbsoluteEtrngResponse { time: u64, data: [u32; 12], } pub struct ModelVerilated { pub v: CaliptraVerilated, fuses: Fuses, output: Output, trace_enabled: bool, trace_path: Option<PathBuf>, trng_mode: TrngMode, itrng_nibbles: Box<dyn Iterator<Item = u8>>, itrng_delay_remaining: u32, etrng_responses: Box<dyn Iterator<Item = EtrngResponse>>, etrng_response: Option<AbsoluteEtrngResponse>, etrng_waiting_for_req_to_clear: bool, log: Rc<RefCell<BusLogger<NullBus>>>, soc_axi_pauser: u32, } impl ModelVerilated { pub fn start_tracing(&mut self, path: &str, depth: i32) { self.v.start_tracing(path, depth).unwrap(); } pub fn stop_tracing(&mut self) { self.v.stop_tracing(); } /// Set all mailbox SRAM cells to value with double-bit ECC errors pub fn corrupt_mailbox_ecc_double_bit(&mut self) { self.v.corrupt_mailbox_ecc_double_bit(); } } fn ahb_txn_size(ty: AhbTxnType) -> RvSize { match ty { AhbTxnType::ReadU8 | AhbTxnType::WriteU8 => RvSize::Byte, AhbTxnType::ReadU16 | AhbTxnType::WriteU16 => RvSize::HalfWord, AhbTxnType::ReadU32 | AhbTxnType::WriteU32 => RvSize::Word, AhbTxnType::ReadU64 | AhbTxnType::WriteU64 => RvSize::Word, } } impl SocManager for ModelVerilated { type TMmio<'a> = BusMmio<VerilatedApbBus<'a>>; fn mmio_mut(&mut self) -> Self::TMmio<'_> { BusMmio::new(self.apb_bus()) } fn delay(&mut self) { self.step(); } 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 ModelVerilated { type TBus<'a> = VerilatedApbBus<'a>; fn new_unbooted(params: crate::InitParams) -> Result<Self, Box<dyn std::error::Error>> where Self: Sized, { let output = Output::new(params.log_writer); let output_sink = output.sink().clone(); let generic_output_wires_changed_cb = { let prev_uout = Cell::new(None); Box::new(move |v: &CaliptraVerilated, out_wires| { if Some(out_wires & 0x1ff) != prev_uout.get() { // bit #8 toggles whenever the Uart driver writes a byte, so // by including it in the comparison we can tell when the // same character has been written a second time if prev_uout.get().is_some() { // Don't print out a character for the initial state output_sink.set_now(v.total_cycles()); output_sink.push_uart_char((out_wires & 0xff) as u8); } prev_uout.set(Some(out_wires & 0x1ff)); } }) }; let log = Rc::new(RefCell::new(BusLogger::new(NullBus()))); let bus_log = log.clone(); let ahb_cb = Box::new( move |_v: &CaliptraVerilated, ty: AhbTxnType, addr: u32, data: u64| { if ty.is_write() { bus_log.borrow_mut().log_write( "UC", ahb_txn_size(ty), addr, data as u32, Ok(()), ); if ty == AhbTxnType::WriteU64 { bus_log.borrow_mut().log_write( "UC", ahb_txn_size(ty), addr + 4, (data >> 32) as u32, Ok(()), ); } } else { bus_log .borrow_mut() .log_read("UC", ahb_txn_size(ty), addr, Ok(data as u32)); if ty == AhbTxnType::WriteU64 { bus_log.borrow_mut().log_read( "UC", ahb_txn_size(ty), addr + 4, Ok((data >> 32) as u32), ); } } }, ); let compiled_trng_mode = if cfg!(feature = "itrng") { TrngMode::Internal } else { TrngMode::External }; let desired_trng_mode = TrngMode::resolve(params.trng_mode); if desired_trng_mode != compiled_trng_mode { let msg_suffix = match desired_trng_mode { TrngMode::Internal => "try compiling with --features itrng", TrngMode::External => "try compiling without --features itrng", }; return Err(format!( "HwModel InitParams asked for trng_mode={desired_trng_mode:?}, \ but verilog was compiled with trng_mode={compiled_trng_mode:?}; {msg_suffix}" ) .into()); } let mut v = CaliptraVerilated::with_callbacks( caliptra_verilated::InitArgs { security_state: u32::from(params.security_state), cptra_obf_key: params.cptra_obf_key, }, generic_output_wires_changed_cb, ahb_cb, ); v.write_rom_image(params.rom); let mut m = ModelVerilated { v, fuses: params.fuses, output, trace_enabled: false, trace_path: trace_path_or_env(params.trace_path), trng_mode: desired_trng_mode, itrng_nibbles: params.itrng_nibbles, itrng_delay_remaining: TRNG_DELAY, etrng_responses: params.etrng_responses, etrng_response: None, etrng_waiting_for_req_to_clear: false, log, soc_axi_pauser: DEFAULT_AXI_PAUSER, }; m.tracing_hint(true); if params.random_sram_puf { m.v.init_random_puf_state(&mut rand::thread_rng()); } m.v.input.cptra_pwrgood = true; m.v.next_cycle_high(1); m.v.input.cptra_rst_b = true; m.v.next_cycle_high(1); while !m.v.output.ready_for_fuses { m.v.next_cycle_high(1); } writeln!(m.output().logger(), "ready_for_fuses is high")?; Ok(m) } fn type_name(&self) -> &'static str { "ModelVerilated" } fn trng_mode(&self) -> TrngMode { self.trng_mode } fn apb_bus(&mut self) -> Self::TBus<'_> { VerilatedApbBus { model: self } } fn step(&mut self) { self.process_trng_start(); self.v.next_cycle_high(1); self.process_trng_end(); } fn output(&mut self) -> &mut crate::Output { self.output.sink().set_now(self.v.total_cycles()); &mut self.output } fn warm_reset(&mut self) { // Toggle reset pin self.v.input.cptra_rst_b = false; self.v.next_cycle_high(1); self.v.input.cptra_rst_b = true; self.v.next_cycle_high(1); // Wait for ready_for_fuses while !self.v.output.ready_for_fuses { self.v.next_cycle_high(1); } } fn cold_reset(&mut self) { // Toggle reset pin self.v.input.cptra_rst_b = false; self.v.next_cycle_high(1); // Toggle pwrgood pin self.v.input.cptra_pwrgood = false; self.v.next_cycle_high(1); self.v.input.cptra_pwrgood = true; self.v.next_cycle_high(1); self.v.input.cptra_rst_b = true; self.v.next_cycle_high(1); // Wait for ready_for_fuses while !self.v.output.ready_for_fuses { self.v.next_cycle_high(1); } } fn ready_for_mb_processing(&self) -> bool { self.v.output.ready_for_mb_processing_push } fn tracing_hint(&mut self, enable: bool) { if self.trace_enabled != enable { self.trace_enabled = enable; if enable { if let Some(trace_path) = &self.trace_path { if trace_path.extension() == Some(OsStr::new("vcd")) { self.v.start_tracing(trace_path.to_str().unwrap(), 99).ok(); } else { self.log.borrow_mut().log = match LogFile::open(Path::new(&trace_path)) { Ok(file) => Some(file), Err(e) => { eprintln!("Unable to open file {trace_path:?}: {e}"); return; } }; } } } else { if self.log.borrow_mut().log.take().is_none() { self.v.stop_tracing(); } } } } fn ecc_error_injection(&mut self, mode: ErrorInjectionMode) { match mode { ErrorInjectionMode::None => { self.v.input.sram_error_injection_mode = 0x0; } ErrorInjectionMode::IccmDoubleBitEcc => { self.v.input.sram_error_injection_mode = 0x2; } ErrorInjectionMode::DccmDoubleBitEcc => { self.v.input.sram_error_injection_mode = 0x8; } } } fn set_axi_user(&mut self, pauser: u32) { self.soc_axi_pauser = pauser; } } impl ModelVerilated { fn process_trng(&mut self) { if self.process_trng_start() { self.v.next_cycle_high(1); self.process_trng_end(); } } fn process_trng_start(&mut self) -> bool { match self.trng_mode { TrngMode::Internal => self.process_itrng_start(), TrngMode::External => self.process_etrng_start(), } } fn process_trng_end(&mut self) { match self.trng_mode { TrngMode::Internal => self.process_itrng_end(), TrngMode::External => {} } } // Returns true if process_trng_end must be called after a clock cycle fn process_etrng_start(&mut self) -> bool { if self.etrng_waiting_for_req_to_clear && !self.v.output.etrng_req { self.etrng_waiting_for_req_to_clear = false; } if self.v.output.etrng_req && !self.etrng_waiting_for_req_to_clear { if self.etrng_response.is_none() { if let Some(response) = self.etrng_responses.next() { self.etrng_response = Some(AbsoluteEtrngResponse { time: self.v.total_cycles() + u64::from(response.delay), data: response.data, }); } } if let Some(etrng_response) = &mut self.etrng_response { if self.v.total_cycles().wrapping_sub(etrng_response.time) < 0x8000_0000_0000_0000 { self.etrng_waiting_for_req_to_clear = true; let etrng_response = self.etrng_response.take().unwrap(); self.soc_ifc_trng() .cptra_trng_data() .write(&etrng_response.data); self.soc_ifc_trng() .cptra_trng_status() .write(|w| w.data_wr_done(true)); } } } false } // Returns true if process_trng_end must be called after a clock cycle fn process_itrng_start(&mut self) -> bool { if self.v.output.etrng_req { if self.itrng_delay_remaining == 0 { if let Some(val) = self.itrng_nibbles.next() { self.v.input.itrng_valid = true; self.v.input.itrng_data = val & 0xf; } self.itrng_delay_remaining = TRNG_DELAY; } else { self.itrng_delay_remaining -= 1; } self.v.input.itrng_valid } else { false } } fn process_itrng_end(&mut self) { if self.v.input.itrng_valid { self.v.input.itrng_valid = false; } } fn put_firmware_in_rri(&mut self, firmware: &[u8]) -> Result<(), ModelError> { todo!() } fn events_from_caliptra(&mut self) -> Vec<Event> { todo!() } fn events_to_caliptra(&mut self) -> mpsc::Sender<Event> { todo!() } fn write_payload_to_ss_staging_area(&mut self, payload: &[u8]) -> Result<u64, ModelError> { todo!() } 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/rv32_builder.rs
hw-model/src/rv32_builder.rs
// Licensed under the Apache-2.0 license /// The world's most primitive RISC-V assembler #[derive(Default)] pub struct Rv32Builder(Vec<u8>); impl Rv32Builder { pub fn new() -> Self { Default::default() } /// Emit machine code to store val at address addr. pub fn store(mut self, addr: u32, val: u32) -> Self { self.lui(addr, 5); self.lui(val, 6); self.addi(val, 6, 6); self.sw(addr, 6, 5); self } /// Enter an infinite loop that does nothing. pub fn empty_loop(mut self) -> Self { self.instr32(0b1101111); self } /// Return the generated machine code. pub fn build(mut self) -> Vec<u8> { self.nop(); self.0 } fn lui(&mut self, imm: u32, rd: u32) { self.instr32((imm & !0xfff) | (rd << 7) | 0b0110111); } fn addi(&mut self, imm: u32, rs1: u32, rd: u32) { self.instr_j(imm, rs1, 0b000, rd, 0b010011); } fn sw(&mut self, imm: u32, src: u32, base: u32) { self.instr_s(imm, src, base, 0b010, 0b0100011); } fn nop(&mut self) { self.addi(0, 0, 0); } fn instr_j(&mut self, imm: u32, rs1: u32, op3: u32, rd: u32, op7: u32) { self.instr32( ((imm & 0xfff) << 20) | ((rs1 & 0x1f) << 15) | ((op3 & 0x7) << 12) | ((rd & 0x1f) << 7) | (op7 & 0x7f), ); } fn instr_s(&mut self, imm: u32, rs2: u32, rs1: u32, op3: u32, op7: u32) { self.instr32( ((imm & 0xfe0) << 20) | ((rs2 & 0x1f) << 20) | ((rs1 & 0x1f) << 15) | ((op3 & 0x7) << 12) | ((imm & 0x1f) << 7) | (op7 & 0x7f), ); } fn instr32(&mut self, instr: u32) { self.0.extend_from_slice(&instr.to_le_bytes()); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_rv32gen_mmio() { let code = Rv32Builder::new() .store(0x5678_1234, 0xa03d_2931) .empty_loop() .build(); assert_eq!( &code, &[ 0xb7, 0x12, 0x78, 0x56, 0x37, 0x23, 0x3d, 0xa0, 0x13, 0x3, 0x13, 0x93, 0x23, 0xaa, 0x62, 0x22, 0x6f, 0x0, 0x0, 0x0, 0x13, 0x0, 0x0, 0x0, ] ); } }
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/model_fpga_realtime.rs
hw-model/src/model_fpga_realtime.rs
// Licensed under the Apache-2.0 license use std::io::{BufRead, BufReader, Write}; use std::marker::PhantomData; use std::process::{Child, Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; use std::sync::Arc; use std::thread; use std::{env, slice, str::FromStr}; use bitfield::bitfield; use caliptra_emu_bus::{Bus, BusError, BusMmio, Event}; use caliptra_emu_types::{RvAddr, RvData, RvSize}; use libc; use nix; use std::time::{Duration, Instant}; use uio::{UioDevice, UioError}; use crate::EtrngResponse; use crate::Fuses; use crate::ModelError; use crate::Output; use crate::{HwModel, SecurityState, SocManager, TrngMode}; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum OpenOcdError { Closed, CaliptraNotAccessible, VeerNotAccessible, WrongVersion, } // UIO mapping indices const FPGA_WRAPPER_MAPPING: usize = 0; const CALIPTRA_MAPPING: usize = 1; const ROM_MAPPING: usize = 2; // Set to core_clk cycles per ITRNG sample. const ITRNG_DIVISOR: u32 = 400; const DEFAULT_AXI_PAUSER: u32 = 0x1; pub(crate) fn fmt_uio_error(err: UioError) -> String { format!("{err:?}") } // ITRNG FIFO stores 1024 DW and outputs 4 bits at a time to Caliptra. const FPGA_ITRNG_FIFO_SIZE: usize = 1024; // FPGA wrapper register offsets const FPGA_WRAPPER_MAGIC_OFFSET: isize = 0x0000 / 4; const FPGA_WRAPPER_VERSION_OFFSET: isize = 0x0004 / 4; const FPGA_WRAPPER_CONTROL_OFFSET: isize = 0x0008 / 4; const FPGA_WRAPPER_STATUS_OFFSET: isize = 0x000C / 4; const FPGA_WRAPPER_PAUSER_OFFSET: isize = 0x0010 / 4; const FPGA_WRAPPER_ITRNG_DIV_OFFSET: isize = 0x0014 / 4; const FPGA_WRAPPER_CYCLE_COUNT_OFFSET: isize = 0x0018 / 4; const FPGA_WRAPPER_GENERIC_INPUT_OFFSET: isize = 0x0030 / 4; const _FPGA_WRAPPER_GENERIC_OUTPUT_OFFSET: isize = 0x0038 / 4; // Secrets const FPGA_WRAPPER_DEOBF_KEY_OFFSET: isize = 0x0040 / 4; const FPGA_WRAPPER_CSR_HMAC_KEY_OFFSET: isize = 0x0060 / 4; const FPGA_WRAPPER_OBF_UDS_SEED_OFFSET: isize = 0x00A0 / 4; const FPGA_WRAPPER_OBF_FIELD_ENTROPY_OFFSET: isize = 0x00E0 / 4; // FIFOs const FPGA_WRAPPER_LOG_FIFO_DATA_OFFSET: isize = 0x1000 / 4; const FPGA_WRAPPER_LOG_FIFO_STATUS_OFFSET: isize = 0x1004 / 4; const FPGA_WRAPPER_ITRNG_FIFO_DATA_OFFSET: isize = 0x1008 / 4; const FPGA_WRAPPER_ITRNG_FIFO_STATUS_OFFSET: isize = 0x100C / 4; bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] /// Wrapper wires -> Caliptra pub struct WrapperControl(u32); cptra_pwrgood, set_cptra_pwrgood: 0, 0; cptra_rst_b, set_cptra_rst_b: 1, 1; cptra_obf_uds_seed_vld, set_cptra_obf_uds_seed_vld: 2, 2; cptra_obf_field_entropy_vld, set_cptra_obf_field_entropy_vld: 3, 3; debug_locked, set_debug_locked: 4, 4; device_lifecycle, set_device_lifecycle: 6, 5; bootfsm_brkpoint, set_bootfsm_brkpoint: 7, 7; scan_mode, set_scan_mode: 8, 8; rsvd_ss_debug_intent, set_rsvd_ss_debug_intent: 16, 16; rsvd_i3c_axi_user_id_filtering, set_rsvd_i3c_axi_user_id_filtering: 17, 17; rsvd_ocp_lock_en, set_rsvd_ocp_lock_en: 18, 18; rsvd_lc_allow_rma_or_scrap_on_ppd, set_rsvd_lc_allow_rma_or_scrap_on_ppd: 19, 19; rsvd_fips_zeroization_ppd, set_rsvd_fips_zeroization_ppd: 20, 20; axi_reset, set_axi_reset: 31, 31; } bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] /// Wrapper wires <- Caliptra pub struct WrapperStatus(u32); cptra_error_fatal, _: 0, 0; cptra_error_non_fatal, _: 1, 1; ready_for_fuses, _: 2, 2; ready_for_fw, _: 3, 3; ready_for_runtime, _: 4, 4; } bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] /// Log FIFO data pub struct FifoData(u32); log_fifo_char, _: 7, 0; log_fifo_valid, _: 8, 8; } bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] /// Log FIFO status pub struct FifoStatus(u32); log_fifo_empty, _: 0, 0; log_fifo_full, _: 1, 1; } bitfield! { #[derive(Debug, PartialEq, Eq, Clone, Copy)] /// ITRNG FIFO status pub struct TrngFifoStatus(u32); trng_fifo_empty, _: 0, 0; trng_fifo_full, _: 1, 1; trng_fifo_reset, set_trng_fifo_reset: 2, 2; } pub struct ModelFpgaRealtime { dev: UioDevice, wrapper: *mut u32, mmio: *mut u32, output: Output, fuses: Fuses, realtime_thread: Option<thread::JoinHandle<()>>, realtime_thread_exit_flag: Arc<AtomicBool>, trng_mode: TrngMode, openocd: Option<Child>, } impl ModelFpgaRealtime { fn realtime_thread_itrng_fn( wrapper: *mut u32, exit: Arc<AtomicBool>, mut itrng_nibbles: Box<dyn Iterator<Item = u8> + Send>, ) { // Reset ITRNG FIFO to clear out old data unsafe { let mut trngfifosts = TrngFifoStatus(0); trngfifosts.set_trng_fifo_reset(1); wrapper .offset(FPGA_WRAPPER_ITRNG_FIFO_STATUS_OFFSET) .write_volatile(trngfifosts.0); trngfifosts.set_trng_fifo_reset(0); wrapper .offset(FPGA_WRAPPER_ITRNG_FIFO_STATUS_OFFSET) .write_volatile(trngfifosts.0); }; // Small delay to allow reset to complete thread::sleep(Duration::from_millis(1)); while !exit.load(Ordering::Relaxed) { // Once TRNG data is requested the FIFO will continously empty. Load at max one FIFO load at a time. // FPGA ITRNG FIFO is 1024 DW deep. for _i in 0..FPGA_ITRNG_FIFO_SIZE { let trngfifosts = unsafe { TrngFifoStatus( wrapper .offset(FPGA_WRAPPER_ITRNG_FIFO_STATUS_OFFSET) .read_volatile(), ) }; if trngfifosts.trng_fifo_full() == 0 { let mut itrng_dw = 0; for i in 0..8 { match itrng_nibbles.next() { Some(nibble) => itrng_dw += u32::from(nibble) << (4 * i), None => return, } } unsafe { wrapper .offset(FPGA_WRAPPER_ITRNG_FIFO_DATA_OFFSET) .write_volatile(itrng_dw); } } else { break; } } // 1 second * (20 MHz / (2^13 throttling counter)) / 8 nibbles per DW: 305 DW of data consumed in 1 second. let end_time = Instant::now() + Duration::from_millis(1000); while !exit.load(Ordering::Relaxed) && Instant::now() < end_time { thread::sleep(Duration::from_millis(1)); } } } fn realtime_thread_etrng_fn( mmio: *mut u32, exit: Arc<AtomicBool>, mut etrng_responses: Box<dyn Iterator<Item = EtrngResponse>>, ) { let soc_ifc_trng = unsafe { caliptra_registers::soc_ifc_trng::RegisterBlock::new_with_mmio( 0x3003_0000 as *mut u32, BusMmio::new(FpgaRealtimeBus { mmio, phantom: Default::default(), }), ) }; while !exit.load(Ordering::Relaxed) { let trng_status = soc_ifc_trng.cptra_trng_status().read(); if trng_status.data_req() { if let Some(resp) = etrng_responses.next() { soc_ifc_trng.cptra_trng_data().write(&resp.data); soc_ifc_trng .cptra_trng_status() .write(|w| w.data_wr_done(true)); } } thread::sleep(Duration::from_millis(1)); } } fn axi_reset(&mut self) { unsafe { let mut val = WrapperControl( self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .read_volatile(), ); val.set_axi_reset(1); // wait a few clock cycles or we can crash the FPGA std::thread::sleep(std::time::Duration::from_micros(1)); } } fn is_ready_for_fuses(&self) -> bool { unsafe { WrapperStatus( self.wrapper .offset(FPGA_WRAPPER_STATUS_OFFSET) .read_volatile(), ) .ready_for_fuses() != 0 } } fn set_cptra_pwrgood(&mut self, value: bool) { unsafe { let mut val = WrapperControl( self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .read_volatile(), ); val.set_cptra_pwrgood(value as u32); self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .write_volatile(val.0); } } fn set_cptra_rst_b(&mut self, value: bool) { unsafe { let mut val = WrapperControl( self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .read_volatile(), ); val.set_cptra_rst_b(value as u32); self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .write_volatile(val.0); } } fn set_security_state(&mut self, value: SecurityState) { unsafe { let mut val = WrapperControl( self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .read_volatile(), ); val.set_debug_locked(u32::from(value.debug_locked())); val.set_device_lifecycle(u32::from(value.device_lifecycle())); self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .write_volatile(val.0); } } fn set_secrets_valid(&mut self, value: bool) { unsafe { let mut val = WrapperControl( self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .read_volatile(), ); val.set_cptra_obf_uds_seed_vld(value as u32); val.set_cptra_obf_field_entropy_vld(value as u32); self.wrapper .offset(FPGA_WRAPPER_CONTROL_OFFSET) .write_volatile(val.0); } } fn set_generic_input_wires(&mut self, value: &[u32; 2]) { unsafe { for i in 0..2 { self.wrapper .offset(FPGA_WRAPPER_GENERIC_INPUT_OFFSET + i) .write_volatile(value[i as usize]); } } } fn clear_log_fifo(&mut self) { loop { let fifodata = unsafe { FifoData( self.wrapper .offset(FPGA_WRAPPER_LOG_FIFO_DATA_OFFSET) .read_volatile(), ) }; if fifodata.log_fifo_valid() == 0 { break; } } } fn handle_log(&mut self) { // Check if the FIFO is full (which probably means there was an overrun) let fifosts = unsafe { FifoStatus( self.wrapper .offset(FPGA_WRAPPER_LOG_FIFO_STATUS_OFFSET) .read_volatile(), ) }; if fifosts.log_fifo_full() != 0 { panic!("FPGA log FIFO overran"); } // Check and empty log FIFO loop { let fifodata = unsafe { FifoData( self.wrapper .offset(FPGA_WRAPPER_LOG_FIFO_DATA_OFFSET) .read_volatile(), ) }; // Add byte to log if it is valid if fifodata.log_fifo_valid() != 0 { self.output() .sink() .push_uart_char(fifodata.log_fifo_char().try_into().unwrap()); } else { break; } } } // UIO crate doesn't provide a way to unmap memory. fn unmap_mapping(&self, addr: *mut u32, mapping: usize) { let map_size = self.dev.map_size(mapping).unwrap(); unsafe { nix::sys::mman::munmap(addr as *mut libc::c_void, map_size.into()).unwrap(); } } fn set_itrng_divider(&mut self, divider: u32) { unsafe { self.wrapper .offset(FPGA_WRAPPER_ITRNG_DIV_OFFSET) .write_volatile(divider - 1); } } } // Hack to pass *mut u32 between threads struct SendPtr(*mut u32); unsafe impl Send for SendPtr {} impl SocManager for ModelFpgaRealtime { 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; type TMmio<'a> = BusMmio<FpgaRealtimeBus<'a>>; fn mmio_mut(&mut self) -> Self::TMmio<'_> { BusMmio::new(self.apb_bus()) } fn delay(&mut self) { self.step(); } } impl HwModel for ModelFpgaRealtime { type TBus<'a> = FpgaRealtimeBus<'a>; fn apb_bus(&mut self) -> Self::TBus<'_> { FpgaRealtimeBus { mmio: self.mmio, phantom: Default::default(), } } fn step(&mut self) { // The FPGA can't be stopped. // Never stop never stopping. self.handle_log(); } fn step_until_boot_status( &mut self, expected_status_u32: u32, ignore_intermediate_status: bool, ) { // We need to check the cycle count from the FPGA, and do so quickly // as possible since the ARM host core is slow. // do an immediate check let initial_boot_status_u32: u32 = self.soc_ifc().cptra_boot_status().read(); if initial_boot_status_u32 == expected_status_u32 { return; } // Since the boot takes about 30M cycles, we know something is wrong if // we're stuck at the same state for that duration. const MAX_WAIT_CYCLES: u32 = 30_000_000; // only check the log every 4096 cycles for performance reasons const LOG_CYCLES: usize = 0x1000; let start_cycle_count = self.cycle_count(); for i in 0..usize::MAX { let actual_status_u32 = self.soc_ifc().cptra_boot_status().read(); if expected_status_u32 == actual_status_u32 { break; } if !ignore_intermediate_status && actual_status_u32 != initial_boot_status_u32 { let cycle_count = self.cycle_count().wrapping_sub(start_cycle_count); panic!( "{cycle_count} Expected the next boot_status to be \ ({expected_status_u32}), but status changed from \ {initial_boot_status_u32} to {actual_status_u32})" ); } // only handle the log sometimes so that we don't miss a state transition if i & (LOG_CYCLES - 1) == 0 { self.handle_log(); } let cycle_count = self.cycle_count().wrapping_sub(start_cycle_count); if cycle_count >= MAX_WAIT_CYCLES { panic!( "Expected boot_status to be \ ({expected_status_u32}), but was stuck at ({actual_status_u32})" ); } } } fn new_unbooted(params: crate::InitParams) -> Result<Self, Box<dyn std::error::Error>> where Self: Sized, { let output = Output::new(params.log_writer); let uio_num = usize::from_str( &env::var("CPTRA_UIO_NUM").expect("Set CPTRA_UIO_NUM when using the FPGA"), )?; // This locks the device, and so acts as a test mutex so that only one test can run at a time. let dev = UioDevice::blocking_new(uio_num) .expect("UIO driver not found. Run \"sudo ./hw/fpga/setup_fpga.sh\""); let wrapper = dev .map_mapping(FPGA_WRAPPER_MAPPING) .map_err(fmt_uio_error)? as *mut u32; let mmio = dev.map_mapping(CALIPTRA_MAPPING).map_err(fmt_uio_error)? as *mut u32; let rom = dev.map_mapping(ROM_MAPPING).map_err(fmt_uio_error)? as *mut u8; let rom_size = dev.map_size(ROM_MAPPING).map_err(fmt_uio_error)?; let realtime_thread_exit_flag = Arc::new(AtomicBool::new(false)); let realtime_thread_exit_flag2 = realtime_thread_exit_flag.clone(); let desired_trng_mode = TrngMode::resolve(params.trng_mode); let realtime_thread = match desired_trng_mode { TrngMode::Internal => { let realtime_thread_wrapper = SendPtr(wrapper); Some(thread::spawn(move || { let wrapper = realtime_thread_wrapper; Self::realtime_thread_itrng_fn( wrapper.0, realtime_thread_exit_flag2, params.itrng_nibbles, ) })) } TrngMode::External => { let realtime_thread_mmio = SendPtr(mmio); Some(thread::spawn(move || { let mmio = realtime_thread_mmio; Self::realtime_thread_etrng_fn( mmio.0, realtime_thread_exit_flag2, params.etrng_responses, ) })) } }; let uds_seed = params.fuses.uds_seed; let field_entropy = params.fuses.field_entropy; let mut m = Self { dev, wrapper, mmio, output, fuses: params.fuses, realtime_thread, realtime_thread_exit_flag, trng_mode: desired_trng_mode, openocd: None, }; // Check if the FPGA image is valid if 0x52545043 == unsafe { wrapper.offset(FPGA_WRAPPER_MAGIC_OFFSET).read_volatile() } { let fpga_version = unsafe { m.wrapper .offset(FPGA_WRAPPER_VERSION_OFFSET) .read_volatile() }; writeln!(m.output().logger(), "FPGA built from {fpga_version:x}")?; } else { panic!("FPGA image invalid"); } // Set pwrgood and rst_b to 0 to boot from scratch m.set_cptra_pwrgood(false); m.set_cptra_rst_b(false); writeln!(m.output().logger(), "new_unbooted")?; println!("AXI reset"); m.axi_reset(); // Set generic input wires. let input_wires = [(!params.uds_fuse_row_granularity_64 as u32) << 31, 0]; m.set_generic_input_wires(&input_wires); // Set Security State signal wires m.set_security_state(params.security_state); // Set initial PAUSER m.set_axi_user(DEFAULT_AXI_PAUSER); // Set divisor for ITRNG throttling m.set_itrng_divider(ITRNG_DIVISOR); // Set deobfuscation key for i in 0..8 { unsafe { m.wrapper .offset(FPGA_WRAPPER_DEOBF_KEY_OFFSET + i) .write_volatile(params.cptra_obf_key[i as usize]) }; } // Set the CSR HMAC key for i in 0..16 { unsafe { m.wrapper .offset(FPGA_WRAPPER_CSR_HMAC_KEY_OFFSET + i) .write_volatile(params.csr_hmac_key[i as usize]) }; } // Set the UDS Seed for i in 0..16 { unsafe { m.wrapper .offset(FPGA_WRAPPER_OBF_UDS_SEED_OFFSET + i) .write_volatile(uds_seed[i as usize]) }; } // Set the FE Seed for i in 0..8 { unsafe { m.wrapper .offset(FPGA_WRAPPER_OBF_FIELD_ENTROPY_OFFSET + i) .write_volatile(field_entropy[i as usize]) }; } // Currently not using strap UDS and FE m.set_secrets_valid(false); // Write ROM image over backdoor writeln!(m.output().logger(), "Writing ROM")?; let mut rom_data = vec![0; rom_size]; rom_data[..params.rom.len()].clone_from_slice(params.rom); let rom_slice = unsafe { slice::from_raw_parts_mut(rom, rom_size) }; rom_slice.copy_from_slice(&rom_data); // Sometimes there's garbage in here; clean it out m.clear_log_fifo(); // Bring Caliptra out of reset and wait for ready_for_fuses m.set_cptra_pwrgood(true); m.set_cptra_rst_b(true); while !m.is_ready_for_fuses() {} writeln!(m.output().logger(), "ready_for_fuses is high")?; // Checking the FPGA model needs to happen after Caliptra's registers are available. let fpga_trng_mode = if m.soc_ifc().cptra_hw_config().read().i_trng_en() { TrngMode::Internal } else { TrngMode::External }; if desired_trng_mode != fpga_trng_mode { return Err(format!( "HwModel InitParams asked for trng_mode={desired_trng_mode:?}, \ but the FPGA was compiled with trng_mode={fpga_trng_mode:?}; \ try matching the test and the FPGA image." ) .into()); } Ok(m) } fn type_name(&self) -> &'static str { "ModelFpgaRealtime" } fn trng_mode(&self) -> TrngMode { self.trng_mode } fn output(&mut self) -> &mut crate::Output { let cycle = self.cycle_count(); self.output.sink().set_now(u64::from(cycle)); &mut self.output } fn warm_reset(&mut self) { // Toggle reset pin self.set_cptra_rst_b(false); self.set_cptra_rst_b(true); // Wait for ready_for_fuses while !self.is_ready_for_fuses() {} } fn cold_reset(&mut self) { // Toggle reset and pwrgood self.set_cptra_rst_b(false); self.set_cptra_pwrgood(false); self.set_cptra_pwrgood(true); self.set_cptra_rst_b(true); // Wait for ready_for_fuses while !self.is_ready_for_fuses() {} } fn ready_for_fw(&self) -> bool { unsafe { WrapperStatus( self.wrapper .offset(FPGA_WRAPPER_STATUS_OFFSET) .read_volatile(), ) .ready_for_fw() != 0 } } fn tracing_hint(&mut self, _enable: bool) { // Do nothing; we don't support tracing yet } fn set_axi_user(&mut self, pauser: u32) { unsafe { self.wrapper .offset(FPGA_WRAPPER_PAUSER_OFFSET) .write_volatile(pauser); } } fn put_firmware_in_rri( &mut self, _firmware: &[u8], _soc_manifest: Option<&[u8]>, _mcu_firmware: Option<&[u8]>, ) -> Result<(), ModelError> { todo!() } fn events_from_caliptra(&mut self) -> Vec<Event> { todo!() } fn events_to_caliptra(&mut self) -> mpsc::Sender<Event> { todo!() } fn write_payload_to_ss_staging_area(&mut self, _payload: &[u8]) -> Result<u64, ModelError> { Err(ModelError::SubsystemSramError) } fn fuses(&self) -> &Fuses { &self.fuses } fn set_fuses(&mut self, fuses: Fuses) { self.fuses = fuses; } } impl ModelFpgaRealtime { fn cycle_count(&self) -> u32 { unsafe { self.wrapper .offset(FPGA_WRAPPER_CYCLE_COUNT_OFFSET) .read_volatile() } } pub fn launch_openocd(&mut self) -> Result<(), OpenOcdError> { let _ = Command::new("sudo") .arg("pkill") .arg("openocd") .spawn() .unwrap() .wait(); let mut openocd = Command::new("sudo") .stdout(Stdio::piped()) .stderr(Stdio::piped()) .arg("openocd") .arg("--command") .arg(include_str!("../../hw/fpga/openocd_caliptra.txt")) .spawn() .unwrap(); let mut child_err = BufReader::new(openocd.stderr.as_mut().unwrap()); let mut output = String::new(); loop { if 0 == child_err.read_line(&mut output).unwrap() { println!("openocd log returned EOF. Log: {output}"); return Err(OpenOcdError::Closed); } if output.contains("OpenOCD setup finished") { break; } } if !output.contains("Open On-Chip Debugger 0.12.0") { return Err(OpenOcdError::WrongVersion); } if output.contains("Caliptra not accessible") { return Err(OpenOcdError::CaliptraNotAccessible); } if output.contains("Core not accessible") { return Err(OpenOcdError::VeerNotAccessible); } self.openocd = Some(openocd); Ok(()) } } impl Drop for ModelFpgaRealtime { fn drop(&mut self) { // Ask the realtime thread to exit and wait for it to finish // SAFETY: The thread is using the UIO mappings below, so it must be // dead before we unmap. // TODO: Find a safer abstraction for UIO mappings. self.realtime_thread_exit_flag .store(true, Ordering::Relaxed); self.realtime_thread.take().unwrap().join().unwrap(); // reset the AXI bus as we leave self.axi_reset(); // Unmap UIO memory space so that the file lock is released self.unmap_mapping(self.wrapper, FPGA_WRAPPER_MAPPING); self.unmap_mapping(self.mmio, CALIPTRA_MAPPING); self.unmap_mapping(self.mmio, ROM_MAPPING); // Close openocd match &mut self.openocd { Some(ref mut cmd) => cmd.kill().expect("Failed to close openocd"), _ => (), } } } pub struct FpgaRealtimeBus<'a> { mmio: *mut u32, phantom: PhantomData<&'a mut ()>, } impl<'a> FpgaRealtimeBus<'a> { fn ptr_for_addr(&mut self, addr: RvAddr) -> Option<*mut u32> { let addr = addr as usize; unsafe { match addr { 0x3002_0000..=0x3003_ffff => Some(self.mmio.add((addr - 0x3000_0000) / 4)), _ => None, } } } } impl<'a> Bus for FpgaRealtimeBus<'a> { fn read(&mut self, _size: RvSize, addr: RvAddr) -> Result<RvData, BusError> { if let Some(ptr) = self.ptr_for_addr(addr) { Ok(unsafe { ptr.read_volatile() }) } else { println!("Error LoadAccessFault"); Err(BusError::LoadAccessFault) } } fn write( &mut self, _size: RvSize, addr: RvAddr, val: RvData, ) -> Result<(), caliptra_emu_bus::BusError> { if let Some(ptr) = self.ptr_for_addr(addr) { // TODO: support 16-bit and 8-bit writes unsafe { ptr.write_volatile(val) }; Ok(()) } else { Err(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/hw-model/src/model_fpga_subsystem.rs
hw-model/src/model_fpga_subsystem.rs
// Licensed under the Apache-2.0 license #![allow(clippy::mut_from_ref)] #![allow(dead_code)] use crate::api_types::{DeviceLifecycle, Fuses}; use crate::bmc::Bmc; use crate::fpga_regs::{Control, FifoData, FifoRegs, FifoStatus, ItrngFifoStatus, WrapperRegs}; use crate::keys::{DEFAULT_LIFECYCLE_RAW_TOKENS, DEFAULT_MANUF_DEBUG_UNLOCK_RAW_TOKEN}; use crate::mcu_boot_status::McuBootMilestones; use crate::openocd::openocd_jtag_tap::{JtagParams, JtagTap, OpenOcdJtagTap}; use crate::otp_provision::{ lc_generate_memory, otp_generate_lifecycle_tokens_mem, otp_generate_manuf_debug_unlock_token_mem, otp_generate_sw_manuf_partition_mem, LifecycleControllerState, OtpSwManufPartition, }; use crate::xi3c::XI3cError; use crate::{ xi3c, BootParams, Error, HwModel, InitParams, ModelCallback, ModelError, Output, TrngMode, }; use crate::{OcpLockState, SecurityState}; use anyhow::Result; use caliptra_api::SocManager; use caliptra_emu_bus::{Bus, BusError, BusMmio, Device, Event, EventData, RecoveryCommandCode}; use caliptra_emu_types::{RvAddr, RvData, RvSize}; use caliptra_hw_model_types::HexSlice; use caliptra_image_types::FwVerificationPqcKeyType; use sensitive_mmio::{SensitiveMmio, SensitiveMmioArgs}; use std::marker::PhantomData; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; use uio::{UioDevice, UioError}; use zerocopy::{FromBytes, IntoBytes}; // UIO mapping indices const FPGA_WRAPPER_MAPPING: (usize, usize) = (0, 0); const CALIPTRA_MAPPING: (usize, usize) = (0, 1); const CALIPTRA_ROM_MAPPING: (usize, usize) = (0, 2); const I3C_CONTROLLER_MAPPING: (usize, usize) = (0, 3); const OTP_RAM_MAPPING: (usize, usize) = (0, 4); const LC_MAPPING: (usize, usize) = (1, 0); const MCU_ROM_MAPPING: (usize, usize) = (1, 1); const I3C_TARGET_MAPPING: (usize, usize) = (1, 2); const MCI_MAPPING: (usize, usize) = (1, 3); const OTP_MAPPING: (usize, usize) = (1, 4); // TODO(timothytrippel): autogenerate these from the OTP memory map definition // Offsets in the OTP for all partitions. // SW_TEST_UNLOCK_PARTITION const OTP_SW_TEST_UNLOCK_PARTITION_OFFSET: usize = 0x0; // SW_MANUF_PARTITION const OTP_SW_MANUF_PARTITION_OFFSET: usize = 0x0F8; // SECRET_LC_TRANSITION_PARTITION const OTP_SECRET_LC_TRANSITION_PARTITION_OFFSET: usize = 0x300; // SVN_PARTITION const OTP_SVN_PARTITION_OFFSET: usize = 0x3B8; const OTP_SVN_PARTITION_FMC_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 0; // 4 bytes const OTP_SVN_PARTITION_RUNTIME_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 4; // 16 bytes const OTP_SVN_PARTITION_SOC_MANIFEST_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 20; // 16 bytes const OTP_SVN_PARTITION_SOC_MAX_SVN_FIELD_OFFSET: usize = OTP_SVN_PARTITION_OFFSET + 36; // 1 byte used // VENDOR_HASHES_MANUF_PARTITION const OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET: usize = 0x420; const FUSE_VENDOR_PKHASH_OFFSET: usize = OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET; const FUSE_PQC_OFFSET: usize = OTP_VENDOR_HASHES_MANUF_PARTITION_OFFSET + 48; // VENDOR_HASHES_PROD_PARTITION const OTP_VENDOR_HASHES_PROD_PARTITION_OFFSET: usize = 0x460; const FUSE_OWNER_PKHASH_OFFSET: usize = OTP_VENDOR_HASHES_PROD_PARTITION_OFFSET; // 48 bytes // VENDOR_REVOCATIONS_PROD_PARTITION const OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET: usize = 0x7C0; const FUSE_VENDOR_ECC_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 12; // 4 bytes const FUSE_VENDOR_LMS_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 16; // 4 bytes const FUSE_VENDOR_REVOCATION_OFFSET: usize = OTP_VENDOR_REVOCATIONS_PROD_PARTITION_OFFSET + 20; // 4 bytes // LIFECYCLE_PARTITION // VENDOR_NON_SECRET_PROD_PARTITION pub const VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET: usize = 0xaa8; const UDS_SEED_OFFSET: usize = VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET; // 64 bytes const FIELD_ENTROPY_OFFSET: usize = VENDOR_NON_SECRET_PROD_PARTITION_BYTE_OFFSET + 64; // 32 bytes // CPTRA_SS_LOCK_HEK_PROD partitions const OTP_CPTRA_SS_LOCK_HEK_PROD_0_OFFSET: usize = 0xCB0; const OTP_CPTRA_SS_LOCK_HEK_PROD_1_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_0_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_2_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_1_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_3_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_2_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_4_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_3_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_5_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_4_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_6_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_5_OFFSET + 48; const OTP_CPTRA_SS_LOCK_HEK_PROD_7_OFFSET: usize = OTP_CPTRA_SS_LOCK_HEK_PROD_6_OFFSET + 48; // LIFECYCLE_PARTITION const OTP_LIFECYCLE_PARTITION_OFFSET: usize = 0xE30; // These are the default physical addresses for the peripherals. The addresses listed in // FPGA_MEMORY_MAP are physical addresses specific to the FPGA. These addresses are used over the // FPGA addresses so similar code can be used between the emulator and the FPGA hardware models. // These are only used for calculating offsets from the virtual addresses retrieved from UIO. const EMULATOR_I3C_ADDR: usize = 0x2000_4000; const EMULATOR_I3C_ADDR_RANGE_SIZE: usize = 0x1000; const EMULATOR_I3C_END_ADDR: usize = EMULATOR_I3C_ADDR + EMULATOR_I3C_ADDR_RANGE_SIZE - 1; const EMULATOR_MCI_ADDR: usize = 0x2100_0000; const EMULATOR_MCI_ADDR_RANGE_SIZE: usize = 0xe0_0000; const EMULATOR_MCI_END_ADDR: usize = EMULATOR_MCI_ADDR + EMULATOR_MCI_ADDR_RANGE_SIZE - 1; pub(crate) fn fmt_uio_error(err: UioError) -> String { format!("{err:?}") } /// Configures the memory map for the MCU. /// These are the defaults that can be overridden and provided to the ROM and runtime builds. #[repr(C)] pub struct McuMemoryMap { pub rom_offset: u32, pub rom_size: u32, pub rom_stack_size: u32, pub sram_offset: u32, pub sram_size: u32, pub pic_offset: u32, pub dccm_offset: u32, pub dccm_size: u32, pub i3c_offset: u32, pub i3c_size: u32, pub mci_offset: u32, pub mci_size: u32, pub mbox_offset: u32, pub mbox_size: u32, pub soc_offset: u32, pub soc_size: u32, pub otp_offset: u32, pub otp_size: u32, pub lc_offset: u32, pub lc_size: u32, } const FPGA_MEMORY_MAP: McuMemoryMap = McuMemoryMap { rom_offset: 0xb004_0000, rom_size: 128 * 1024, rom_stack_size: 0x3000, dccm_offset: 0x5000_0000, dccm_size: 16 * 1024, sram_offset: 0xa8c0_0000, sram_size: 384 * 1024, pic_offset: 0x6000_0000, i3c_offset: 0xa403_0000, i3c_size: 0x1000, mci_offset: 0xa800_0000, mci_size: 0xa0_0028, mbox_offset: 0xa412_0000, mbox_size: 0x28, soc_offset: 0xa413_0000, soc_size: 0x5e0, otp_offset: 0xa406_0000, otp_size: OTP_FULL_SIZE as u32, lc_offset: 0xa404_0000, lc_size: 0x8c, }; // Set to core_clk cycles per ITRNG sample. const ITRNG_DIVISOR: u32 = 400; const DEFAULT_AXI_PAUSER: u32 = 0x1; // we split the OTP memory into two parts: the OTP half and a simulated flash half. const OTP_FULL_SIZE: usize = 16384; const FLASH_SIZE: usize = 8192; const OTP_SIZE: usize = 8192; const _: () = assert!(OTP_SIZE + FLASH_SIZE == OTP_FULL_SIZE); const _: () = assert!(OTP_LIFECYCLE_PARTITION_OFFSET + 88 + 8 <= OTP_SIZE); const AXI_CLK_HZ: u32 = 199_999_000; const I3C_CLK_HZ: u32 = 12_500_000; // ITRNG FIFO stores 1024 DW and outputs 4 bits at a time to Caliptra. const FPGA_ITRNG_FIFO_SIZE: usize = 1024; const I3C_WRITE_FIFO_SIZE: u16 = 128; pub struct Wrapper { pub ptr: *mut u32, } impl Wrapper { pub fn regs(&self) -> &mut WrapperRegs { unsafe { &mut *(self.ptr as *mut WrapperRegs) } } pub fn fifo_regs(&self) -> &mut FifoRegs { unsafe { &mut *(self.ptr.offset(0x1000 / 4) as *mut FifoRegs) } } } unsafe impl Send for Wrapper {} unsafe impl Sync for Wrapper {} #[derive(Clone)] pub struct Mci { pub ptr: *mut u32, } impl Mci { pub fn regs(&self) -> caliptra_registers::mci::RegisterBlock<BusMmio<FpgaRealtimeBus<'_>>> { unsafe { caliptra_registers::mci::RegisterBlock::new_with_mmio( EMULATOR_MCI_ADDR as *mut u32, BusMmio::new(FpgaRealtimeBus { mmio: self.ptr, phantom: Default::default(), }), ) } } } #[derive(Clone)] pub struct XI3CWrapper { pub controller: Arc<Mutex<xi3c::Controller>>, // TODO: remove pub from these once we know all the ways we need to use them. // TODO: Possibly use Mutex to protect access as well. pub i3c_mmio: *mut u32, pub i3c_controller_mmio: *mut u32, } // needed to copy pointers // Safety: the pointers are themselves perfectly thread-safe since they are static, but // the underlying hardware behavior may not be guaranteed if they are used by multiple threads. unsafe impl Send for XI3CWrapper {} unsafe impl Sync for XI3CWrapper {} impl XI3CWrapper { pub unsafe fn i3c_core( &self, ) -> caliptra_registers::i3ccsr::RegisterBlock<BusMmio<FpgaRealtimeBus<'_>>> { caliptra_registers::i3ccsr::RegisterBlock::new_with_mmio( EMULATOR_I3C_ADDR as *mut u32, BusMmio::new(FpgaRealtimeBus { mmio: self.i3c_mmio, phantom: Default::default(), }), ) } pub const unsafe fn regs(&self) -> &xi3c::XI3c { &*(self.i3c_controller_mmio as *const xi3c::XI3c) } pub fn configure(&self) { println!("I3C controller initializing"); // Safety: we are only reading the register println!("XI3C HW version = {:x}", unsafe { self.regs().version.get() }); const I3C_MODE: u8 = 1; self.controller .lock() .unwrap() .set_s_clk(AXI_CLK_HZ, I3C_CLK_HZ, I3C_MODE); self.controller.lock().unwrap().cfg_initialize().unwrap(); println!("I3C controller finished initializing"); } /// Start receiving data (non-blocking). pub fn read_start(&self, len: u16) -> Result<(), XI3cError> { let target_addr = self.get_primary_addr(); let cmd = xi3c::Command { no_repeated_start: 1, pec: 0, target_addr, ..Default::default() }; self.controller.lock().unwrap().master_recv(&cmd, len) } /// Finish receiving data (blocking). pub fn read_finish(&self, len: u16) -> Result<Vec<u8>, XI3cError> { let target_addr = self.get_primary_addr(); let cmd = xi3c::Command { cmd_type: 1, no_repeated_start: 1, pec: 0, target_addr, ..Default::default() }; self.controller .lock() .unwrap() .master_recv_finish(None, &cmd, len) } /// Receive data (blocking). pub fn read(&self, len: u16) -> Result<Vec<u8>, XI3cError> { let target_addr = self.get_primary_addr(); let cmd = xi3c::Command { no_repeated_start: 1, target_addr, ..Default::default() }; self.controller .lock() .unwrap() .master_recv_polled(None, &cmd, len) } pub fn get_primary_addr(&self) -> u8 { // Safety: we are only reading the register let reg = unsafe { self.i3c_core() .stdby_ctrl_mode() .stby_cr_device_addr() .read() }; if reg.dynamic_addr_valid() { reg.dynamic_addr() as u8 } else if reg.static_addr_valid() { reg.static_addr() as u8 } else { panic!("I3C target does not have a valid address set"); } } fn get_recovery_addr(&self) -> u8 { // Safety: we are only reading the register let reg = unsafe { self.i3c_core() .stdby_ctrl_mode() .stby_cr_virt_device_addr() .read() }; if reg.virt_dynamic_addr_valid() { reg.virt_dynamic_addr() as u8 } else if reg.virt_static_addr_valid() { reg.virt_static_addr() as u8 } else { panic!("I3C virtual target does not have a valid address set"); } } /// Write data and wait for ACK (blocking). pub fn write(&self, payload: &[u8]) -> Result<(), XI3cError> { let target_addr = self.get_primary_addr(); let cmd = xi3c::Command { no_repeated_start: 1, target_addr, ..Default::default() }; self.controller .lock() .unwrap() .master_send_polled(&cmd, payload, payload.len() as u16) } /// Send data but don't wait for ACK (non-blocking). pub fn write_nowait(&self, payload: &[u8]) -> Result<(), XI3cError> { let target_addr = self.get_primary_addr(); let cmd = xi3c::Command { no_repeated_start: 1, target_addr, ..Default::default() }; self.controller .lock() .unwrap() .master_send(&cmd, payload, payload.len() as u16) } pub fn ibi_ready(&self) -> bool { self.controller.lock().unwrap().ibi_ready() } pub fn ibi_recv(&self, timeout: Option<Duration>) -> Result<Vec<u8>, XI3cError> { self.controller .lock() .unwrap() .ibi_recv_polled(timeout.unwrap_or(Duration::from_millis(1))) // 256 bytes only takes ~0.2ms to transmit, so this gives us plenty of time } /// Available space in CMD_FIFO to write pub fn cmd_fifo_level(&self) -> u16 { self.controller.lock().unwrap().cmd_fifo_level() } /// Available space in WR_FIFO to write pub fn write_fifo_level(&self) -> u16 { self.controller.lock().unwrap().write_fifo_level() } /// Number of RESP status details are available in RESP_FIFO to read pub fn resp_fifo_level(&self) -> u16 { self.controller.lock().unwrap().resp_fifo_level() } /// Number of read data words are available in RD_FIFO to read pub fn read_fifo_level(&self) -> u16 { self.controller.lock().unwrap().read_fifo_level() } pub fn write_fifo_empty(&self) -> bool { self.write_fifo_level() == I3C_WRITE_FIFO_SIZE } } pub struct ModelFpgaSubsystem { pub devs: [UioDevice; 2], pub wrapper: Arc<Wrapper>, pub caliptra_rom_backdoor: *mut u8, pub mcu_rom_backdoor: *mut u8, pub otp_mem_backdoor: *mut u8, // Reset sensitive MMIO UIO pointers. Accessing these while subsystem is in reset will trigger // a kernel panic. pub mmio: SensitiveMmio, pub realtime_thread: Option<thread::JoinHandle<()>>, pub realtime_thread_exit_flag: Arc<AtomicBool>, pub fuses: Fuses, pub otp_init: Vec<u8>, pub output: Output, pub recovery_started: bool, pub bmc: Bmc, pub from_bmc: mpsc::Receiver<Event>, pub to_bmc: mpsc::Sender<Event>, pub recovery_fifo_blocks: Vec<Vec<u8>>, pub recovery_ctrl_len: usize, pub recovery_ctrl_written: bool, pub bmc_step_counter: usize, pub blocks_sent: usize, pub enable_mcu_uart_log: bool, pub bootfsm_break: bool, pub rom_callback: Option<ModelCallback>, } impl ModelFpgaSubsystem { fn set_bootfsm_break(&mut self, val: bool) { if val { self.wrapper .regs() .control .modify(Control::BootfsmBrkpoint::SET); } else { self.wrapper .regs() .control .modify(Control::BootfsmBrkpoint::CLEAR); } } fn set_ss_ocp_lock(&mut self, val: bool) { if val { self.wrapper.regs().control.modify(Control::OcpLockEn::SET); } else { self.wrapper .regs() .control .modify(Control::OcpLockEn::CLEAR); } } fn set_ss_debug_intent(&mut self, val: bool) { if val { self.wrapper .regs() .control .modify(Control::SsDebugIntent::SET); } else { self.wrapper .regs() .control .modify(Control::SsDebugIntent::CLEAR); } } fn set_ss_rma_or_scrap_ppd(&mut self, val: bool) { if val { self.wrapper .regs() .control .modify(Control::LcAllowRmaOrScrapOnPpd::SET); } else { self.wrapper .regs() .control .modify(Control::LcAllowRmaOrScrapOnPpd::CLEAR); } } fn set_raw_unlock_token_hash(&mut self, token_hash: &[u32; 4]) { for i in 0..token_hash.len() { self.wrapper.regs().cptr_ss_raw_unlock_token_hash[i].set(token_hash[i]); } } fn axi_reset(&mut self) { self.wrapper.regs().control.modify(Control::AxiReset.val(1)); // wait a few clock cycles or we can crash the FPGA std::thread::sleep(std::time::Duration::from_micros(1)); } pub fn set_subsystem_reset(&mut self, reset: bool) { if reset { self.mmio.disable(); } self.wrapper.regs().control.modify( Control::CptraSsRstB.val((!reset) as u32) + Control::CptraPwrgood.val((!reset) as u32), ); if !reset { self.mmio.enable(); } } pub fn set_cptra_ss_rst_b(&mut self, value: bool) { self.wrapper .regs() .control .modify(Control::CptraSsRstB.val(value as u32)); } fn set_secrets_valid(&mut self, value: bool) { self.wrapper.regs().control.modify( Control::CptraObfUdsSeedVld.val(value as u32) + Control::CptraObfFieldEntropyVld.val(value as u32), ) } fn clear_logs(&mut self) { println!("Clearing Caliptra logs"); loop { if self .wrapper .fifo_regs() .log_fifo_status .is_set(FifoStatus::Empty) { break; } if !self .wrapper .fifo_regs() .log_fifo_data .is_set(FifoData::CharValid) { break; } } println!("Clearing MCU logs"); loop { if self .wrapper .fifo_regs() .dbg_fifo_status .is_set(FifoStatus::Empty) { break; } if !self .wrapper .fifo_regs() .dbg_fifo_data_pop .is_set(FifoData::CharValid) { break; } } } fn handle_log(&mut self) { loop { // Check if the FIFO is full (which probably means there was an overrun) if self .wrapper .fifo_regs() .log_fifo_status .is_set(FifoStatus::Full) { panic!("FPGA log FIFO overran"); } if self .wrapper .fifo_regs() .log_fifo_status .is_set(FifoStatus::Empty) { break; } let data = self.wrapper.fifo_regs().log_fifo_data.extract(); // Add byte to log if it is valid if data.is_set(FifoData::CharValid) { self.output() .sink() .push_uart_char(data.read(FifoData::NextChar) as u8); } } if self.enable_mcu_uart_log { loop { // Check if the FIFO is full (which probably means there was an overrun) if self .wrapper .fifo_regs() .dbg_fifo_status .is_set(FifoStatus::Full) { panic!("FPGA log FIFO overran"); } if self .wrapper .fifo_regs() .dbg_fifo_status .is_set(FifoStatus::Empty) { break; } let data = self.wrapper.fifo_regs().dbg_fifo_data_pop.extract(); // Add byte to log if it is valid if data.is_set(FifoData::CharValid) { self.output() .sink() .push_uart_char(data.read(FifoData::NextChar) as u8); } } } } // UIO crate doesn't provide a way to unmap memory. pub fn unmap_mapping(&self, addr: *mut u32, mapping: (usize, usize)) { let map_size = self.devs[mapping.0].map_size(mapping.1).unwrap(); unsafe { nix::sys::mman::munmap(addr as *mut libc::c_void, map_size).unwrap(); } } fn realtime_thread_itrng_fn( wrapper: Arc<Wrapper>, running: Arc<AtomicBool>, mut itrng_nibbles: Box<dyn Iterator<Item = u8> + Send>, ) { // Reset ITRNG FIFO to clear out old data wrapper .fifo_regs() .itrng_fifo_status .write(ItrngFifoStatus::Reset::SET); wrapper .fifo_regs() .itrng_fifo_status .write(ItrngFifoStatus::Reset::CLEAR); // Small delay to allow reset to complete thread::sleep(Duration::from_millis(1)); while running.load(Ordering::Relaxed) { // Once TRNG data is requested the FIFO will continously empty. Load at max one FIFO load at a time. // FPGA ITRNG FIFO is 1024 DW deep. for _ in 0..FPGA_ITRNG_FIFO_SIZE { if !wrapper .fifo_regs() .itrng_fifo_status .is_set(ItrngFifoStatus::Full) { let mut itrng_dw = 0; for i in 0..8 { match itrng_nibbles.next() { Some(nibble) => itrng_dw += u32::from(nibble) << (4 * i), None => return, } } wrapper.fifo_regs().itrng_fifo_data.set(itrng_dw); } else { break; } } // 1 second * (20 MHz / (2^13 throttling counter)) / 8 nibbles per DW: 305 DW of data consumed in 1 second. let end_time = Instant::now() + Duration::from_millis(1000); while running.load(Ordering::Relaxed) && Instant::now() < end_time { thread::sleep(Duration::from_millis(1)); } } } pub fn i3c_core( &mut self, ) -> Option<caliptra_registers::i3ccsr::RegisterBlock<BusMmio<FpgaRealtimeBus<'_>>>> { self.mmio.i3c_core() } pub fn i3c_controller(&self) -> Option<XI3CWrapper> { self.mmio.i3c_controller().clone() } pub fn i3c_target_configured(&mut self) -> bool { u32::from( self.i3c_core() .unwrap() .stdby_ctrl_mode() .stby_cr_device_addr() .read(), ) != 0 } pub fn start_recovery_bmc(&mut self) { self.recovery_started = true; } fn bmc_step(&mut self) { if !self.recovery_started { return; } self.bmc_step_counter += 1; // check if we need to fill the recovey FIFO if !self.recovery_fifo_blocks.is_empty() { if !self.recovery_ctrl_written { let status = self .i3c_core() .unwrap() .sec_fw_recovery_if() .device_status_0() .read() .dev_status(); if status != 3 && self.bmc_step_counter % 65536 == 0 { println!("Waiting for device status to be 3, currently: {}", status); return; } // wait for any other packets to be sent if !self.i3c_controller().unwrap().write_fifo_empty() { return; } let len = ((self.recovery_ctrl_len / 4) as u32).to_le_bytes(); let mut ctrl = vec![0, 1]; // CMS = 0, reset FIFO ctrl.extend_from_slice(&len); println!("Writing Indirect fifo ctrl: {:x?}", ctrl); self.recovery_block_write_request(RecoveryCommandCode::IndirectFifoCtrl, &ctrl); let reported_len = self .i3c_core() .unwrap() .sec_fw_recovery_if() .indirect_fifo_ctrl_1() .read(); println!("I3C core reported length: {}", reported_len); if reported_len as usize != self.recovery_ctrl_len / 4 { println!( "I3C core reported length should have been {}", self.recovery_ctrl_len / 4 ); self.print_i3c_registers(); panic!( "I3C core reported length should have been {}", self.recovery_ctrl_len / 4 ); } self.recovery_ctrl_written = true; } let fifo_status = self .i3c_core() .unwrap() .sec_fw_recovery_if() .indirect_fifo_status_0() .read(); // fifo is empty, send a block if fifo_status.empty() { let chunk = self.recovery_fifo_blocks.pop().unwrap(); self.blocks_sent += 1; self.recovery_block_write_request(RecoveryCommandCode::IndirectFifoData, &chunk); return; } } let status = self .i3c_core() .unwrap() .sec_fw_recovery_if() .recovery_status() .read() .dev_rec_status(); const DEVICE_RECOVERY_STATUS_COMPLETE: u32 = 3; if status == DEVICE_RECOVERY_STATUS_COMPLETE { println!("Recovery complete; device recovery status: 0x{:x}", status); self.recovery_started = false; return; } // don't run the BMC every time as it can spam requests if self.bmc_step_counter < 100_000 || self.bmc_step_counter % 10_000 != 0 { return; } self.bmc.step(); // we need to translate from the BMC events to the I3C controller block reads and writes let Ok(event) = self.from_bmc.try_recv() else { return; }; // ignore messages that aren't meant for Caliptra core. if !matches!(event.dest, Device::CaliptraCore) { return; } match event.event { EventData::RecoveryBlockReadRequest { source_addr, target_addr, command_code, } => { // println!("From BMC: Recovery block read request {:?}", command_code); if let Some(payload) = self.recovery_block_read_request(command_code) { self.to_bmc .send(Event { src: Device::CaliptraCore, dest: Device::BMC, event: EventData::RecoveryBlockReadResponse { source_addr: target_addr, target_addr: source_addr, command_code, payload, }, }) .unwrap(); } } EventData::RecoveryBlockReadResponse { source_addr: _, target_addr: _, command_code: _, payload: _, } => todo!(), EventData::RecoveryBlockWrite { source_addr: _, target_addr: _, command_code, payload, } => { //println!("Recovery block write request: {:?}", command_code); self.recovery_block_write_request(command_code, &payload); } EventData::RecoveryImageAvailable { image_id: _, image } => { // do the indirect fifo thing println!("Recovery image available; writing blocks"); self.recovery_ctrl_len = image.len(); self.recovery_ctrl_written = false; self.recovery_fifo_blocks = image.chunks(256).map(|chunk| chunk.to_vec()).collect(); self.recovery_fifo_blocks.reverse(); // reverse so we can pop from the end } _ => todo!(), } } fn command_code_to_u8(command: RecoveryCommandCode) -> u8 { match command { RecoveryCommandCode::ProtCap => 34, RecoveryCommandCode::DeviceId => 35, RecoveryCommandCode::DeviceStatus => 36, RecoveryCommandCode::DeviceReset => 37, RecoveryCommandCode::RecoveryCtrl => 38, RecoveryCommandCode::RecoveryStatus => 39, RecoveryCommandCode::HwStatus => 40, RecoveryCommandCode::IndirectCtrl => 41, RecoveryCommandCode::IndirectStatus => 42, RecoveryCommandCode::IndirectData => 43, RecoveryCommandCode::Vendor => 44, RecoveryCommandCode::IndirectFifoCtrl => 45, RecoveryCommandCode::IndirectFifoStatus => 46, RecoveryCommandCode::IndirectFifoData => 47, } } fn command_code_to_len(command: RecoveryCommandCode) -> (u16, u16) { match command { RecoveryCommandCode::ProtCap => (15, 15), RecoveryCommandCode::DeviceId => (24, 255), RecoveryCommandCode::DeviceStatus => (7, 255), RecoveryCommandCode::DeviceReset => (3, 3), RecoveryCommandCode::RecoveryCtrl => (3, 3), RecoveryCommandCode::RecoveryStatus => (2, 2), RecoveryCommandCode::HwStatus => (4, 255), RecoveryCommandCode::IndirectCtrl => (6, 6), RecoveryCommandCode::IndirectStatus => (6, 6), RecoveryCommandCode::IndirectData => (1, 252), RecoveryCommandCode::Vendor => (1, 255), RecoveryCommandCode::IndirectFifoCtrl => (6, 6), RecoveryCommandCode::IndirectFifoStatus => (20, 20), RecoveryCommandCode::IndirectFifoData => (1, 4095), } } fn print_i3c_registers(&mut self) { println!("Dumping registers"); println!( "sec_fw_recovery_if_prot_cap_0: {:08x}", self.i3c_core() .unwrap() .sec_fw_recovery_if() .prot_cap_0() .read() .swap_bytes() ); println!( "sec_fw_recovery_if_prot_cap_1: {:08x}", self.i3c_core() .unwrap() .sec_fw_recovery_if() .prot_cap_1() .read() .swap_bytes() ); println!( "sec_fw_recovery_if_prot_cap_2: {:08x}", u32::from( self.i3c_core() .unwrap() .sec_fw_recovery_if() .prot_cap_2() .read() ) .swap_bytes() ); println!( "sec_fw_recovery_if_prot_cap_3: {:08x}", u32::from( self.i3c_core() .unwrap()
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/otp_provision.rs
hw-model/src/otp_provision.rs
// Licensed under the Apache-2.0 license #![allow(dead_code)] use crate::otp_digest::{otp_digest, otp_scramble, otp_unscramble}; use caliptra_image_fake_keys::{VENDOR_ECC_KEY_0_PUBLIC, VENDOR_MLDSA_KEY_0_PUBLIC}; use anyhow::{bail, Result}; use sha2::{Digest, Sha384, Sha512}; use sha3::{digest::ExtendableOutput, digest::Update, CShake128, CShake128Core}; use zerocopy::{FromBytes, IntoBytes, KnownLayout}; /// Unhashed token, suitable for doing lifecycle transitions. #[derive(Clone, Copy)] pub struct LifecycleToken(pub [u8; 16]); impl From<[u8; 16]> for LifecycleToken { fn from(value: [u8; 16]) -> Self { LifecycleToken(value) } } impl From<LifecycleToken> for [u8; 16] { fn from(value: LifecycleToken) -> Self { value.0 } } /// Raw lifecycle tokens. pub struct LifecycleRawTokens { pub test_unlock: [LifecycleToken; 7], pub manuf: LifecycleToken, pub manuf_to_prod: LifecycleToken, pub prod_to_prod_end: LifecycleToken, pub rma: LifecycleToken, } /// Hashed token, suitable for burning into OTP. #[derive(Clone, Copy)] pub struct LifecycleHashedToken(pub [u8; 16]); impl From<[u8; 16]> for LifecycleHashedToken { fn from(value: [u8; 16]) -> Self { LifecycleHashedToken(value) } } impl From<LifecycleHashedToken> for [u8; 16] { fn from(value: LifecycleHashedToken) -> Self { value.0 } } /// Hashed lifecycle tokens to be burned into OTP to enable lifecycle transitions. pub struct LifecycleHashedTokens { pub test_unlock: [LifecycleHashedToken; 7], pub manuf: LifecycleHashedToken, pub manuf_to_prod: LifecycleHashedToken, pub prod_to_prod_end: LifecycleHashedToken, pub rma: LifecycleHashedToken, } /// Raw (unhashed) manuf debug unlock token. #[derive(Clone, Copy)] pub struct ManufDebugUnlockToken(pub [u32; 8]); impl From<[u32; 8]> for ManufDebugUnlockToken { fn from(value: [u32; 8]) -> Self { ManufDebugUnlockToken(value) } } impl From<ManufDebugUnlockToken> for [u32; 8] { fn from(value: ManufDebugUnlockToken) -> Self { value.0 } } impl From<ManufDebugUnlockToken> for [u8; 32] { fn from(value: ManufDebugUnlockToken) -> Self { let mut dest = [0u8; 32]; let mut offset = 0; for &val in value.0.iter() { let bytes = val.to_le_bytes(); // Returns [u8; 4] dest[offset..offset + 4].copy_from_slice(&bytes); offset += 4; } dest } } /// Hashed (SHA512) manuf debug unlock token. #[derive(Clone, Copy)] pub struct ManufDebugUnlockHashedToken(pub [u8; 64]); impl From<[u8; 64]> for ManufDebugUnlockHashedToken { fn from(value: [u8; 64]) -> Self { ManufDebugUnlockHashedToken(value) } } impl From<ManufDebugUnlockHashedToken> for [u8; 64] { fn from(value: ManufDebugUnlockHashedToken) -> Self { value.0 } } #[derive(Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum LifecycleControllerState { Raw = 0, TestUnlocked0 = 1, TestLocked0 = 2, TestUnlocked1 = 3, TestLocked1 = 4, TestUnlocked2 = 5, TestLocked2 = 6, TestUnlocked3 = 7, TestLocked3 = 8, TestUnlocked4 = 9, TestLocked4 = 10, TestUnlocked5 = 11, TestLocked5 = 12, TestUnlocked6 = 13, TestLocked6 = 14, TestUnlocked7 = 15, Dev = 16, Prod = 17, ProdEnd = 18, Rma = 19, Scrap = 20, } impl core::fmt::Display for LifecycleControllerState { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { LifecycleControllerState::Raw => write!(f, "raw"), LifecycleControllerState::TestUnlocked0 => write!(f, "test_unlocked0"), LifecycleControllerState::TestLocked0 => write!(f, "test_locked0"), LifecycleControllerState::TestUnlocked1 => write!(f, "test_unlocked1"), LifecycleControllerState::TestLocked1 => write!(f, "test_locked1"), LifecycleControllerState::TestUnlocked2 => write!(f, "test_unlocked2"), LifecycleControllerState::TestLocked2 => write!(f, "test_locked2"), LifecycleControllerState::TestUnlocked3 => write!(f, "test_unlocked3"), LifecycleControllerState::TestLocked3 => write!(f, "test_locked3"), LifecycleControllerState::TestUnlocked4 => write!(f, "test_unlocked4"), LifecycleControllerState::TestLocked4 => write!(f, "test_locked4"), LifecycleControllerState::TestUnlocked5 => write!(f, "test_unlocked5"), LifecycleControllerState::TestLocked5 => write!(f, "test_locked5"), LifecycleControllerState::TestUnlocked6 => write!(f, "test_unlocked6"), LifecycleControllerState::TestLocked6 => write!(f, "test_locked6"), LifecycleControllerState::TestUnlocked7 => write!(f, "test_unlocked7"), LifecycleControllerState::Dev => write!(f, "dev"), LifecycleControllerState::Prod => write!(f, "prod"), LifecycleControllerState::ProdEnd => write!(f, "prod_end"), LifecycleControllerState::Rma => write!(f, "rma"), LifecycleControllerState::Scrap => write!(f, "scrap"), } } } impl core::str::FromStr for LifecycleControllerState { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "raw" => Ok(LifecycleControllerState::Raw), "test_unlocked0" => Ok(LifecycleControllerState::TestUnlocked0), "test_locked0" => Ok(LifecycleControllerState::TestLocked0), "test_unlocked1" => Ok(LifecycleControllerState::TestUnlocked1), "test_locked1" => Ok(LifecycleControllerState::TestLocked1), "test_unlocked2" => Ok(LifecycleControllerState::TestUnlocked2), "test_locked2" => Ok(LifecycleControllerState::TestLocked2), "test_unlocked3" => Ok(LifecycleControllerState::TestUnlocked3), "test_locked3" => Ok(LifecycleControllerState::TestLocked3), "test_unlocked4" => Ok(LifecycleControllerState::TestUnlocked4), "test_locked4" => Ok(LifecycleControllerState::TestLocked4), "test_unlocked5" => Ok(LifecycleControllerState::TestUnlocked5), "test_locked5" => Ok(LifecycleControllerState::TestLocked5), "test_unlocked6" => Ok(LifecycleControllerState::TestUnlocked6), "test_locked6" => Ok(LifecycleControllerState::TestLocked6), "test_unlocked7" => Ok(LifecycleControllerState::TestUnlocked7), "dev" | "manuf" | "manufacturing" => Ok(LifecycleControllerState::Dev), "production" | "prod" => Ok(LifecycleControllerState::Prod), "prod_end" => Ok(LifecycleControllerState::ProdEnd), "rma" => Ok(LifecycleControllerState::Rma), "scrap" => Ok(LifecycleControllerState::Scrap), _ => Err("Invalid lifecycle state"), } } } impl From<LifecycleControllerState> for u8 { fn from(value: LifecycleControllerState) -> Self { match value { LifecycleControllerState::Raw => 0, LifecycleControllerState::TestUnlocked0 => 1, LifecycleControllerState::TestLocked0 => 2, LifecycleControllerState::TestUnlocked1 => 3, LifecycleControllerState::TestLocked1 => 4, LifecycleControllerState::TestUnlocked2 => 5, LifecycleControllerState::TestLocked2 => 6, LifecycleControllerState::TestUnlocked3 => 7, LifecycleControllerState::TestLocked3 => 8, LifecycleControllerState::TestUnlocked4 => 9, LifecycleControllerState::TestLocked4 => 10, LifecycleControllerState::TestUnlocked5 => 11, LifecycleControllerState::TestLocked5 => 12, LifecycleControllerState::TestUnlocked6 => 13, LifecycleControllerState::TestLocked6 => 14, LifecycleControllerState::TestUnlocked7 => 15, LifecycleControllerState::Dev => 16, LifecycleControllerState::Prod => 17, LifecycleControllerState::ProdEnd => 18, LifecycleControllerState::Rma => 19, LifecycleControllerState::Scrap => 20, } } } impl From<u8> for LifecycleControllerState { fn from(value: u8) -> Self { match value { 1 => LifecycleControllerState::TestUnlocked0, 2 => LifecycleControllerState::TestLocked0, 3 => LifecycleControllerState::TestUnlocked1, 4 => LifecycleControllerState::TestLocked1, 5 => LifecycleControllerState::TestUnlocked2, 6 => LifecycleControllerState::TestLocked2, 7 => LifecycleControllerState::TestUnlocked3, 8 => LifecycleControllerState::TestLocked3, 9 => LifecycleControllerState::TestUnlocked4, 10 => LifecycleControllerState::TestLocked4, 11 => LifecycleControllerState::TestUnlocked5, 12 => LifecycleControllerState::TestLocked5, 13 => LifecycleControllerState::TestUnlocked6, 14 => LifecycleControllerState::TestLocked6, 15 => LifecycleControllerState::TestUnlocked7, 16 => LifecycleControllerState::Dev, 17 => LifecycleControllerState::Prod, 18 => LifecycleControllerState::ProdEnd, 19 => LifecycleControllerState::Rma, 20 => LifecycleControllerState::Scrap, _ => LifecycleControllerState::Raw, } } } impl From<u32> for LifecycleControllerState { fn from(value: u32) -> Self { ((value & 0x1f) as u8).into() } } // These are the default lifecycle controller constants from the // standard Caliptra RTL. These can be overridden by vendors. // from caliptra-rtl/src/lc_ctrl/rtl/lc_ctrl_state_pkg.sv const _A0: u16 = 0b0110010010101110; // ECC: 6'b001010 const B0: u16 = 0b0111010111101110; // ECC: 6'b111110 const A1: u16 = 0b0000011110110100; // ECC: 6'b100101 const B1: u16 = 0b0000111111111110; // ECC: 6'b111101 const A2: u16 = 0b0011000111010010; // ECC: 6'b000111 const B2: u16 = 0b0111101111111110; // ECC: 6'b000111 const A3: u16 = 0b0010111001001101; // ECC: 6'b001010 const B3: u16 = 0b0011111101101111; // ECC: 6'b111010 const A4: u16 = 0b0100000111111000; // ECC: 6'b011010 const B4: u16 = 0b0101111111111100; // ECC: 6'b011110 const A5: u16 = 0b1010110010000101; // ECC: 6'b110001 const B5: u16 = 0b1111110110011111; // ECC: 6'b110001 const A6: u16 = 0b1001100110001100; // ECC: 6'b010110 const B6: u16 = 0b1111100110011111; // ECC: 6'b011110 const A7: u16 = 0b0101001100001111; // ECC: 6'b100010 const B7: u16 = 0b1101101101101111; // ECC: 6'b100111 const A8: u16 = 0b0111000101100000; // ECC: 6'b111001 const B8: u16 = 0b0111001101111111; // ECC: 6'b111001 const A9: u16 = 0b0010110001100011; // ECC: 6'b101010 const B9: u16 = 0b0110110001101111; // ECC: 6'b111111 const A10: u16 = 0b0110110100001000; // ECC: 6'b110011 const B10: u16 = 0b0110111110011110; // ECC: 6'b111011 const A11: u16 = 0b1001001001001100; // ECC: 6'b000011 const B11: u16 = 0b1101001111011100; // ECC: 6'b111111 const A12: u16 = 0b0111000001000000; // ECC: 6'b011110 const B12: u16 = 0b0111011101010010; // ECC: 6'b111110 const A13: u16 = 0b1001001010111110; // ECC: 6'b000010 const B13: u16 = 0b1111001011111110; // ECC: 6'b101110 const A14: u16 = 0b1001010011010010; // ECC: 6'b100011 const B14: u16 = 0b1011110111010011; // ECC: 6'b101111 const A15: u16 = 0b0110001010001101; // ECC: 6'b000111 const B15: u16 = 0b0110111111001101; // ECC: 6'b011111 const A16: u16 = 0b1011001000101000; // ECC: 6'b010111 const B16: u16 = 0b1011001011111011; // ECC: 6'b011111 const A17: u16 = 0b0001111001110001; // ECC: 6'b001001 const B17: u16 = 0b1001111111110101; // ECC: 6'b011011 const A18: u16 = 0b0010110110011011; // ECC: 6'b000100 const B18: u16 = 0b0011111111011111; // ECC: 6'b010101 const A19: u16 = 0b0100110110001100; // ECC: 6'b101010 const B19: u16 = 0b1101110110111110; // ECC: 6'b101011 // The C/D values are used for the encoded LC transition counter. const _C0: u16 = 0b0001010010011110; // ECC: 6'b011100 const D0: u16 = 0b1011011011011111; // ECC: 6'b111100 const C1: u16 = 0b0101101011000100; // ECC: 6'b111000 const D1: u16 = 0b1111101011110100; // ECC: 6'b111101 const C2: u16 = 0b0001111100100100; // ECC: 6'b100011 const D2: u16 = 0b0001111110111111; // ECC: 6'b100111 const C3: u16 = 0b1100111010000101; // ECC: 6'b011000 const D3: u16 = 0b1100111011101111; // ECC: 6'b011011 const C4: u16 = 0b0100001010011111; // ECC: 6'b011000 const D4: u16 = 0b0101101110111111; // ECC: 6'b111100 const C5: u16 = 0b1001111000100010; // ECC: 6'b111000 const D5: u16 = 0b1111111110100010; // ECC: 6'b111110 const C6: u16 = 0b0010011110000110; // ECC: 6'b010000 const D6: u16 = 0b0111011111000110; // ECC: 6'b011101 const C7: u16 = 0b0010111101000110; // ECC: 6'b000110 const D7: u16 = 0b1010111111000110; // ECC: 6'b111111 const C8: u16 = 0b0000001011011011; // ECC: 6'b000001 const D8: u16 = 0b1010101111011011; // ECC: 6'b111011 const C9: u16 = 0b0111000011000110; // ECC: 6'b110001 const D9: u16 = 0b1111111011001110; // ECC: 6'b110011 const C10: u16 = 0b0100001000010010; // ECC: 6'b110110 const D10: u16 = 0b0111001010110110; // ECC: 6'b110111 const C11: u16 = 0b0100101111110001; // ECC: 6'b000001 const D11: u16 = 0b0110101111110011; // ECC: 6'b110111 const C12: u16 = 0b1000100101000001; // ECC: 6'b000001 const D12: u16 = 0b1011110101001111; // ECC: 6'b001011 const C13: u16 = 0b1000000000010001; // ECC: 6'b011111 const D13: u16 = 0b1001100010110011; // ECC: 6'b111111 const C14: u16 = 0b0101110000000100; // ECC: 6'b111110 const D14: u16 = 0b1111111010001101; // ECC: 6'b111110 const C15: u16 = 0b1100001000001001; // ECC: 6'b001011 const D15: u16 = 0b1110011000011011; // ECC: 6'b111011 const C16: u16 = 0b0101001001101100; // ECC: 6'b001000 const D16: u16 = 0b0111111001111110; // ECC: 6'b001001 const C17: u16 = 0b0100001001110100; // ECC: 6'b010100 const D17: u16 = 0b1100101001110111; // ECC: 6'b110110 const C18: u16 = 0b1100000001100111; // ECC: 6'b100000 const D18: u16 = 0b1100011101110111; // ECC: 6'b100101 const C19: u16 = 0b1010000001001010; // ECC: 6'b101111 const D19: u16 = 0b1111011101101010; // ECC: 6'b101111 const C20: u16 = 0b1001001001010101; // ECC: 6'b001110 const D20: u16 = 0b1101111011011101; // ECC: 6'b001111 const C21: u16 = 0b1001010000011011; // ECC: 6'b100000 const D21: u16 = 0b1001111000111011; // ECC: 6'b110101 const C22: u16 = 0b1011101101100001; // ECC: 6'b000100 const D22: u16 = 0b1011111101111111; // ECC: 6'b000110 const C23: u16 = 0b1101101000000111; // ECC: 6'b001100 const D23: u16 = 0b1101111011100111; // ECC: 6'b101110 const ZRO: u16 = 0b0000000000000000; // ECC: 6'b000000 const COUNTS: [[u16; 24]; 25] = [ [ ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, C5, C4, C3, C2, C1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, C5, C4, C3, C2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, C5, C4, C3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, C5, C4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, C5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, C6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, C7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, C8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, C9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, C10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, C11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, C12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, C13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, C14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, C15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, C16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, C17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, C18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, C19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, C20, D19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, C21, D20, D19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, C22, D21, D20, D19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ C23, D22, D21, D20, D19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], [ D23, D22, D21, D20, D19, D18, D17, D16, D15, D14, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0, ], ]; const STATES: [[u16; 20]; 21] = [ [ ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ZRO, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, A5, A4, A3, A2, A1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, A5, A4, A3, A2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, A5, A4, A3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, A5, A4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, A5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, A6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, A7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, A8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, A9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, A10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, A11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, A12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, A13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, A14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, A15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, A16, B15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, A17, B16, B15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, A18, B17, B16, B15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ A19, B18, B17, B16, B15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], [ B19, B18, B17, B16, B15, B14, B13, B12, B11, B10, B9, B8, B7, B6, B5, B4, B3, B2, B1, B0, ], ]; pub const LIFECYCLE_STATE_SIZE: usize = 40; pub const LIFECYCLE_COUNT_SIZE: usize = 48; pub const LIFECYCLE_MEM_SIZE: usize = LIFECYCLE_STATE_SIZE + LIFECYCLE_COUNT_SIZE; /// Generate the OTP memory contents associated with the lifecycle state. pub fn lc_generate_state_mem( state: LifecycleControllerState, ) -> Result<[u8; LIFECYCLE_STATE_SIZE]> { let state = u8::from(state); if state >= STATES.len() as u8 { bail!("Invalid lifecycle state: {:?}", state); } let mut result = [0u8; 40]; let state_data = STATES[state as usize]; for (i, &value) in state_data.iter().enumerate() { result[i * 2] = (value >> 8) as u8; result[i * 2 + 1] = (value & 0xFF) as u8; } Ok(result) } /// Generate the OTP memory contents associated with the lifecycle transition count. pub fn lc_generate_count_mem(count: u8) -> Result<[u8; LIFECYCLE_COUNT_SIZE]> { if count >= COUNTS.len() as u8 { bail!("Invalid lifecycle count: {:?}", count); } let mut result = [0u8; 48]; let count_data = COUNTS[count as usize]; for (i, &value) in count_data.iter().enumerate() { result[i * 2] = (value >> 8) as u8; result[i * 2 + 1] = (value & 0xFF) as u8; } Ok(result) } /// Generate the OTP memory contents associated with the lifecycle state and transition count. pub fn lc_generate_memory( state: LifecycleControllerState, transition_count: u8, ) -> Result<[u8; LIFECYCLE_MEM_SIZE]> { let mut result = [0u8; LIFECYCLE_MEM_SIZE]; let state = lc_generate_state_mem(state)?; result[..state.len()].copy_from_slice(&state); let count = lc_generate_count_mem(transition_count)?; result[state.len()..state.len() + count.len()].copy_from_slice(&count); result.reverse(); Ok(result) } /// Hash a token using cSHAKE128 for the lifecycle controller. fn hash_token(raw_token: &[u8; 16]) -> [u8; 16] { let mut hasher: CShake128 = CShake128::from_core(CShake128Core::new(b"LC_CTRL")); hasher.update(raw_token); let mut output = [0u8; 16]; hasher.finalize_xof_into(&mut output); output } fn hash_manuf_debug_token(raw_token: &[u8; 32]) -> [u8; 64] { let mut hasher: Sha512 = Sha512::new(); sha2::Digest::update(&mut hasher, raw_token); let output: [u8; 64] = hasher.finalize().into(); output } pub const DIGEST_SIZE: usize = 8; // TODO(timothytrippel): autogenerate these from the OTP memory map definition // OTP partition sizes. // Partition sizes are in bytes and include the digest and zeroization fields. const OTP_SECRET_LC_TRANSITION_PARTITION_SIZE: usize = 184; const OTP_SW_TEST_UNLOCK_PARTITION_SIZE: usize = 72; const OTP_SW_MANUF_PARTITION_SIZE: usize = 520; // Default from caliptra-ss/src/fuse_ctrl/rtl/otp_ctrl_part_pkg.sv const OTP_IV: u64 = 0x90C7F21F6224F027; const OTP_CNST: u128 = 0xF98C48B1F93772844A22D4B78FE0266F; // These are in reverse order from the RTL. pub(crate) const OTP_SCRAMBLE_KEYS: [u128; 7] = [ 0x3BA121C5E097DDEB7768B4C666E9C3DA, 0xEFFA6D736C5EFF49AE7B70F9C46E5A62, 0x85A9E830BC059BA9286D6E2856A05CC3, 0xBEAD91D5FA4E09150E95F517CB98955B, 0x4D5A89AA9109294AE048B657396B4B83, 0x277195FC471E4B26B6641214B61D1B43, 0xB7474D640F8A7F5D60822E1FAEC5C72, ]; const LC_TOKENS_KEY_IDX: usize = 6; fn otp_scramble_data(data: &mut [u8], key_idx: usize) -> Result<()> { if data.len() % 8 != 0 { bail!("Data length must be a multiple of 8 bytes for scrambling"); } if key_idx >= OTP_SCRAMBLE_KEYS.len() { bail!("Invalid key index for OTP scrambling"); } for chunk in data.chunks_exact_mut(8) { let input = u64::from_le_bytes(chunk.try_into().unwrap()); let output = otp_scramble(input, OTP_SCRAMBLE_KEYS[key_idx]); chunk.copy_from_slice(&output.to_le_bytes()); } Ok(()) } #[allow(unused)] fn otp_unscramble_data(data: &mut [u8], key_idx: usize) -> Result<()> { if data.len() % 8 != 0 { bail!("Data length must be a multiple of 8 bytes for scrambling"); } if key_idx >= OTP_SCRAMBLE_KEYS.len() { bail!("Invalid key index for OTP scrambling"); } for chunk in data.chunks_exact_mut(8) { let input = u64::from_le_bytes(chunk.try_into().unwrap()); let output = otp_unscramble(input, OTP_SCRAMBLE_KEYS[key_idx]); chunk.copy_from_slice(&output.to_le_bytes()); } Ok(()) } /// Generate the OTP memory contents for lifecycle tokens partition (including the digest). pub fn otp_generate_lifecycle_tokens_mem( tokens: &LifecycleRawTokens, ) -> Result<[u8; OTP_SECRET_LC_TRANSITION_PARTITION_SIZE]> { let mut output = [0u8; OTP_SECRET_LC_TRANSITION_PARTITION_SIZE]; for (i, token) in tokens.test_unlock.iter().enumerate() { let hashed_token = hash_token(&token.0); output[i * 16..(i + 1) * 16].copy_from_slice(&hashed_token); } output[7 * 16..8 * 16].copy_from_slice(&hash_token(&tokens.manuf.0)); output[8 * 16..9 * 16].copy_from_slice(&hash_token(&tokens.manuf_to_prod.0)); output[9 * 16..10 * 16].copy_from_slice(&hash_token(&tokens.prod_to_prod_end.0)); output[10 * 16..11 * 16].copy_from_slice(&hash_token(&tokens.rma.0)); otp_scramble_data( &mut output[..OTP_SECRET_LC_TRANSITION_PARTITION_SIZE - DIGEST_SIZE], LC_TOKENS_KEY_IDX, )?; let digest = otp_digest( &output[..OTP_SECRET_LC_TRANSITION_PARTITION_SIZE - DIGEST_SIZE], OTP_IV, OTP_CNST, ); output[OTP_SECRET_LC_TRANSITION_PARTITION_SIZE - DIGEST_SIZE..] .copy_from_slice(&digest.to_le_bytes()); Ok(output) } /// Generate the OTP memory contents for the manuf debug unlock token partition (including the digest). pub fn otp_generate_manuf_debug_unlock_token_mem( token: &ManufDebugUnlockToken, ) -> Result<[u8; OTP_SW_TEST_UNLOCK_PARTITION_SIZE]> { let mut output = [0u8; OTP_SW_TEST_UNLOCK_PARTITION_SIZE]; let mut hash = hash_manuf_debug_token(&<[u8; 32]>::from(*token)); // Reverse the byte order before setting in OTP so the token is read properly by the HW. let mut i = 0; for chunk in hash.chunks_exact_mut(4) { let word = u32::from_be_bytes(chunk.try_into().unwrap()); output[i..i + 4].copy_from_slice(&word.to_le_bytes()); i += 4; } let digest = otp_digest( &output[..OTP_SW_TEST_UNLOCK_PARTITION_SIZE - DIGEST_SIZE], OTP_IV, OTP_CNST, ); output[OTP_SW_TEST_UNLOCK_PARTITION_SIZE - DIGEST_SIZE..] .copy_from_slice(&digest.to_le_bytes()); Ok(output) } // TODO(timothytrippel): autogenerate these field sizes from the OTP memory map. #[derive(Debug, FromBytes, KnownLayout)] pub struct OtpSwManufPartition { pub anti_rollback_disable: u32, pub idevid_cert_attr: [u8; 96], pub idevid_cert: u32, pub hsm_id: u128, pub stepping_id: u32, pub prod_debug_unlock_pks_0: [u8; 48], pub prod_debug_unlock_pks_1: [u8; 48], pub prod_debug_unlock_pks_2: [u8; 48], pub prod_debug_unlock_pks_3: [u8; 48], pub prod_debug_unlock_pks_4: [u8; 48], pub prod_debug_unlock_pks_5: [u8; 48], pub prod_debug_unlock_pks_6: [u8; 48], pub prod_debug_unlock_pks_7: [u8; 48], } impl Default for OtpSwManufPartition { fn default() -> Self { // Compute the SHA2-384 hash of the default ECDSA and ML-DSA public keys. let mut ecdsa_pubkey = [0u32; 24]; ecdsa_pubkey[..12].copy_from_slice(&VENDOR_ECC_KEY_0_PUBLIC.x); ecdsa_pubkey[12..].copy_from_slice(&VENDOR_ECC_KEY_0_PUBLIC.y); let mut hasher = Sha384::new(); sha2::Digest::update(&mut hasher, ecdsa_pubkey.as_bytes()); sha2::Digest::update(&mut hasher, VENDOR_MLDSA_KEY_0_PUBLIC.0.as_bytes()); // Reverse bytes in each words so it matches the hash the ROM computes. let mut default_prod_debug_unlock_pks: [u8; 48] = hasher.finalize().into(); for chunk in default_prod_debug_unlock_pks.chunks_mut(4) { chunk.reverse(); } Self { anti_rollback_disable: 0x1, idevid_cert_attr: [0; 96], idevid_cert: 0, hsm_id: 0, stepping_id: 0, prod_debug_unlock_pks_0: default_prod_debug_unlock_pks, prod_debug_unlock_pks_1: default_prod_debug_unlock_pks, prod_debug_unlock_pks_2: default_prod_debug_unlock_pks, prod_debug_unlock_pks_3: default_prod_debug_unlock_pks, prod_debug_unlock_pks_4: default_prod_debug_unlock_pks, prod_debug_unlock_pks_5: default_prod_debug_unlock_pks, prod_debug_unlock_pks_6: default_prod_debug_unlock_pks, prod_debug_unlock_pks_7: default_prod_debug_unlock_pks, } } } /// Generate the OTP memory contents for the SW_MANUF partition, including the digest. pub fn otp_generate_sw_manuf_partition_mem( sw_manuf_partition: &OtpSwManufPartition, ) -> Result<[u8; OTP_SW_MANUF_PARTITION_SIZE]> { let mut output = [0u8; OTP_SW_MANUF_PARTITION_SIZE]; let mut offset = 0; let out = &mut output; let off = &mut offset; fn push(out_buf: &mut [u8], out_offset: &mut usize, src_buf: &[u8]) { let len = src_buf.len(); out_buf[*out_offset..*out_offset + len].copy_from_slice(src_buf); *out_offset += len; } // Anti-Rollback Disable field. push( out, off, &sw_manuf_partition.anti_rollback_disable.to_le_bytes(), ); // IDevID Cert Attributes field. push(out, off, &sw_manuf_partition.idevid_cert_attr); // IDevID Cert field. push(out, off, &sw_manuf_partition.idevid_cert.to_le_bytes()); // HSM ID field. push(out, off, &sw_manuf_partition.hsm_id.to_le_bytes()); // Stepping ID field. push(out, off, &sw_manuf_partition.stepping_id.to_le_bytes()); // Prod debug unlock public key hash fields. push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_0); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_1); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_2); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_3); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_4); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_5); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_6); push(out, off, &sw_manuf_partition.prod_debug_unlock_pks_7); // Compute and write digest field to lock the partition. let digest = otp_digest( &output[..OTP_SW_MANUF_PARTITION_SIZE - DIGEST_SIZE], OTP_IV, OTP_CNST, ); output[OTP_SW_MANUF_PARTITION_SIZE - DIGEST_SIZE..].copy_from_slice(&digest.to_le_bytes()); Ok(output) } #[cfg(test)] mod tests { use super::*; #[test] fn test_otp_unscramble_token() { let raw_token = LifecycleToken(0x05edb8c608fcc830de181732cfd65e57u128.to_le_bytes()); let tokens = LifecycleRawTokens { test_unlock: [raw_token; 7], manuf: raw_token, manuf_to_prod: raw_token, prod_to_prod_end: raw_token, rma: raw_token, }; let mut memory = otp_generate_lifecycle_tokens_mem(&tokens).unwrap(); otp_unscramble_data(&mut memory[..16], LC_TOKENS_KEY_IDX).unwrap(); let expected_hashed_token: [u8; 16] = 0x9c5f6f5060437af930d06d56630a536bu128.to_le_bytes(); assert_eq!(&memory[..16], &expected_hashed_token); } #[test] fn test_otp_generate_lifecycle_tokens_mem() { let raw_token = LifecycleToken(0x05edb8c608fcc830de181732cfd65e57u128.to_le_bytes()); let tokens = LifecycleRawTokens { test_unlock: [raw_token; 7], manuf: raw_token, manuf_to_prod: raw_token, prod_to_prod_end: raw_token, rma: raw_token, }; let memory = otp_generate_lifecycle_tokens_mem(&tokens).unwrap(); let expected: [u8; 184] = [ 0x16, 0x84, 0x0d, 0x3c, 0x82, 0x1b, 0x86, 0xae, 0xbc, 0x27, 0x8d, 0xe1, 0xf1, 0x4c,
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/otp_digest.rs
hw-model/src/otp_digest.rs
// Licensed under the Apache-2.0 license. // Copyright lowRISC contributors (OpenTitan project). #![allow(dead_code)] use core::convert::TryInto; // This section is converted from the OpenTitan project's Python implementation of OTP digest algorithm. /// Scramble a 64bit block with PRESENT cipher. fn present_64bit_encrypt(plain: u64, key: u128) -> u64 { // Make sure data is within 64bit range Present::new_128(&key.to_le_bytes()).encrypt_block(plain) } pub fn otp_scramble(data: u64, key: u128) -> u64 { Present::new_128(&key.to_le_bytes()).encrypt_block(data) } pub fn otp_unscramble(data: u64, key: u128) -> u64 { Present::new_128(&key.to_le_bytes()).decrypt_block(data) } pub fn otp_digest(data: &[u8], iv: u64, cnst: u128) -> u64 { assert_eq!(data.len() % 8, 0); let data_blocks = data .chunks_exact(8) .map(|chunk| u64::from_le_bytes(chunk.try_into().unwrap())) .collect::<Vec<u64>>(); otp_digest64(&data_blocks, iv, cnst) } /// Compute digest over multiple 64bit data blocks. fn otp_digest64(data_blocks: &[u64], iv: u64, cnst: u128) -> u64 { // Make a deepcopy since we're going to modify and pad the list. let mut data_blocks = Vec::from(data_blocks); // We need to align the number of data blocks to 2x64bit // for the digest to work properly. if data_blocks.len() % 2 == 1 { data_blocks.push(data_blocks[data_blocks.len() - 1]); } // Append finalization constant. data_blocks.push((cnst & 0xFFFF_FFFF_FFFF_FFFF) as u64); data_blocks.push(((cnst >> 64) & 0xFFFF_FFFF_FFFF_FFFF) as u64); // This computes a digest according to a Merkle-Damgard construction // that uses the Davies-Meyer scheme to turn the PRESENT cipher into // a one-way compression function. Digest finalization consists of // a final digest round with a 128bit constant. // See also: https://docs.opentitan.org/hw/ip/otp_ctrl/doc/index.html#scrambling-datapath let mut state = iv; let mut last_b64 = None; for b64 in data_blocks.iter() { match last_b64 { None => { last_b64 = Some(*b64); continue; } Some(last) => { let b128 = last as u128 + ((*b64 as u128) << 64); state ^= present_64bit_encrypt(state, b128); last_b64 = None; } } } assert!(last_b64.is_none()); state } /// PRESENT block cipher. /// /// Based on version 1.2 of the following Python implementation /// <https://github.com/doegox/python-cryptoplus> pub(crate) struct Present { round_keys: Vec<u64>, } pub(crate) type PresentErr = String; #[allow(dead_code)] impl Present { pub fn try_new_rounds(key: Vec<u8>, rounds: usize) -> Result<Present, PresentErr> { if !(1..=254).contains(&rounds) { Err(format!("unsupported number of rounds {}", rounds))?; } let round_keys = match key.len() { 10 => generate_round_keys_80(key, rounds), 16 => generate_round_keys_128(key, rounds), _ => Err("key length must be 80 or 128 bits")?, }; Ok(Present { round_keys }) } /// Create a new instance of the PRESENT cipher. /// /// Valid key lengths are 80 and 128 bits. All other key lengths will return an error. pub(crate) fn try_new(key: Vec<u8>) -> Result<Present, PresentErr> { Self::try_new_rounds(key, 32) } /// Create a new 128-bit PRESENT cipher instance. pub(crate) fn new_128(key: &[u8; 16]) -> Present { Self::try_new(key.to_vec()).unwrap() } /// Create a new 80-bit PRESENT cipher instance. pub(crate) fn new_80(key: &[u8; 10]) -> Present { Self::try_new(key.to_vec()).unwrap() } /// Encrypt a 64-bit block. pub(crate) fn encrypt_block(&self, block: u64) -> u64 { let mut state = block; state ^= self.round_keys[0]; for round_key in &self.round_keys[1..] { state = s_box_layer(state); state = p_box_layer(state); state ^= round_key; } state } /// Decrypt a 64-bit block. pub(crate) fn decrypt_block(&self, block: u64) -> u64 { let mut state = block; for round_key in self.round_keys[1..].iter().rev() { state ^= round_key; state = p_box_layer_dec(state); state = s_box_layer_dec(state); } state ^ self.round_keys[0] } } const S_BOX: [u8; 16] = [ 0x0c, 0x05, 0x06, 0x0b, 0x09, 0x00, 0x0a, 0x0d, 0x03, 0x0e, 0x0f, 0x08, 0x04, 0x07, 0x01, 0x02, ]; const S_BOX_INV: [u8; 16] = [ 0x05, 0x0e, 0x0f, 0x08, 0x0c, 0x01, 0x02, 0x0d, 0x0b, 0x04, 0x06, 0x03, 0x00, 0x07, 0x09, 0x0a, ]; const P_BOX: [u8; 64] = [ 0x00, 0x10, 0x20, 0x30, 0x01, 0x11, 0x21, 0x31, 0x02, 0x12, 0x22, 0x32, 0x03, 0x13, 0x23, 0x33, 0x04, 0x14, 0x24, 0x34, 0x05, 0x15, 0x25, 0x35, 0x06, 0x16, 0x26, 0x36, 0x07, 0x17, 0x27, 0x37, 0x08, 0x18, 0x28, 0x38, 0x09, 0x19, 0x29, 0x39, 0x0a, 0x1a, 0x2a, 0x3a, 0x0b, 0x1b, 0x2b, 0x3b, 0x0c, 0x1c, 0x2c, 0x3c, 0x0d, 0x1d, 0x2d, 0x3d, 0x0e, 0x1e, 0x2e, 0x3e, 0x0f, 0x1f, 0x2f, 0x3f, ]; const P_BOX_INV: [u8; 64] = [ 0x00, 0x04, 0x08, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x28, 0x2c, 0x30, 0x34, 0x38, 0x3c, 0x01, 0x05, 0x09, 0x0d, 0x11, 0x15, 0x19, 0x1d, 0x21, 0x25, 0x29, 0x2d, 0x31, 0x35, 0x39, 0x3d, 0x02, 0x06, 0x0a, 0x0e, 0x12, 0x16, 0x1a, 0x1e, 0x22, 0x26, 0x2a, 0x2e, 0x32, 0x36, 0x3a, 0x3e, 0x03, 0x07, 0x0b, 0x0f, 0x13, 0x17, 0x1b, 0x1f, 0x23, 0x27, 0x2b, 0x2f, 0x33, 0x37, 0x3b, 0x3f, ]; /// Generate the round_keys for an 80-bit key. fn generate_round_keys_80(key: Vec<u8>, rounds: usize) -> Vec<u64> { // Pad out key so it fits in a u128 later. let mut orig_key = key; let mut key = vec![0u8; 6]; key.append(&mut orig_key); // Convert key into a u128 for easier bit manipulation. let key: &[u8; 16] = key.as_slice().try_into().unwrap(); let mut key = u128::from_le_bytes(*key); let mut round_keys = Vec::new(); for i in 1..rounds + 1 { // rawKey[0:64] let round_key = (key >> 16) as u64; // 1. Rotate bits // rawKey[19:len(rawKey)]+rawKey[0:19] key = ((key & 0x7ffff) << 61) | (key >> 19); // 2. SBox // rawKey[76:80] = S(rawKey[76:80]) key = ((S_BOX[(key >> 76) as usize] as u128) << 76) | (key & (!0u128 >> (128 - 76))); // 3. Salt // rawKey[15:20] ^ i key ^= (i as u128) << 15; round_keys.push(round_key); } round_keys } /// Generate the round_keys for a 128-bit key. fn generate_round_keys_128(key: Vec<u8>, rounds: usize) -> Vec<u64> { let mut round_keys = Vec::new(); // Convert key into a u128 for easier bit manipulation. let key: &[u8; 16] = key.as_slice().try_into().unwrap(); let mut key = u128::from_le_bytes(*key); for i in 1..rounds + 1 { // rawKey[0:64] let round_key = (key >> 64) as u64; // 1. Rotate bits key = key.rotate_left(61); // 2. SBox key = ((S_BOX[(key >> 124) as usize] as u128) << 124) | ((S_BOX[((key >> 120) & 0xF) as usize] as u128) << 120) | (key & (!0u128 >> 8)); // 3. Salt // rawKey[62:67] ^ i key ^= (i as u128) << 62; round_keys.push(round_key); } round_keys } /// SBox funciton for encryption. fn s_box_layer(state: u64) -> u64 { let mut output: u64 = 0; for i in (0..64).step_by(4) { output |= (S_BOX[((state >> i) & 0x0f) as usize] as u64) << i; } output } #[allow(dead_code)] /// SBox inverse function for decryption. fn s_box_layer_dec(state: u64) -> u64 { let mut output: u64 = 0; for i in (0..64).step_by(4) { output |= (S_BOX_INV[((state >> i) & 0x0f) as usize] as u64) << i; } output } /// PBox function for encryption. fn p_box_layer(state: u64) -> u64 { let mut output: u64 = 0; for (i, v) in P_BOX.iter().enumerate() { output |= ((state >> i) & 0x01) << v; } output } #[allow(dead_code)] /// PBox inverse function for decryption. fn p_box_layer_dec(state: u64) -> u64 { let mut output: u64 = 0; for (i, v) in P_BOX_INV.iter().enumerate() { output |= ((state >> i) & 0x01) << v; } output } #[cfg(test)] mod test { use super::*; #[rustfmt::skip] const ROUND_KEYS_80: [u64; 32] = [ 0x0000000000000000, 0xc000000000000000, 0x5000180000000001, 0x60000a0003000001, 0xb0000c0001400062, 0x900016000180002a, 0x0001920002c00033, 0xa000a0003240005b, 0xd000d4001400064c, 0x30017a001a800284, 0xe01926002f400355, 0xf00a1c0324c005ed, 0x800d5e014380649e, 0x4017b001abc02876, 0x71926802f600357f, 0x10a1ce324d005ec7, 0x20d5e21439c649a8, 0xc17b041abc428730, 0xc926b82f60835781, 0x6a1cd924d705ec19, 0xbd5e0d439b249aea, 0x07b077abc1a8736e, 0x426ba0f60ef5783e, 0x41cda84d741ec1d5, 0xf5e0e839b509ae8f, 0x2b075ebc1d0736ad, 0x86ba2560ebd783ad, 0x8cdab0d744ac1d77, 0x1e0eb19b561ae89b, 0xd075c3c1d6336acd, 0x8ba27a0eb8783ac9, 0x6dab31744f41d700, ]; #[rustfmt::skip] const ROUND_KEYS_128: [u64; 32] = [ 0x0000000000000000, 0xcc00000000000000, 0xc300000000000000, 0x5b30000000000000, 0x580c000000000001, 0x656cc00000000001, 0x6e60300000000001, 0xb595b30000000001, 0xbeb980c000000002, 0x96d656cc00000002, 0x9ffae60300000002, 0x065b595b30000002, 0x0f7feb980c000003, 0xac196d656cc00003, 0xa33dffae60300003, 0xd6b065b595b30003, 0xdf8cf7feb980c004, 0x3b5ac196d656cc04, 0x387e33dffae60304, 0xeced6b065b595b34, 0xe3e1f8cf7feb9809, 0x6bb3b5ac196d6569, 0xbb8f87e33dffae65, 0x80aeced6b065b590, 0xc1ee3e1f8cf7febf, 0x2602bb3b5ac196d0, 0xcb07b8f87e33dffc, 0x34980aeced6b065d, 0x8b2c1ee3e1f8cf78, 0x54d2602bb3b5ac1e, 0x4a2cb07b8f87e33a, 0x97534980aeced6b7, ]; #[test] fn test_generate_80() { let key = vec![0u8; 10]; let round_keys = generate_round_keys_80(key, 32); assert_eq!(round_keys, ROUND_KEYS_80); } #[test] fn test_generate_128() { let key = vec![0u8; 16]; let round_keys = generate_round_keys_128(key, 32); assert_eq!(round_keys, ROUND_KEYS_128); } #[test] fn test_enc_80() { let cipher = Present::try_new(vec![0; 10]).unwrap(); assert_eq!(cipher.encrypt_block(0), 0x5579c1387b228445); } #[test] fn test_dec_80() { let cipher = Present::try_new(vec![0; 10]).unwrap(); assert_eq!(cipher.decrypt_block(0x5579c1387b228445), 0); } #[test] fn test_enc_128() { let cipher = Present::try_new(vec![0; 16]).unwrap(); assert_eq!(cipher.encrypt_block(0), 0x96db702a2e6900af); assert_eq!(cipher.encrypt_block(!0), 0x3c6019e5e5edd563); let cipher = Present::try_new(vec![0xff; 16]).unwrap(); assert_eq!(cipher.encrypt_block(0), 0x13238c710272a5d8); assert_eq!(cipher.encrypt_block(!0), 0x628d9fbd4218e5b4); } #[test] fn test_dec_128() { let cipher = Present::try_new(vec![0; 16]).unwrap(); assert_eq!(cipher.decrypt_block(0x96db702a2e6900af), 0); assert_eq!(cipher.decrypt_block(0x3c6019e5e5edd563), !0); let cipher = Present::try_new(vec![0xff; 16]).unwrap(); assert_eq!(cipher.decrypt_block(0x13238c710272a5d8), 0); assert_eq!(cipher.decrypt_block(0x628d9fbd4218e5b4), !0); } #[test] fn test_matches_python_128_and_is_little_endian() { assert_eq!( present_64bit_encrypt(0x0123456789abcdef, 0x0123456789abcdef0123456789abcdefu128), 0xe9d28685e671dd6 ); } }
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/jtag.rs
hw-model/src/jtag.rs
// Licensed under the Apache-2.0 license #![allow(dead_code)] pub trait JtagAccessibleReg { fn byte_offset(&self) -> u32; /// Converts the register's byte offset into a word offset for use with DMI. fn word_offset(&self) -> u32 { const BYTES_PER_WORD: u32 = std::mem::size_of::<u32>() as u32; assert_eq!(self.byte_offset() % BYTES_PER_WORD, 0); self.byte_offset() / BYTES_PER_WORD } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u32)] pub enum DmReg { DmControl = 0x10, DmStatus = 0x11, } impl JtagAccessibleReg for DmReg { // The offsets above are word offsets. fn byte_offset(&self) -> u32 { *self as u32 * 4 } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u32)] pub enum CaliptraCoreReg { MboxDlen = 0x50, MboxDout = 0x51, MboxStatus = 0x52, BootStatus = 0x53, CptraHwErrrorEnc = 0x54, CptraFwErrorEnc = 0x55, SsUdsSeedBaseAddrL = 0x56, SsUdsSeedBaseAddrH = 0x57, HwFatalError = 0x58, FwFatalError = 0x59, HwNonFatalError = 0x5a, FwNonFatalError = 0x5b, CptraDbgManufServiceReg = 0x60, BootfsmGo = 0x61, MboxDin = 0x62, SsDebugIntent = 0x63, SsCaliptraBaseAddrL = 0x64, SsCaliptraBaseAddrH = 0x65, SsMciBaseAddrL = 0x66, SsMciBaseAddrH = 0x67, SsRecoveryIfcBaseAddrL = 0x68, SsRecoveryIfcBaseAddrH = 0x69, SsOtpFcBaseAddrL = 0x6A, SsOtpFcBaseAddrH = 0x6B, SsStrapGeneric0 = 0x6C, SsStrapGeneric1 = 0x6D, SsStrapGeneric2 = 0x6E, SsStrapGeneric3 = 0x6F, SsDbgManufServiceRegReq = 0x70, SsDbgManufServiceRegRsp = 0x71, SsDbgUnlockLevel0 = 0x72, SsDbgUnlockLevel1 = 0x73, SsStrapCaliptraDmaAxiUser = 0x74, MboxLock = 0x75, MboxCmd = 0x76, MboxExecute = 0x77, SsExternalStagingAreaBaseAddrL = 0x78, SsExternalStagingAreaBaseAddrH = 0x79, } impl JtagAccessibleReg for CaliptraCoreReg { // The offsets above are word offsets. fn byte_offset(&self) -> u32 { *self as u32 * 4 } }
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/bus_logger.rs
hw-model/src/bus_logger.rs
// Licensed under the Apache-2.0 license use std::{ cell::RefCell, fs::File, io::{BufWriter, Write}, path::Path, rc::Rc, }; use caliptra_emu_bus::{Bus, BusError}; use caliptra_emu_types::{RvAddr, RvData, RvSize}; #[derive(Clone)] pub struct LogFile(Rc<RefCell<BufWriter<File>>>); impl LogFile { pub fn open(path: &Path) -> std::io::Result<Self> { Ok(Self(Rc::new(RefCell::new(BufWriter::new(File::create( path, )?))))) } } impl Write for LogFile { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.0.borrow_mut().write(buf) } fn flush(&mut self) -> std::io::Result<()> { self.0.borrow_mut().flush() } } pub struct NullBus(); impl Bus for NullBus { fn read(&mut self, _size: RvSize, _addr: RvAddr) -> Result<RvData, caliptra_emu_bus::BusError> { Err(BusError::LoadAccessFault) } fn write( &mut self, _size: RvSize, _addr: RvAddr, _val: RvData, ) -> Result<(), caliptra_emu_bus::BusError> { Err(BusError::StoreAccessFault) } } pub struct BusLogger<TBus: Bus> { pub bus: TBus, pub log: Option<LogFile>, } impl<TBus: Bus> BusLogger<TBus> { pub fn new(bus: TBus) -> Self { Self { bus, log: None } } pub fn log_read( &mut self, bus_name: &str, size: RvSize, addr: RvAddr, result: Result<RvData, caliptra_emu_bus::BusError>, ) { if addr < 0x1000_0000 { // Don't care about memory return; } if let Some(log) = &mut self.log { let size = usize::from(size); match result { Ok(val) => { writeln!(log, "{bus_name} read{size} *0x{addr:08x} -> 0x{val:x}").unwrap() } Err(e) => { writeln!(log, "{bus_name} read{size} *0x{addr:08x} ***FAULT {e:?}").unwrap() } } } } pub fn log_write( &mut self, bus_name: &str, size: RvSize, addr: RvAddr, val: RvData, result: Result<(), caliptra_emu_bus::BusError>, ) { if addr < 0x1000_0000 { // Don't care about memory return; } if let Some(log) = &mut self.log { let size = usize::from(size); match result { Ok(()) => { writeln!(log, "{bus_name} write{size} *0x{addr:08x} <- 0x{val:x}").unwrap() } Err(e) => writeln!( log, "{bus_name} write{size} *0x{addr:08x} <- 0x{val:x} ***FAULT {e:?}" ) .unwrap(), } } } } impl<TBus: Bus> Bus for BusLogger<TBus> { fn read(&mut self, size: RvSize, addr: RvAddr) -> Result<RvData, caliptra_emu_bus::BusError> { let result = self.bus.read(size, addr); self.log_read("UC", size, addr, result); result } fn write( &mut self, size: RvSize, addr: RvAddr, val: RvData, ) -> Result<(), caliptra_emu_bus::BusError> { let result = self.bus.write(size, addr, val); self.log_write("UC", size, addr, val, result); result } fn poll(&mut self) { self.bus.poll(); } fn warm_reset(&mut self) { self.bus.warm_reset(); } fn update_reset(&mut self) { self.bus.update_reset(); } fn incoming_event(&mut self, event: Rc<caliptra_emu_bus::Event>) { self.bus.incoming_event(event); } fn register_outgoing_events( &mut self, sender: std::sync::mpsc::Sender<caliptra_emu_bus::Event>, ) { self.bus.register_outgoing_events(sender); } }
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/bmc.rs
hw-model/src/bmc.rs
// Licensed under the Apache-2.0 license #![allow(dead_code)] use crate::recovery; use caliptra_emu_bus::{Device, Event, EventData, RecoveryCommandCode}; use std::sync::mpsc; pub struct Bmc { events_to_caliptra: mpsc::Sender<Event>, events_from_caliptra: mpsc::Receiver<Event>, events_to_mcu: mpsc::Sender<Event>, events_from_mcu: mpsc::Receiver<Event>, /// Recovery state machine recovery_state_machine: recovery::StateMachine<recovery::Context>, } impl Bmc { pub fn new( events_to_caliptra: mpsc::Sender<Event>, events_from_caliptra: mpsc::Receiver<Event>, events_to_mcu: mpsc::Sender<Event>, events_from_mcu: mpsc::Receiver<Event>, ) -> Bmc { let recovery_context = recovery::Context::new(events_to_caliptra.clone()); Bmc { events_to_caliptra, events_from_caliptra, events_to_mcu, events_from_mcu, recovery_state_machine: recovery::StateMachine::new(recovery_context), } } pub fn push_recovery_image(&mut self, image: Vec<u8>) { self.recovery_state_machine .context_mut() .recovery_images .push(image); } /// Called once every clock cycle by the emulator so the BMC can do work pub fn step(&mut self) { let prev_state = *self.recovery_state_machine.state(); // process any incoming events while let Ok(event) = self.events_from_caliptra.try_recv() { match event.dest { Device::BMC => self.incoming_caliptra_event(event), // route to the MCU Device::MCU => { self.events_to_mcu.send(event).unwrap(); } Device::ExternalTestSram => { self.events_to_mcu.send(event).unwrap(); } _ => {} } } while let Ok(event) = self.events_from_mcu.try_recv() { match event.dest { Device::BMC => self.incoming_mcu_event(event), // route to the Caliptra core Device::CaliptraCore => self.events_to_caliptra.send(event).unwrap(), _ => {} } } self.recovery_step(); if prev_state != *self.recovery_state_machine.state() { println!( "[emulator bmc recovery] Recovery state transition: {:?} -> {:?}", prev_state, self.recovery_state_machine.state() ); } } /// Take any actions for the recovery interface. fn recovery_step(&mut self) { let state = *self.recovery_state_machine.state(); if state == recovery::States::Done { return; } if let Some(event) = recovery::state_to_read_request(state) { self.events_to_caliptra.send(event).unwrap(); } } pub fn incoming_mcu_event(&mut self, _event: Event) { // do nothing for now } // translate from Caliptra events to state machine events pub fn incoming_caliptra_event(&mut self, event: Event) { match &event.event { EventData::RecoveryBlockReadResponse { source_addr: _, target_addr: _, command_code, payload, } => match command_code { RecoveryCommandCode::ProtCap => { if payload.len() >= 15 { let msg2 = u32::from_le_bytes(payload[8..12].try_into().unwrap()); let prot_cap = msg2.into(); let _ = self .recovery_state_machine .process_event(recovery::Events::ProtCap(prot_cap)); } else { println!("Invalid ProtCap payload (should be at least 15 bytes); ignoring message"); } } RecoveryCommandCode::DeviceStatus => { if payload.len() >= 4 { let status0: u32 = u32::from_le_bytes(payload[0..4].try_into().unwrap()); let device_status = status0.into(); let _ = self .recovery_state_machine .process_event(recovery::Events::DeviceStatus(device_status)); } else { println!("Invalid DeviceStatus payload (should be at least 4 bytes); ignoring message"); } } RecoveryCommandCode::RecoveryStatus => { if payload.len() >= 2 { let status0: u16 = u16::from_le_bytes(payload[0..2].try_into().unwrap()); let recovery_status = (status0 as u32).into(); let _ = self .recovery_state_machine .process_event(recovery::Events::RecoveryStatus(recovery_status)); } else { println!("Invalid RecoveryStatus payload (should be at least 2 bytes); ignoring message"); } } _ => todo!(), }, _ => todo!(), } } }
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/output.rs
hw-model/src/output.rs
// Licensed under the Apache-2.0 license use std::fmt::Display; use std::io::LineWriter; use std::{ cell::{Cell, RefCell}, io::Write, rc::Rc, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ExitStatus { Passed, Failed, } struct OutputSinkImpl { exit_status: Cell<Option<ExitStatus>>, new_uart_output: Cell<String>, log_writer: RefCell<LineWriter<Box<dyn std::io::Write>>>, at_start_of_line: Cell<bool>, now: Cell<u64>, next_write_needs_time_prefix: Cell<bool>, char_buffer: Cell<PartialUtf8>, // it's faster to copy than to manage a RefCell } struct PrettyU64(u64); impl Display for PrettyU64 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { const RANKS: [u64; 7] = [ 1_000_000_000_000_000_000, 1_000_000_000_000_000, 1_000_000_000_000, 1_000_000_000, 1_000_000, 1_000, 1, ]; const PADDING_RANK: u64 = 1_000_000_000; let mut prev_numbers = false; for rank in RANKS { if (self.0 / rank) > 0 || rank == 1 { if prev_numbers { write!(f, "{:03}", (self.0 / rank) % 1000)?; } else if rank >= PADDING_RANK { write!(f, "{}", (self.0 / rank) % 1000)?; } else { write!(f, "{:>3}", (self.0 / rank) % 1000)?; } if rank > 1 { write!(f, ",")?; } prev_numbers = true; } else if rank < PADDING_RANK { write!(f, " ")?; } } Ok(()) } } #[cfg(test)] #[test] fn test_pretty_u64() { assert_eq!(PrettyU64(0).to_string(), " 0"); assert_eq!(PrettyU64(1).to_string(), " 1"); assert_eq!(PrettyU64(999).to_string(), " 999"); assert_eq!(PrettyU64(1_000).to_string(), " 1,000"); assert_eq!(PrettyU64(1_001).to_string(), " 1,001"); assert_eq!(PrettyU64(999_999).to_string(), " 999,999"); assert_eq!(PrettyU64(1_000_000).to_string(), " 1,000,000"); assert_eq!(PrettyU64(1_000_001).to_string(), " 1,000,001"); assert_eq!(PrettyU64(999_999_999).to_string(), "999,999,999"); assert_eq!(PrettyU64(1_999_999_999).to_string(), "1,999,999,999"); } #[derive(Clone, Copy)] struct PartialUtf8 { len: usize, buf: [u8; 4], } impl Default for PartialUtf8 { fn default() -> Self { Self::new() } } impl PartialUtf8 { fn new() -> Self { Self { len: 0, buf: [0; 4], } } fn push(&mut self, ch: u8) { self.buf[self.len] = ch; self.len += 1; } fn next(&mut self) -> Option<char> { if self.len == 0 { return None; } // check partial sequences for l in 1..=self.len { let v = &self.buf[..l]; // avoid extra borrow let ch = match std::str::from_utf8(v) { Ok(s) => s.chars().next(), _ => None, }; if let Some(ch) = ch { self.buf.copy_within(l..4, 0); self.len -= l; return Some(ch); } } if self.len == 4 { // Invalid UTF-8 sequence, just output one character and shift the rest down let ch = self.buf[0] as char; self.buf.copy_within(1..4, 0); self.len -= 1; Some(ch) } else { None } } } #[cfg(test)] mod test { use super::*; #[test] fn test_utf8_buffer() { let mut p = PartialUtf8::new(); p.push(0x20); assert!(p.next() == Some(' ')); assert!(p.next().is_none()); for ch in 0..0x7f { // all ASCII characters are single byte p.push(ch); assert!(p.next() == Some(ch as char)); assert!(p.next().is_none()); } // 2-byte UTF-8 character p.push(0xCE); assert_eq!(p.next(), None); p.push(0x92); assert_eq!(p.next(), Some('Β')); assert_eq!(p.next(), None); // 3-byte UTF-8 character p.push(0xEC); assert_eq!(p.next(), None); p.push(0x9C); assert_eq!(p.next(), None); p.push(0x84); assert_eq!(p.next(), Some('위')); assert_eq!(p.next(), None); // 4-byte UTF-8 character p.push(0xF0); assert_eq!(p.next(), None); p.push(0x90); assert_eq!(p.next(), None); p.push(0x8D); assert_eq!(p.next(), None); p.push(0x85); assert_eq!(p.next(), Some('𐍅')); assert_eq!(p.next(), None); // invalid UTF-8 sequence p.push(0xF0); assert_eq!(p.next(), None); p.push(0x20); assert_eq!(p.next(), None); p.push(0x21); assert_eq!(p.next(), None); p.push(0x22); assert_eq!(p.next(), Some(0xF0 as char)); assert_eq!(p.next(), Some(0x20 as char)); assert_eq!(p.next(), Some(0x21 as char)); assert_eq!(p.next(), Some(0x22 as char)); } } #[derive(Clone)] pub struct OutputSink(Rc<OutputSinkImpl>); impl OutputSink { pub fn set_now(&self, now: u64) { self.0.now.set(now); } pub fn now(&self) -> u64 { self.0.now.get() } fn push_char_valid(&self, ch: char) { const UART_LOG_PREFIX: &[u8] = b"UART: "; let mut s = self.0.new_uart_output.take(); s.push(ch); self.0.new_uart_output.set(s); let log_writer = &mut self.0.log_writer.borrow_mut(); if self.0.at_start_of_line.get() { log_writer.flush().unwrap(); write!(log_writer, "{} ", PrettyU64(self.0.now.get())).unwrap(); log_writer.write_all(UART_LOG_PREFIX).unwrap(); self.0.at_start_of_line.set(false); } let mut buffer = [0; 4]; let s = ch.encode_utf8(&mut buffer); log_writer.write_all(s.as_bytes()).unwrap(); if ch == '\n' { self.0.at_start_of_line.set(true); } } pub fn push_uart_char(&self, ch: u8) { const TESTCASE_FAILED: u8 = 0x01; const TESTCASE_PASSED: u8 = 0xff; match ch { TESTCASE_PASSED => { // This is the same string as printed by the verilog test-bench self.0 .log_writer .borrow_mut() .write_all(b"* TESTCASE PASSED\n") .unwrap(); self.0.exit_status.set(Some(ExitStatus::Passed)); } TESTCASE_FAILED => { // This is the same string as printed by the verilog test-bench self.0 .log_writer .borrow_mut() .write_all(b"* TESTCASE FAILED\n") .unwrap(); self.0.exit_status.set(Some(ExitStatus::Failed)); } 0x02..=0x7f => self.push_char_valid(ch as char), 0x80..=0xf4 => { let mut partial = self.0.char_buffer.take(); partial.push(ch); while let Some(c) = partial.next() { self.push_char_valid(c); } self.0.char_buffer.set(partial); } _ => { writeln!( self.0.log_writer.borrow_mut(), "Unknown generic load 0x{ch:02x}" ) .unwrap(); } } } } impl std::io::Write for &OutputSink { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let log_writer = &mut self.0.log_writer.borrow_mut(); // Write a time prefix in front of every line for line in buf.split_inclusive(|ch| *ch == b'\n') { if self.0.next_write_needs_time_prefix.get() { write!(log_writer, "{} ", PrettyU64(self.0.now.get())).unwrap(); self.0.next_write_needs_time_prefix.set(false); } log_writer.write_all(line)?; if line.ends_with(b"\n") { self.0.next_write_needs_time_prefix.set(true); } } Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { self.0.log_writer.borrow_mut().flush() } } pub struct Output { output: String, sink: OutputSink, search_term: Option<String>, search_pos: usize, // Position to start searching from search_matched: bool, } impl Output { pub fn new(log_writer: impl std::io::Write + 'static) -> Self { Self::new_internal(Box::new(log_writer)) } fn new_internal(log_writer: Box<dyn std::io::Write>) -> Self { Self { output: "".into(), sink: OutputSink(Rc::new(OutputSinkImpl { new_uart_output: Default::default(), log_writer: RefCell::new(LineWriter::new(log_writer)), exit_status: Cell::new(None), at_start_of_line: Cell::new(true), now: Cell::new(0), next_write_needs_time_prefix: Cell::new(true), char_buffer: Cell::new(PartialUtf8::new()), })), search_term: None, search_pos: 0, search_matched: false, } } pub fn sink(&self) -> &OutputSink { &self.sink } pub fn logger(&self) -> impl std::io::Write + '_ { &self.sink } /// Peek at all the output captured so far pub fn peek(&mut self) -> &str { self.process_new_data(); &self.output } /// Take at most `limit` characters from the output pub fn take(&mut self, limit: usize) -> String { self.process_new_data(); if self.output.len() <= limit { std::mem::take(&mut self.output) } else { let remaining = self.output[limit..].to_string(); let mut result = std::mem::replace(&mut self.output, remaining); result.truncate(limit); result } } fn process_new_data(&mut self) { let new_data = self.sink.0.new_uart_output.take(); let new_data_len = new_data.len(); if new_data_len == 0 { return; } if self.output.is_empty() { self.output = new_data; } else { self.output.push_str(&new_data); } if let Some(term) = &self.search_term { if !self.search_matched { self.search_matched = self.output[self.search_pos..].contains(term); self.search_pos = self.output.len().saturating_sub(term.len()); if self.search_matched { self.search_term = None; } } } } pub fn set_search_term(&mut self, search_term: &str) { self.process_new_data(); self.search_term = Some(search_term.to_string()); self.search_pos = self.output.len(); self.search_matched = false; } pub fn search_matched(&mut self) -> bool { self.process_new_data(); self.search_matched } /// Returns true if the caliptra microcontroller has signalled that it wants to exit /// (this only makes sense when running test cases on the microcontroller) pub fn exit_requested(&self) -> bool { self.exit_status().is_some() } pub fn exit_status(&self) -> Option<ExitStatus> { self.sink.0.exit_status.get() } } #[cfg(test)] mod tests { use std::io::Sink; use super::*; #[derive(Clone)] pub struct Log { log: Rc<RefCell<Vec<u8>>>, } impl Log { /// Construct an empty `Log`. pub fn new() -> Self { Self { log: Rc::new(RefCell::new(vec![])), } } fn into_string(self) -> String { String::from_utf8(self.log.take()).unwrap() } } impl Default for Log { fn default() -> Self { Self::new() } } impl std::io::Write for Log { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { std::io::Write::write(&mut *self.log.borrow_mut(), buf) } fn flush(&mut self) -> std::io::Result<()> { std::io::Write::flush(&mut *self.log.borrow_mut()) } } #[test] fn test_take() { let log = Log::new(); let mut out = Output::new(log.clone()); out.sink().set_now(0); out.sink().push_uart_char(b'h'); out.sink().set_now(1); out.sink().push_uart_char(b'i'); out.sink().push_uart_char(b'!'); out.sink().push_uart_char(0xe2); out.sink().push_uart_char(0x98); out.sink().push_uart_char(0x83); out.sink().push_uart_char(b'\n'); assert_eq!(&out.take(2), "hi"); assert_eq!(&out.take(10), "!☃\n"); assert_eq!(&out.take(10), ""); assert_eq!(log.into_string(), " 0 UART: hi!☃\n"); } #[test] fn test_peek() { let mut out = Output::new(Sink::default()); out.sink().push_uart_char(b'h'); out.sink().push_uart_char(b'i'); assert_eq!(out.peek(), "hi"); out.sink().push_uart_char(b'!'); assert_eq!(out.peek(), "hi!"); } #[test] fn test_passed() { let log = Log::new(); let mut out = Output::new(log.clone()); out.sink().set_now(1000); out.sink().push_uart_char(b'h'); out.sink().set_now(2000); out.sink().push_uart_char(b'i'); out.sink().push_uart_char(b'\n'); assert_eq!(&out.take(10), "hi\n"); out.sink().push_uart_char(0xff); assert_eq!(out.exit_status(), Some(ExitStatus::Passed)); assert_eq!(&out.take(10), ""); assert_eq!( log.into_string(), " 1,000 UART: hi\n* TESTCASE PASSED\n" ); } #[test] fn test_failed() { let log = Log::new(); let mut out = Output::new(log.clone()); out.sink().push_uart_char(b'h'); out.sink().push_uart_char(b'i'); out.sink().push_uart_char(b'\n'); out.sink().push_uart_char(0x01); assert_eq!(out.exit_status(), Some(ExitStatus::Failed)); assert_eq!(&out.take(10), "hi\n"); assert_eq!( log.into_string(), " 0 UART: hi\n* TESTCASE FAILED\n" ); } #[test] fn test_unknown_generic_load() { let log = Log::new(); let mut out = Output::new(log.clone()); out.sink().push_uart_char(0xf8); assert_eq!(&out.take(30), ""); assert_eq!(log.into_string(), "Unknown generic load 0xf8\n"); } #[test] fn test_search() { let mut out = Output::new(Log::new()); out.set_search_term("foobar"); assert!(!out.search_matched); for &ch in b"this is my foobar string!" { out.sink.push_uart_char(ch); } out.process_new_data(); assert!(out.search_matched); out.set_search_term("foobar"); out.process_new_data(); assert!(!out.search_matched); for &ch in b"hello world strin" { out.sink.push_uart_char(ch); } out.set_search_term("string"); for &ch in b"g no match" { out.sink.push_uart_char(ch); } out.process_new_data(); assert!(!out.search_matched); for &ch in b" matching string" { out.sink.push_uart_char(ch); } out.process_new_data(); assert!(out.search_matched); out.set_search_term("string"); assert!(!out.search_matched); } }
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/recovery.rs
hw-model/src/recovery.rs
// Licensed under the Apache-2.0 license use caliptra_emu_bus::{Device, Event, EventData, ReadWriteRegister, RecoveryCommandCode}; use caliptra_emu_periph::dma::recovery::RecoveryStatus; use smlang::statemachine; use std::sync::mpsc; use tock_registers::interfaces::Readable; use tock_registers::register_bitfields; statemachine! { derive_states: [Clone, Copy, Debug], transitions: { // syntax: CurrentState Event [guard] / action = NextState // start by reading ProtCap to see if the device supports recovery *ReadProtCap + ProtCap(ProtCapBlock) [check_device_status_support] = ReadDeviceStatus, ReadProtCap + ProtCap(ProtCapBlock) [check_no_device_status_support] = Done, // read the device status to see if it needs recovery ReadDeviceStatus + DeviceStatus(DeviceStatusBlock) [check_device_status_healthy] = Done, // if the device needs recovery, send the recovery control message ReadDeviceStatus + DeviceStatus(DeviceStatusBlock) [check_device_status_recovery] / send_recovery_control = WaitForRecoveryStatus, // send the requested recovery image WaitForRecoveryStatus + RecoveryStatus(RecoveryStatusBlock) [check_recovery_status_awaiting] / start_recovery = WaitForRecoveryPending, // activate the recovery image after it has been processed WaitForRecoveryPending + DeviceStatus(DeviceStatusBlock) [check_device_status_recovery_pending] / activate = Activate, // check if we need to send another recovery image (if awaiting image is set and running recovery) Activate + DeviceStatus(DeviceStatusBlock) [check_device_status_recovery] = WaitForRecoveryStatus, // Activate + DeviceStatus(DeviceStatusBlock) [check_device_status_recovery_running_recovery] // = ActivateCheckRecoveryStatus, // ActivateCheckRecoveryStatus + RecoveryStatus(RecoveryStatusBlock) [check_recovery_status_awaiting] // / start_recovery = WaitForRecoveryPending, } } // map states to the corresponding recovery read block we want to read pub(crate) fn state_to_read_request(state: States) -> Option<Event> { let command_code = match state { States::ReadProtCap => Some(RecoveryCommandCode::ProtCap), States::ReadDeviceStatus => Some(RecoveryCommandCode::DeviceStatus), States::WaitForRecoveryStatus => Some(RecoveryCommandCode::RecoveryStatus), States::WaitForRecoveryPending => Some(RecoveryCommandCode::DeviceStatus), States::Activate => Some(RecoveryCommandCode::DeviceStatus), //States::ActivateCheckRecoveryStatus => Some(RecoveryCommandCode::RecoveryStatus), _ => None, }; command_code.map(|command_code| { Event::new( Device::BMC, Device::CaliptraCore, EventData::RecoveryBlockReadRequest { source_addr: 0, target_addr: 0, command_code, }, ) }) } register_bitfields! [ u32, pub ProtCap2 [ AgentCapabilities OFFSET(16) NUMBITS(16) [ Identification = 1<<0, ForcedRecovery = 1<<1, MgmtReset = 1<<2, DeviceReset = 1<<3, DeviceStatus = 1<<4, RecoveryImageAccess = 1<<5, LocalCImageSupport = 1<<6, PushCImageSupport = 1<<7, InterfaceIsolation = 1<<8, HardwareStatus = 1<<9, VendorCommand = 1<<10, FlashlessBoot = 1<<11, FifoCmsSupport = 1<<12, // Other bits are reserved ], ], pub DeviceStatus [ Status OFFSET(0) NUMBITS(8) [ Pending = 0, Healthy = 1, Error = 2, RecoveryMode = 3, RecoveryPending = 4, RunnningRecoveryImage = 5, BootFailure = 0xe, FatalError = 0xf, // Other values reserved ], ProtocolError OFFSET(8) NUMBITS(8) [ NoError = 0, UnsupportedWriteCommand = 1, UnsupportedParameter = 2, LengthWriteError = 3, CrcError = 4, GeneralProtocolError = 0xff, // Other values reserved ], RecoveryReasonCode OFFSET(16) NUMBITS(16) [], ], ]; type ProtCapBlock = ReadWriteRegister<u32, ProtCap2::Register>; type DeviceStatusBlock = ReadWriteRegister<u32, DeviceStatus::Register>; type RecoveryStatusBlock = ReadWriteRegister<u32, RecoveryStatus::Register>; /// State machine extended variables. pub(crate) struct Context { events_to_caliptra: mpsc::Sender<Event>, pub(crate) recovery_images: Vec<Vec<u8>>, } impl Context { pub(crate) fn new(events_to_caliptra: mpsc::Sender<Event>) -> Context { Context { events_to_caliptra, recovery_images: vec![], } } } impl StateMachineContext for Context { /// Check that the the protcap supports device status fn check_device_status_support(&self, prot_cap: &ProtCapBlock) -> Result<bool, ()> { let agent_cap = prot_cap.reg.get(); Ok(ProtCap2::AgentCapabilities::DeviceStatus.any_matching_bits_set(agent_cap)) } /// Check that the the protcap does not support device status fn check_no_device_status_support(&self, prot_cap: &ProtCapBlock) -> Result<bool, ()> { let agent_cap = prot_cap.reg.get(); Ok(!ProtCap2::AgentCapabilities::DeviceStatus.any_matching_bits_set(agent_cap)) } /// Chjeck that the device status is healthy fn check_device_status_healthy(&self, status: &DeviceStatusBlock) -> Result<bool, ()> { let status = status.reg.read(DeviceStatus::Status); if status == DeviceStatus::Status::Healthy.value { Ok(true) } else { Ok(false) } } /// Check that the device status is recovery mode fn check_device_status_recovery(&self, status: &DeviceStatusBlock) -> Result<bool, ()> { let status = status.reg.read(DeviceStatus::Status); if status == DeviceStatus::Status::RecoveryMode.value { Ok(true) } else { Ok(false) } } /// Check that the recovery status is awaiting a recovery image fn check_recovery_status_awaiting(&self, status: &RecoveryStatusBlock) -> Result<bool, ()> { let recovery = status.reg.read(RecoveryStatus::DEVICE_RECOVERY); if recovery == RecoveryStatus::DEVICE_RECOVERY::AwaitingRecoveryImage.value { Ok(true) } else { Ok(false) } } /// Check that the device status is recovery pending fn check_device_status_recovery_pending(&self, status: &DeviceStatusBlock) -> Result<bool, ()> { let status = status.reg.read(DeviceStatus::Status); if status == DeviceStatus::Status::RecoveryPending.value { Ok(true) } else { Ok(false) } } fn send_recovery_control(&mut self, _status: DeviceStatusBlock) -> Result<(), ()> { self.events_to_caliptra .send(Event::new( Device::BMC, Device::CaliptraCore, EventData::RecoveryBlockWrite { source_addr: 0, target_addr: 0, command_code: RecoveryCommandCode::RecoveryCtrl, payload: vec![0, 0, 0], }, )) .unwrap(); Ok(()) } fn activate(&mut self, _: DeviceStatusBlock) -> Result<(), ()> { self.events_to_caliptra .send(Event::new( Device::BMC, Device::CaliptraCore, EventData::RecoveryBlockWrite { source_addr: 0, target_addr: 0, command_code: RecoveryCommandCode::RecoveryCtrl, payload: vec![0, 0, 0xf], // activate }, )) .unwrap(); Ok(()) } fn start_recovery(&mut self, status: RecoveryStatusBlock) -> Result<(), ()> { let idx = status.reg.read(RecoveryStatus::RECOVERY_IMAGE_INDEX); if idx as usize >= self.recovery_images.len() { println!( "[emulator bmc recovery] Invalid recovery image index {}", idx ); Err(()) } else { let image = &self.recovery_images[idx as usize]; println!("[emulator bmc recovery] Sending recovery image {}", idx); self.events_to_caliptra .send(Event::new( Device::BMC, Device::CaliptraCore, EventData::RecoveryImageAvailable { image_id: idx as u8, image: image.clone(), }, )) .unwrap(); Ok(()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_no_prot_cap() { let (tx, _) = mpsc::channel(); let context = Context::new(tx); let mut sm = StateMachine::new(context); assert_eq!(*sm.state(), States::ReadProtCap); // we will go straight to Done if the ProtCap isn't valid assert!(sm.process_event(Events::ProtCap(0u32.into())).is_ok()); assert_eq!(*sm.state(), States::Done); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false