Skip to content

Commit

Permalink
Generate unique id for device peripherals
Browse files Browse the repository at this point in the history
  • Loading branch information
gephaistos committed Jul 23, 2024
1 parent f864c3e commit ed21f8f
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/generate/device.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::svd::{array::names, Device, Peripheral};
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::Ident;

use log::debug;
use std::fs::File;
Expand Down Expand Up @@ -270,12 +271,24 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
}
}

// Generate unique identifier to prevent linkage errors when using multiple devices.
let mut id = String::from("TAKEN_");
for ch in d.name.chars() {
if ch == ' ' || ch == '-' {
id.push('_');
} else {
id.extend(ch.to_uppercase());
}
}

let taken: Ident = syn::parse_str(&id)?;

out.extend(quote! {
// NOTE `no_mangle` is used here to prevent linking different minor versions of the device
// crate as that would let you `take` the device peripherals more than once (one per minor
// version)
#[no_mangle]
static mut DEVICE_PERIPHERALS: bool = false;
static mut #taken: bool = false;

/// All the peripherals.
#[allow(non_snake_case)]
Expand All @@ -290,12 +303,12 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
pub fn take() -> Option<Self> {
critical_section::with(|_| {
// SAFETY: We are in a critical section, so we have exclusive access
// to `DEVICE_PERIPHERALS`.
if unsafe { DEVICE_PERIPHERALS } {
// to `#taken`.
if unsafe { #taken } {
return None
}

// SAFETY: `DEVICE_PERIPHERALS` is set to `true` by `Peripherals::steal`,
// SAFETY: `#taken` is set to `true` by `Peripherals::steal`,
// ensuring the peripherals can only be returned once.
Some(unsafe { Peripherals::steal() })
})
Expand All @@ -308,7 +321,7 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
/// Each of the returned peripherals must be used at most once.
#[inline]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
#taken = true;

Peripherals {
#exprs
Expand Down

0 comments on commit ed21f8f

Please sign in to comment.