Skip to main content

lockdep/
lib.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![no_std]
6
7// Keep dependency alive even when lockdep is disabled to satisfy unused dependency lints.
8use zr as _;
9
10/// Trait implemented by lock class types to expose their dynamic LockClassId pointer.
11pub trait LockClass {
12    const ID: *mut core::ffi::c_void;
13}
14
15#[cfg(any(lock_dep, lock_metadata_only))]
16mod enabled {
17    core::cfg_select! {
18        lock_dep => {
19            const LOCK_CLASS_STATE_SIZE: usize = 840;
20            const LOCK_CLASS_REGISTRATION_SIZE: usize = 856;
21        }
22        lock_metadata_only => {
23            const LOCK_CLASS_STATE_SIZE: usize = 8;
24            const LOCK_CLASS_REGISTRATION_SIZE: usize = 24;
25        }
26    }
27
28    #[repr(C, align(8))]
29    #[derive(Default)]
30    struct LockClassStateStorage(zr::OpaqueBytes<LOCK_CLASS_STATE_SIZE>);
31
32    impl LockClassStateStorage {
33        const fn uninit() -> Self {
34            Self(zr::OpaqueBytes::uninit())
35        }
36    }
37
38    /// A registration entry for a Rust lock class.
39    ///
40    /// This struct is registered with the C++ lockdep implementation via a linker section. The
41    /// layout of this struct is known to C++.
42    #[repr(C)]
43    pub struct LockClassRegistration {
44        name: *const kstring::interned_string::InternedString,
45        flags: u16,
46        state_storage: LockClassStateStorage,
47    }
48
49    unsafe impl Sync for LockClassRegistration {}
50    unsafe impl Send for LockClassRegistration {}
51
52    impl LockClassRegistration {
53        pub const fn new(name: &'static ::kstring::interned_string::InternedString) -> Self {
54            Self { name, flags: 0, state_storage: LockClassStateStorage::uninit() }
55        }
56
57        #[inline]
58        pub const fn get(&self) -> *mut core::ffi::c_void {
59            self.state_storage.0.get() as *mut _
60        }
61    }
62
63    zr::static_assert!(
64        core::mem::size_of::<LockClassRegistration>() == LOCK_CLASS_REGISTRATION_SIZE
65    );
66    zr::static_assert!(core::mem::align_of::<LockClassRegistration>() == 8);
67}
68
69#[cfg(any(lock_dep, lock_metadata_only))]
70pub use enabled::LockClassRegistration;
71
72#[cfg(not(any(lock_dep, lock_metadata_only)))]
73mod disabled {
74    /// A registration entry for a Rust lock class (stub for disabled lockdep).
75    pub struct LockClassRegistration;
76
77    impl LockClassRegistration {
78        pub const fn new(_name: &'static ::kstring::interned_string::InternedString) -> Self {
79            Self
80        }
81
82        #[inline]
83        pub const fn get(&self) -> *mut core::ffi::c_void {
84            core::ptr::null_mut()
85        }
86    }
87}
88
89#[cfg(not(any(lock_dep, lock_metadata_only)))]
90pub use disabled::LockClassRegistration;