Skip to content

Commit

Permalink
rust: make Lock trait unsafe.
Browse files Browse the repository at this point in the history
Without this, one could implement a lock that doesn't really provide
mutual exclusion, which could result in UB. For example, a no-op `Lock`
implementation could provide guards from two different threads
concurrently, which could be used by `LockedBy` to generate two mutable
references to the same underlying object.

Marking `Lock` unsafe has no implication on driver code because all
implementations are expected to come from the `kernel` crate anyway.

Signed-off-by: Wedson Almeida Filho <[email protected]>
  • Loading branch information
wedsonaf committed Oct 15, 2021
1 parent 6d76783 commit 2c1e84a
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
7 changes: 6 additions & 1 deletion rust/kernel/sync/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@ impl<'a, L: Lock + ?Sized> Guard<'a, L> {
///
/// [`Guard`] is written such that any mutual exclusion primitive that can implement this trait can
/// also benefit from having an automatic way to unlock itself.
pub trait Lock {
///
/// # Safety
///
/// Implementers of this trait must ensure that only one thread/CPU may access the protected data
/// once the lock is held, that is, between calls to `lock_noguard` and `unlock`.
pub unsafe trait Lock {
/// The type of the data protected by the lock.
type Inner: ?Sized;

Expand Down
3 changes: 2 additions & 1 deletion rust/kernel/sync/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ impl<T: ?Sized> NeedsLockClass for Mutex<T> {
}
}

impl<T: ?Sized> Lock for Mutex<T> {
// SAFETY: The underlying kernel `struct mutex` object ensures mutual exclusion.
unsafe impl<T: ?Sized> Lock for Mutex<T> {
type Inner = T;
type GuardContext = ();

Expand Down
3 changes: 2 additions & 1 deletion rust/kernel/sync/spinlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ impl<T: ?Sized> NeedsLockClass for SpinLock<T> {
}
}

impl<T: ?Sized> Lock for SpinLock<T> {
// SAFETY: The underlying kernel `spinlock_t` object ensures mutual exclusion.
unsafe impl<T: ?Sized> Lock for SpinLock<T> {
type Inner = T;
type GuardContext = ();

Expand Down

0 comments on commit 2c1e84a

Please sign in to comment.