Skip to content

Add signals with atomic usize #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
with:
use-cross: true
command: build
args: --target=${{ matrix.TARGET }}
args: --target=${{ matrix.TARGET }} --all-features

test:
name: Tests
Expand Down
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

## Unreleased

* [#23] - Add `strncasecmp`
* [#23] - Add `strncasecmp`
* [#21] - Add signal API

[#23]: https://github.com/rust-embedded-community/tinyrlibc/pull/21
[#21]: https://github.com/rust-embedded-community/tinyrlibc/pull/21

## v0.3.0 (2022-10-18)

Expand Down
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ readme = "README.md"
repository = "https://github.com/thejpster/tinyrlibc"

[dependencies]
portable-atomic = { version = "1.6.0", optional = true }

[dev-dependencies]
static-alloc = "0.2.4"
Expand Down Expand Up @@ -42,7 +43,6 @@ all = [
"isdigit",
"isalpha",
"isupper",
"alloc",
]
abs = []
strcmp = []
Expand All @@ -68,3 +68,5 @@ isdigit = []
isalpha = []
isupper = []
alloc = []
signal = ["dep:portable-atomic"]
signal-cs = ["portable-atomic/critical-section"]
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ This crate basically came about so that the [nrfxlib](https://github.com/NordicP
* calloc
* realloc
* free
* signal (optional)
* signal
* raise
* abort

## Non-standard helper functions

Expand Down
14 changes: 5 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ mod malloc;
#[cfg(feature = "alloc")]
pub use self::malloc::{calloc, free, malloc, realloc};

// A new global allocator is required for the tests, but not for the library itself.
// This is because the default alloc crate uses the system allocator, collides with
// the one in this crate, and causes a link error.
#[cfg(all(feature = "alloc", test))]
use static_alloc::Bump;
#[cfg(all(feature = "alloc", test))]
#[global_allocator]
static ALLOCATOR: Bump<[u8; 1024 * 1024]> = Bump::uninit();

mod itoa;
#[cfg(feature = "itoa")]
pub use self::itoa::itoa;
Expand Down Expand Up @@ -91,6 +82,11 @@ mod strchr;
#[cfg(feature = "strchr")]
pub use self::strchr::strchr;

#[cfg(feature = "signal")]
mod signal;
#[cfg(feature = "signal")]
pub use self::signal::{abort, raise, signal};

mod snprintf;

mod ctype;
Expand Down
8 changes: 4 additions & 4 deletions src/malloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const MAX_ALIGN: usize = 16;
/// Rust implementation of C library function `malloc`
///
/// See [malloc](https://linux.die.net/man/3/malloc) for alignment details.
#[no_mangle]
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "C" fn malloc(size: CSizeT) -> *mut u8 {
// size + MAX_ALIGN for to store the size of the allocated memory.
let layout = alloc::alloc::Layout::from_size_align(size + MAX_ALIGN, MAX_ALIGN).unwrap();
Expand All @@ -29,7 +29,7 @@ pub unsafe extern "C" fn malloc(size: CSizeT) -> *mut u8 {
/// Rust implementation of C library function `calloc`
///
/// See [calloc](https://linux.die.net/man/3/calloc) for alignment details.
#[no_mangle]
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "C" fn calloc(nmemb: CSizeT, size: CSizeT) -> *mut u8 {
let total_size = nmemb * size;
let layout = alloc::alloc::Layout::from_size_align(total_size + MAX_ALIGN, MAX_ALIGN).unwrap();
Expand All @@ -46,7 +46,7 @@ pub unsafe extern "C" fn calloc(nmemb: CSizeT, size: CSizeT) -> *mut u8 {
/// Rust implementation of C library function `realloc`
///
/// See [realloc](https://linux.die.net/man/3/realloc) for alignment details.
#[no_mangle]
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "C" fn realloc(ptr: *mut u8, size: CSizeT) -> *mut u8 {
if ptr.is_null() {
return malloc(size);
Expand All @@ -64,7 +64,7 @@ pub unsafe extern "C" fn realloc(ptr: *mut u8, size: CSizeT) -> *mut u8 {
}

/// Rust implementation of C library function `free`
#[no_mangle]
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "C" fn free(ptr: *mut u8) {
if ptr.is_null() {
return;
Expand Down
203 changes: 203 additions & 0 deletions src/signal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
//! Rust implementation of the C standard library's `signal` related functions.
//!
//! Copyright (c) Gyungmin Myung <gmmyung@kaist.ac.kr>
//! Licensed under the Blue Oak Model Licence 1.0.0

use core::{cell::RefCell, default};
use portable_atomic::{AtomicUsize, Ordering};

/// An initialiser for our array.
///
/// We turn off the clippy warning because it's wrong - and there's no other
/// way to initialise an array of atomics.
#[allow(clippy::declare_interior_mutable_const)]
const SIG_DFL_ATOMIC: AtomicUsize = AtomicUsize::new(SIG_DFL);

/// Our array of registered signal handlers.
///
/// Signals in C are either 0, 1, -1, or a function pointer. We cast function
/// pointers into `usize` so they can be stored in this array.
static SIGNAL_HANDLERS: [AtomicUsize; 16] = [SIG_DFL_ATOMIC; 16];

/// A signal handler - either a function pointer or a magic integer.
pub type SignalHandler = usize;

/// Indicates we should use the default signal handler
const SIG_DFL: usize = 0;

/// Indicates we should use the default signal handler
const SIG_IGN: usize = 1;

/// Indicates we should use the default signal handler
const SIG_ERR: usize = usize::MAX;

/// The TERM signal
const SIGTERM: i32 = 15;

/// The SEGV signal
const SIGSEGV: i32 = 11;

/// The INT signal
const SIGINT: i32 = 2;

/// The ILL signal
const SIGILL: i32 = 4;

/// The ABRT signal
const SIGABRT: i32 = 6;

/// The FPE signal
const SIGFPE: i32 = 8;

/// The list of support signals.
///
/// Only ANSI C signals are now supported.
///
/// SIGSEGV, SIGILL, SIGFPE are not supported on bare metal, but handlers are
/// invoked when raise() is called.
///
/// We will index `SIGNAL_HANDLERS` by any integer in this list, so ensure that
/// the array is made larger if required.
///
/// TODO: Support SIGSEGV, SIGILL, SIGFPE by using the `cortex-m-rt` or
/// `riscv-rt` crate.
const SIGNALS: [i32; 6] = [SIGTERM, SIGSEGV, SIGINT, SIGILL, SIGABRT, SIGFPE];

/// An empty handler function that does nothing
fn ignore_handler(_sig: i32) {}

/// The default handler functions
///
/// Performs a panic.
fn default_handler(_sig: i32) {
// TODO: This should call core::intrinsics::abort() but that's unstable.
panic!("Aborted");
}

/// Rust implementation of the C standard library's `signal` function.
///
/// Using `not(test)` ensures we don't replace the actual OS `signal` function
/// when running tests!
#[cfg_attr(all(not(test), feature = "signal"), no_mangle)]
pub unsafe extern "C" fn signal(sig: i32, handler: SignalHandler) -> SignalHandler {
if !SIGNALS.contains(&sig) {
return SIG_ERR;
}
SIGNAL_HANDLERS[sig as usize].swap(handler, Ordering::Relaxed)
}

/// Rust implementation of the C standard library's `raise` function.
///
/// Using `not(test)` ensures we don't replace the actual OS `raise` function
/// when running tests!
#[cfg_attr(all(not(test), feature = "signal"), no_mangle)]
pub extern "C" fn raise(sig: i32) -> i32 {
if !SIGNALS.contains(&sig) {
return -1;
}
let handler = SIGNAL_HANDLERS[sig as usize].load(Ordering::Relaxed);
match handler {
SIG_DFL => {
default_handler(sig);
}
SIG_IGN => {
ignore_handler(sig);
}
_ => unsafe {
let handler_fn: unsafe extern "C" fn(core::ffi::c_int) = core::mem::transmute(handler);
handler_fn(sig);
},
}
0
}

#[cfg_attr(all(not(test), feature = "signal"), no_mangle)]
pub extern "C" fn abort() {
raise(SIGABRT);
}

#[cfg(test)]
mod tests {
use super::*;

struct State {
inner: std::sync::Mutex<()>,
}

impl State {
fn lock(&self) -> std::sync::MutexGuard<()> {
// Ensure we have exclusive access
let guard = self.inner.lock().unwrap();
// Reset the global signal handler list to defaults
for sig in SIGNAL_HANDLERS.iter() {
sig.store(SIG_DFL, Ordering::SeqCst);
}
guard
}
}

/// Used to ensure we don't run multiple signal test concurrently, because
/// they share some global state.
///
/// If a test fails, the lock will be poisoned and all subsequent tests will
/// fail.
static TEST_LOCK: State = State {
inner: std::sync::Mutex::new(()),
};

#[test]
fn test_signal() {
let _guard = TEST_LOCK.lock();
static COUNT: AtomicUsize = AtomicUsize::new(0);
extern "C" fn count_handler(_sig: i32) {
COUNT.fetch_add(1, Ordering::Relaxed);
}
let count_handler_ptr = count_handler as *const fn(i32) as usize;
let old_handler = unsafe { signal(SIGTERM, count_handler_ptr) };
assert_eq!(old_handler, SIG_DFL);
(0..10).for_each(|_| {
raise(SIGTERM);
});
let old_handler = unsafe { signal(SIGTERM, SIG_DFL) };
assert_eq!(COUNT.load(Ordering::Relaxed), 10);
assert_eq!(old_handler, count_handler_ptr);
}

#[test]
fn test_abort() {
let _guard = TEST_LOCK.lock();
let result = std::panic::catch_unwind(|| {
abort();
});
assert!(result.is_err());
}

#[test]
fn test_signal_error() {
let _guard = TEST_LOCK.lock();
let err = unsafe { signal(1000, SIG_DFL) };
assert_eq!(err, SIG_ERR);
}

#[test]
fn test_raise() {
let result = std::panic::catch_unwind(|| raise(SIGTERM));
assert!(result.is_err());
}

#[test]
fn test_ignore() {
let _guard = TEST_LOCK.lock();
let old_handler = unsafe { signal(SIGTERM, SIG_IGN) };
assert_eq!(old_handler, SIG_DFL);
// Shouldn't cause a panic
raise(SIGTERM);
let old_handler = unsafe { signal(SIGTERM, SIG_DFL) };
assert_eq!(old_handler, SIG_IGN);
}

#[test]
fn test_raise_error() {
assert!(raise(1000) == -1);
}
}