Skip to content

Commit

Permalink
Prevent multiple initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
bugadani committed Nov 20, 2024
1 parent c310d05 commit c1f91d7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Target side implementation of the RTT (Real-Time Transfer) I/O protocol. RTT imp

## Platform support

To use the global `rprintln!` macro or the defmt implementation, a platform-specific [`critical-section`](https://github.com/rust-embedded/critical-section) implementation is needed for locking.
A platform-specific [`critical-section`](https://github.com/rust-embedded/critical-section) implementation is needed to use this library.

Output directly to a channel object with `write!` or the binary `write` method does not require locking and therefore does not need any platform-specific critical section.

Expand Down
15 changes: 15 additions & 0 deletions rtt-target/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ macro_rules! rtt_init {
} => {{
use core::mem::MaybeUninit;
use core::ptr;
use core::cell::Cell;
use $crate::UpChannel;
use $crate::DownChannel;
use $crate::rtt::*;
Expand All @@ -137,6 +138,20 @@ macro_rules! rtt_init {
#[export_name = "_SEGGER_RTT"]
pub static mut CONTROL_BLOCK: MaybeUninit<RttControlBlock> = MaybeUninit::uninit();

#[allow(unused)]
#[export_name = "rtt_init_must_not_be_called_multiple_times"]
fn rtt_init_must_not_be_called_multiple_times() { }

use ::rtt_target::export::critical_section;

static INITIALIZED: critical_section::Mutex<Cell<bool>> = critical_section::Mutex::new(Cell::new(false));
critical_section::with(|cs| {
if INITIALIZED.borrow(cs).get() {
panic!("rtt_init! must not be called multiple times");
}
INITIALIZED.borrow(cs).set(true);
});

unsafe {
ptr::write_bytes(CONTROL_BLOCK.as_mut_ptr(), 0, 1);

Expand Down
7 changes: 7 additions & 0 deletions rtt-target/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,3 +438,10 @@ impl Drop for TerminalWriter<'_> {
}
}
}

/// Used to reexport items for use in macros. Do not use directly.
/// Not covered by semver guarantees.
#[doc(hidden)]
pub mod export {
pub use critical_section;
}

0 comments on commit c1f91d7

Please sign in to comment.