Skip to content

Instantly share code, notes, and snippets.

@agrif
Created June 14, 2024 03:09
Show Gist options
  • Save agrif/f8abceb14d8345b38913f46aa48fdf49 to your computer and use it in GitHub Desktop.
Save agrif/f8abceb14d8345b38913f46aa48fdf49 to your computer and use it in GitHub Desktop.
#![no_std]
const CODE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dp32g030-hal-flash.bin"));
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HeaderFn<F>(*const core::marker::PhantomData<F>);
impl<F> HeaderFn<F> {
pub const fn from_addr(addr: usize) -> Self {
Self(addr as *const core::marker::PhantomData<F>)
}
pub fn as_addr(&self) -> usize {
self.0 as usize
}
}
#[cfg(all(target_arch = "arm", target_os = "none"))]
impl<F> HeaderFn<F> {
pub const unsafe fn from_fn_unchecked(ptr: *const ()) -> Self {
Self(ptr as *const core::marker::PhantomData<F>)
}
pub const unsafe fn check(self, f: F) -> Self {
core::mem::forget(f);
self
}
pub unsafe fn as_fn(&self, offset: usize) -> F {
let p = (offset + self.as_addr()) as *const ();
core::mem::transmute_copy::<*const (), F>(&p)
}
}
#[cfg(all(target_arch = "arm", target_os = "none"))]
#[macro_export]
macro_rules! header_fn {
($x:expr) => {
unsafe { $crate::HeaderFn::from_fn_unchecked($x as *const ()).check($x) }
};
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Header {
pub entry: HeaderFn<extern "C" fn()>,
}
unsafe impl Sync for Header {}
impl Header {
const fn from_code() -> Self {
Self {
entry: HeaderFn::from_addr(Self::read_u32le(0) as usize),
}
}
const fn read_u32le(offset: usize) -> u32 {
CODE[offset] as u32
| ((CODE[offset + 1] as u32) << 8)
| ((CODE[offset + 2] as u32) << 16)
| ((CODE[offset + 3] as u32) << 24)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Code {
header: Header,
data: [u8; CODE.len()],
}
impl Code {
pub fn new() -> Self {
Self {
header: Header::from_code(),
data: CODE.try_into().unwrap(),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment