Skip to content

Commit 273fa80

Browse files
committed
Add stripe lock to get_weakrefs and compile-time alignment assertions
- Acquire weakref stripe lock in get_weakrefs() before dereferencing head_ptr to prevent race with add/clear/drop_inner. - Add compile-time assertions that ObjExt size/alignment guarantees no padding from Layout::extend, validating EXT_OFFSET correctness.
1 parent dc0dec0 commit 273fa80

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

‎crates/vm/src/object/core.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -279,9 +279,14 @@ impl fmt::Debug for ObjExt {
279279
}
280280

281281
/// Precomputed offset from PyInner pointer back to ObjExt prefix.
282-
/// Both ObjExt and PyInner are #[repr(C)] with 8-byte alignment,
283-
/// so the offset equals size_of::<ObjExt>() with no padding.
282+
/// ObjExt is #[repr(C, align(8))] and PyInner is #[repr(C)], so as long as
283+
/// ObjExt's alignment >= PyInner's alignment, Layout::extend adds no padding
284+
/// and the offset equals size_of::<ObjExt>().
284285
const EXT_OFFSET: usize = core::mem::size_of::<ObjExt>();
286+
// Guarantee: ObjExt size is a multiple of its alignment, and its alignment
287+
// is >= any PyInner alignment, so Layout::extend produces no inter-padding.
288+
const _: () = assert!(core::mem::size_of::<ObjExt>() % core::mem::align_of::<ObjExt>() == 0);
289+
const _: () = assert!(core::mem::align_of::<ObjExt>() >= core::mem::align_of::<PyInner<()>>());
285290

286291
/// This is an actual python object. It consists of a `typ` which is the
287292
/// python class, and carries some rust payload optionally. This rust
@@ -1061,6 +1066,7 @@ impl PyObject {
10611066
/// Returns the first weakref in the weakref list, if any.
10621067
pub(crate) fn get_weakrefs(&self) -> Option<PyObjectRef> {
10631068
let wrl = self.weak_ref_list()?;
1069+
let _lock = weakref_lock::lock(self as *const PyObject as usize);
10641070
let head_ptr = wrl.head.load(Ordering::Relaxed);
10651071
if head_ptr.is_null() {
10661072
None

0 commit comments

Comments
 (0)