#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
pub(crate) const EPK_SEG_NAME: &str = "epk";
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::{Mutex, MutexGuard, PoisonError};
use thiserror::Error;
mod mc_registry;
pub use mc_registry::McApplication;
pub use mc_registry::Registry;
mod a2l;
pub use a2l::McA2mlMode;
pub const XCP_104_AML: &str = include_str!("../XCP_104.aml");
mod mc_event;
pub use mc_event::McEvent;
pub use mc_event::McEventList;
mod mc_calseg;
pub use mc_calseg::McCalibrationSegment;
pub use mc_calseg::McCalibrationSegmentList;
mod mc_instance;
pub use mc_instance::McInstance;
pub use mc_instance::McInstanceList;
mod mc_typedef;
pub use mc_typedef::McTypeDef;
pub use mc_typedef::McTypeDefField;
pub use mc_typedef::McTypeDefList;
mod mc_support;
pub use mc_support::McObjectQualifier;
pub use mc_support::McObjectType;
pub use mc_support::McSupportData;
mod mc_type;
pub use mc_type::McDimType;
pub use mc_type::McValueType;
pub use mc_type::McValueTypeTrait;
mod mc_address;
pub use mc_address::McAddrMode;
pub use mc_address::McAddress;
mod mc_text;
pub use mc_text::McIdentifier;
pub use mc_text::McText;
mod mc_register_type;
pub use mc_register_type::McEnumType;
pub use mc_register_type::McRegisterContext;
pub use mc_register_type::McRegisterTarget;
pub use mc_register_type::McRegisterType;
pub use xcp_registry_derive::McRegisterEnum;
pub use xcp_registry_derive::McRegisterType;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum RegistryError {
#[error("io error")]
Io(#[from] std::io::Error),
#[error("registry error: duplicate symbol `{0}` ")]
Duplicate(String),
#[error("registry error: `{0}` not found")]
NotFound(String),
#[error("registry error: event id not defined `{0}` ")]
UnknownEventChannel(u16),
#[error("registry error: metadata already set for field `{0}`")]
MetadataAlreadySet(String),
#[error("registry error: index overflow")]
IndexOverflow,
#[error("registry error: object type of `{0}` is unspecified")]
ObjectTypeUnspecified(String),
#[error("A2L error: {0}")]
A2l(String),
#[error("unknown error")]
Unknown,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct McXcpTransportLayer {
pub protocol_name: &'static str,
pub addr: Option<Ipv4Addr>,
pub port: Option<u16>,
pub baud_rate: Option<u32>,
}
impl Default for McXcpTransportLayer {
fn default() -> Self {
McXcpTransportLayer {
protocol_name: "UDP",
addr: Some(Ipv4Addr::new(127, 0, 0, 1)),
port: Some(5555),
baud_rate: None,
}
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct McXcpProtocolLayer {
pub max_cto: u8,
pub max_dto: u16,
}
impl Default for McXcpProtocolLayer {
fn default() -> Self {
McXcpProtocolLayer { max_cto: 8, max_dto: 8 }
}
}
static REGISTRY: Mutex<Option<Registry>> = Mutex::new(None);
static CLOSED_REGISTRY: Mutex<Option<&'static Registry>> = Mutex::new(None);
fn lock<T>(m: &'static Mutex<T>) -> MutexGuard<'static, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn init() {
let mut l = lock(®ISTRY);
if l.is_none() {
*l = Some(Registry::new());
log::info!("Registry initialized");
} else {
log::info!("Registry already initialized");
}
}
#[derive(Debug)]
pub struct RegistryGuard(MutexGuard<'static, Option<Registry>>);
impl std::ops::Deref for RegistryGuard {
type Target = Option<Registry>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for RegistryGuard {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub fn get_lock() -> RegistryGuard {
#[cfg(not(test))]
if lock(&CLOSED_REGISTRY).is_some() {
let l = lock(®ISTRY);
assert!(l.is_none());
return RegistryGuard(l);
}
let l = lock(®ISTRY);
assert!(l.is_some(), "Registry not initialized!");
RegistryGuard(l)
}
pub fn get() -> &'static Registry {
if lock(&CLOSED_REGISTRY).is_none() {
log::warn!("Automatically close registry - call to Registry::get() without explictic close!");
close();
}
lock(&CLOSED_REGISTRY).unwrap()
}
pub fn is_closed() -> bool {
lock(&CLOSED_REGISTRY).is_some()
}
pub fn close() {
if is_closed() {
log::warn!("Mutable registry singleton already closed !");
return;
}
log::info!("Mutable registry singleton closed !");
let mut reg = get_lock().take().unwrap();
if reg.get_flatten_typedefs_mode() {
flatten_registry(&mut reg);
}
*lock(&CLOSED_REGISTRY) = Some(Box::leak(Box::new(reg)));
}
#[allow(clippy::too_many_arguments)]
fn expand_typedef_slot(
reg: &Registry,
new_instances: &mut McInstanceList,
typedef_index: &HashMap<&'static str, usize>,
base_name: &str,
root_instance_address: &McAddress,
base_offset: i32,
dim_type: &McDimType,
typedef: &McTypeDef,
) {
let [x_dim, y_dim] = dim_type.get_dim();
if x_dim <= 1 && y_dim <= 1 {
collect_flattened_instances(reg, new_instances, typedef_index, base_name.to_string(), root_instance_address, base_offset, typedef);
return;
}
let columns = x_dim.max(1);
let rows = y_dim.max(1);
let stride = i32::try_from(typedef.size).expect("Typedef size exceeds i32::MAX");
for iy in 0..rows {
for ix in 0..columns {
let element_index = iy as i32 * columns as i32 + ix as i32;
let element_offset = base_offset + element_index * stride;
let element_name = if y_dim > 1 {
format!("{}._{}_{}", base_name, iy, ix)
} else {
format!("{}._{}", base_name, ix)
};
collect_flattened_instances(reg, new_instances, typedef_index, element_name, root_instance_address, element_offset, typedef);
}
}
}
fn collect_flattened_instances(
reg: &Registry,
new_instances: &mut McInstanceList,
typedef_index: &HashMap<&'static str, usize>,
name: String,
root_instance_address: &McAddress,
root_address_offset: i32,
typedef: &McTypeDef,
) {
for field in &typedef.fields {
let mangled_name = format!("{}.{}", name, field.name);
if let Some(typedef_name) = field.get_typedef_name() {
let i = *typedef_index.get(typedef_name).unwrap();
let field_typedef = reg.typedef_list.get(i).unwrap();
expand_typedef_slot(
reg,
new_instances,
typedef_index,
&mangled_name,
root_instance_address,
root_address_offset + field.offset as i32,
&field.dim_type,
field_typedef,
);
} else {
let mut address = *root_instance_address;
address.add_addr_offset(root_address_offset + field.offset as i32);
let _ = new_instances.add_instance(mangled_name, field.dim_type.clone(), field.mc_support_data.clone(), address);
}
}
}
fn create_flattened_instance_list(reg: &mut Registry, typedef_index: &HashMap<&'static str, usize>) -> McInstanceList {
let mut flat_instance_list = McInstanceList::new();
for instance in ®.instance_list {
let name: String = instance.get_name().to_string();
if let Some(typedef_name) = instance.get_typedef_name() {
if let Some(i) = typedef_index.get(typedef_name) {
expand_typedef_slot(
reg,
&mut flat_instance_list,
typedef_index,
&name,
instance.get_address(),
0,
instance.get_dim_type(),
reg.typedef_list.get(*i).unwrap(),
);
} else {
log::error!("Typedef {} not found in typedef list", typedef_name);
}
} else {
let _ = flat_instance_list.add_instance(name, instance.dim_type.clone(), instance.get_mc_support_data().clone(), *instance.get_address());
}
}
flat_instance_list
}
pub fn flatten_registry(reg: &mut Registry) {
log::info!("Flattening typedef structure in registry into mangled instance names !");
let typedef_index: &HashMap<&str, usize> = ®
.typedef_list
.into_iter()
.enumerate()
.map(|(index, typedef)| (typedef.get_name(), index))
.collect::<std::collections::HashMap<_, _>>();
reg.instance_list = create_flattened_instance_list(reg, typedef_index);
reg.typedef_list.clear();
}
#[doc(hidden)]
pub mod registry_test {
use super::*;
pub fn test_reinit() {
*lock(®ISTRY) = Some(Registry::new());
*lock(&CLOSED_REGISTRY) = None;
}
}
#[cfg(test)]
mod flatten_tests {
use super::*;
fn offset_of(reg: &Registry, name: &str) -> i32 {
reg.instance_list
.get_instance(name, McObjectType::Characteristic, None)
.unwrap_or_else(|| panic!("flattened instance '{}' not found", name))
.get_address()
.get_addr_offset()
}
#[test]
fn flatten_array_of_structs() {
let mut reg = Registry::new();
let cal = McSupportData::new(McObjectType::Characteristic);
reg.add_typedef("Inner", 4).unwrap();
reg.add_typedef_field("Inner", "a", McDimType::new(McValueType::Ubyte, 1, 1), cal.clone(), 0).unwrap();
reg.add_typedef_field("Inner", "b", McDimType::new(McValueType::Uword, 1, 1), cal.clone(), 2).unwrap();
reg.add_typedef("Outer", 16).unwrap();
reg.add_typedef_field("Outer", "items", McDimType::new(McValueType::new_typedef("Inner"), 3, 1), cal.clone(), 0)
.unwrap();
reg.add_typedef_field("Outer", "count", McDimType::new(McValueType::Ulong, 1, 1), cal.clone(), 12).unwrap();
reg.instance_list
.add_instance(
"outer",
McDimType::new(McValueType::new_typedef("Outer"), 1, 1),
cal.clone(),
McAddress::new_calseg_rel("seg", 0x10),
)
.unwrap();
reg.instance_list
.add_instance(
"arr",
McDimType::new(McValueType::new_typedef("Inner"), 2, 1),
cal.clone(),
McAddress::new_calseg_rel("seg", 0x40),
)
.unwrap();
flatten_registry(&mut reg);
assert!(reg.typedef_list.is_empty(), "typedef list should be empty after flattening");
assert_eq!(offset_of(®, "outer.items._0.a"), 0x10);
assert_eq!(offset_of(®, "outer.items._0.b"), 0x12);
assert_eq!(offset_of(®, "outer.items._1.a"), 0x14);
assert_eq!(offset_of(®, "outer.items._1.b"), 0x16);
assert_eq!(offset_of(®, "outer.items._2.a"), 0x18);
assert_eq!(offset_of(®, "outer.items._2.b"), 0x1A);
assert_eq!(offset_of(®, "outer.count"), 0x1C);
assert_eq!(offset_of(®, "arr._0.a"), 0x40);
assert_eq!(offset_of(®, "arr._0.b"), 0x42);
assert_eq!(offset_of(®, "arr._1.a"), 0x44);
assert_eq!(offset_of(®, "arr._1.b"), 0x46);
assert_eq!(reg.instance_list.len(), 11);
}
}