Repository navigation
Expand file tree
/
Copy pathcore.rs
More file actions
3366 lines (3012 loc) · 119 KB
/
Copy pathcore.rs
File metadata and controls
3366 lines (3012 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Essential types for object models
//!
//! +-------------------------+--------------+-----------------------+
//! | Management | Typed | Untyped |
//! +-------------------------+------------------+-------------------+
//! | Interpreter-independent | [`Py<T>`] | [`PyObject`] |
//! | Reference-counted | [`PyRef<T>`] | [`PyObjectRef`] |
//! | Weak | [`PyWeakRef<T>`] | [`PyRef<PyWeak>`] |
//! +-------------------------+--------------+-----------------------+
//!
//! [`PyRef<PyWeak>`] may looking like to be called as PyObjectWeak by the rule,
//! but not to do to remember it is a PyRef object.
use super::{
PyAtomicRef,
ext::{AsObject, PyRefExact, PyResult},
payload::PyPayload,
};
use crate::object::traverse_object::PyObjVTable;
use crate::{
builtins::{PyDictRef, PyTuple, PyTupleRef, PyType, PyTypeRef, type_::PyTypeTupleRef},
common::{
atomic::{Ordering, PyAtomic, Radium},
linked_list::{Link, Pointers},
lock::PyRwLock,
refcount::RefCount,
},
vm::VirtualMachine,
};
use crate::{
class::StaticType,
object::traverse::{MaybeTraverse, Traverse, TraverseFn},
};
use alloc::fmt;
use core::{
any::TypeId,
borrow::Borrow,
cell::UnsafeCell,
marker::PhantomData,
mem::ManuallyDrop,
num::NonZeroUsize,
ops::Deref,
ptr::{self, NonNull},
};
// so, PyObjectRef is basically equivalent to `PyRc<Py<dyn PyObjectPayload>>`, except it's
// only one pointer in width rather than 2. We do that by manually creating a vtable, and putting
// a &'static reference to it inside the `PyRc` rather than adjacent to it, like trait objects do.
// This can lead to faster code since there's just less data to pass around, as well as because of
// some weird stuff with trait objects, alignment, and padding.
//
// So, every type has an alignment, which means that if you create a value of it it's location in
// memory has to be a multiple of it's alignment. e.g., a type with alignment 4 (like i32) could be
// at 0xb7befbc0, 0xb7befbc4, or 0xb7befbc8, but not 0xb7befbc2. If you have a struct and there are
// 2 fields whose sizes/alignments don't perfectly fit in with each other, e.g.:
// +-------------+-------------+---------------------------+
// | u16 | ? | i32 |
// | 0x00 | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 |
// +-------------+-------------+---------------------------+
// There has to be padding in the space between the 2 fields. But, if that field is a trait object
// (like `dyn PyObjectPayload`) we don't *know* how much padding there is between the `payload`
// field and the previous field. So, Rust has to consult the vtable to know the exact offset of
// `payload` in `Py<dyn PyObjectPayload>`, which has a huge performance impact when *every
// single payload access* requires a vtable lookup. Thankfully, we're able to avoid that because of
// the way we use PyObjectRef, in that whenever we want to access the payload we (almost) always
// access it from a generic function. So, rather than doing
//
// - check vtable for payload offset
// - get offset in Py struct
// - call as_any() method of PyObjectPayload
// - call downcast_ref() method of Any
// we can just do
// - check vtable that typeid matches
// - pointer cast directly to *const Py<T>
//
// and at that point the compiler can know the offset of `payload` for us because **we've given it a
// concrete type to work with before we ever access the `payload` field**
/// A type to just represent "we've erased the type of this object, cast it before you use it"
#[derive(Debug)]
pub(super) struct Erased;
/// Trashcan mechanism to limit recursive deallocation depth (Py_TRASHCAN).
/// Without this, deeply nested structures (e.g. 200k-deep list) cause stack overflow
/// during deallocation because each level adds a stack frame.
mod trashcan {
use core::cell::Cell;
/// Maximum nesting depth for deallocation before deferring.
/// CPython uses UNWIND_NO_NESTING = 50.
const TRASHCAN_LIMIT: usize = 50;
type DeallocFn = unsafe fn(*mut super::PyObject);
type DeallocQueue = Vec<(*mut super::PyObject, DeallocFn)>;
/// Per-thread trashcan state. Depth and deferral queue live in one
/// thread-local so a single access reaches both fields (one `_tlv_get_addr`
/// on platforms where thread-local access is a function call). Both fields
/// are `Cell`-based so reentrant deallocation (nested `begin`/`end` triggered
/// by draining deferred objects) never holds an outstanding borrow.
struct Trashcan {
depth: Cell<usize>,
queue: Cell<DeallocQueue>,
}
thread_local! {
static TRASHCAN: Trashcan = const {
Trashcan {
depth: Cell::new(0),
queue: Cell::new(Vec::new()),
}
};
}
/// Try to begin deallocation. Returns true if we should proceed,
/// false if the object was deferred (depth exceeded).
#[inline]
pub(super) unsafe fn begin(
obj: *mut super::PyObject,
dealloc: unsafe fn(*mut super::PyObject),
) -> bool {
TRASHCAN.with(|t| {
let depth = t.depth.get();
if depth >= TRASHCAN_LIMIT {
// Depth exceeded: defer this deallocation
let mut queue = t.queue.take();
queue.push((obj, dealloc));
t.queue.set(queue);
false
} else {
t.depth.set(depth + 1);
true
}
})
}
/// End deallocation and process any deferred objects if at outermost level.
#[inline]
pub(super) unsafe fn end() {
TRASHCAN.with(|t| {
let depth = t.depth.get();
debug_assert!(depth > 0, "trashcan::end called without matching begin");
let depth = depth - 1;
t.depth.set(depth);
if depth != 0 {
return;
}
// Process deferred deallocations iteratively. The queue is set back
// before each `dealloc` call so a reentrant `begin` can push freely.
loop {
let next = {
let mut queue = t.queue.take();
let item = queue.pop();
t.queue.set(queue);
item
};
if let Some((obj, dealloc)) = next {
unsafe { dealloc(obj) };
} else {
break;
}
}
})
}
}
/// Default dealloc: handles __del__, weakref clearing, tp_clear, and memory free.
/// Equivalent to subtype_dealloc.
pub(super) unsafe fn default_dealloc<T: PyPayload>(obj: *mut PyObject) {
let obj_ref = unsafe { &*(obj as *const PyObject) };
if let Err(()) = obj_ref.drop_slow_inner() {
return; // resurrected by __del__
}
// Only tracked objects take the trashcan recursion guard and untrack path.
// Untracked objects either own no children (int, float, str, ...) or, like
// non-escaped frames, are released at interpreter depth with at most one
// unguarded link before their tracked children (dicts, functions, code)
// re-enter guarded deallocation, so recursion stays bounded. A frame stored
// in an object graph is forced to escape, becoming tracked and guarded here.
// Read once and reuse for both gates below.
let tracked = obj_ref.is_gc_tracked();
// Trashcan: limit recursive deallocation depth to prevent stack overflow
if tracked && !unsafe { trashcan::begin(obj, default_dealloc::<T>) } {
return; // deferred to queue
}
let vtable = obj_ref.0.vtable;
// Untrack from GC BEFORE deallocation.
// Must happen before memory is freed because intrusive list removal
// reads the object's gc_pointers (prev/next).
if tracked {
let ptr = unsafe { NonNull::new_unchecked(obj) };
unsafe {
crate::gc_state::gc_state().untrack_object(ptr);
}
// Verify untrack cleared the tracked flag and generation
debug_assert!(
!obj_ref.is_gc_tracked(),
"object still tracked after untrack_object"
);
debug_assert_eq!(
obj_ref.gc_generation(),
crate::object::GC_UNTRACKED,
"gc_generation not reset after untrack_object"
);
}
// Extract child references to break circular refs (tp_clear), then drop
// them. Some payloads (e.g. FrameObject) drop children in place inside clear_fn
// instead of extracting them, so user code (`__del__`) may run here.
let mut edges = Vec::new();
if let Some(clear_fn) = vtable.clear {
unsafe { clear_fn(obj, &mut edges) };
}
// Drop extracted child references - may trigger recursive destruction.
drop(edges);
// Try to store in freelist for reuse. This must happen AFTER clear_fn and
// after the extracted-children drop: both can run user code (`__del__`)
// that allocates, and `PyRef::new_ref` pops from the same thread-local
// freelist. If the husk were already in the freelist, a reentrant
// allocation could pop it and write a fresh payload into it while clear_fn
// still holds a `&mut` borrow of that payload (aliasing UB). Pushing only
// once no borrows into the payload can be live closes that window.
// Only exact base types (not heaptype or structseq subtypes) go into the freelist.
// Published objects (e.g. a tuple stored as a type attribute) must skip the
// freelist: `PyRef::new_ref` would reuse the slot and overwrite the refcount
// word with a non-atomic write, racing a reader's atomic try-incref. Route
// them through `Py::dealloc` instead, whose QSBR hook defers the actual
// memory free until readers can no longer observe it.
let typ = obj_ref.class();
let pushed = if T::HAS_FREELIST
&& typ.heaptype_ext.is_none()
&& core::ptr::eq(typ, T::class(crate::vm::Context::genesis()))
&& !obj_ref.0.ref_count.is_published()
{
if let Some(ext) = obj_ref.0.ext_ref() {
if obj_ref
.class()
.slots
.flags
.has_feature(crate::types::PyTypeFlags::HAS_DICT)
{
drop(ext.dict.replace(None));
}
for slot in obj_ref.0.slot_cells() {
drop(slot.store(None));
}
}
unsafe { T::freelist_push(obj) }
} else {
false
};
if !pushed {
// Deallocate the object memory (handles ObjExt prefix if present)
unsafe { Py::dealloc(obj as *mut Py<T>) };
}
// Trashcan: decrement depth and process deferred objects at outermost level
if tracked {
unsafe { trashcan::end() };
}
}
pub(super) unsafe fn debug_obj<T: PyPayload + core::fmt::Debug>(
x: &PyObject,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
let x = unsafe { &*(x as *const PyObject as *const Py<T>) };
write!(f, "[PyObject {:?}]", x.payload)
}
/// Call `try_trace` on payload
pub(super) unsafe fn try_traverse_obj<T: PyPayload>(x: &PyObject, tracer_fn: &mut TraverseFn<'_>) {
let x = unsafe { &*(x as *const PyObject as *const Py<T>) };
let payload = &x.payload;
payload.try_traverse(tracer_fn)
}
/// Call `try_clear` on payload to extract child references (tp_clear)
pub(super) unsafe fn try_clear_obj<T: PyPayload>(x: *mut PyObject, out: &mut Vec<PyObjectRef>) {
let x = unsafe { &mut *(x as *mut Py<T>) };
x.payload.try_clear(out);
}
bitflags::bitflags! {
/// GC bits for free-threading support (like ob_gc_bits in Py_GIL_DISABLED)
/// These bits are stored in a separate atomic field for lock-free access.
/// See Include/internal/pycore_gc.h
#[derive(Copy, Clone, Debug, Default)]
pub(crate) struct GcBits: u8 {
/// Tracked by the GC
const TRACKED = 1 << 0;
/// tp_finalize was called (prevents __del__ from being called twice)
const FINALIZED = 1 << 1;
/// Object is unreachable (during GC collection)
const UNREACHABLE = 1 << 2;
/// Object is frozen (immutable)
const FROZEN = 1 << 3;
/// Memory the object references is shared between multiple threads
/// and needs special handling when freeing due to possible in-flight lock-free reads
const SHARED = 1 << 4;
/// Memory of the object itself is shared between multiple threads
/// Objects with this bit that are GC objects will automatically be delay-freed
const SHARED_INLINE = 1 << 5;
/// Use deferred reference counting
const DEFERRED = 1 << 6;
/// In the candidate set of the collection that is running, so its
/// `gc_refs` is meaningful. `_PyGC_PREV_MASK_COLLECTING`.
const COLLECTING = 1 << 7;
}
}
/// GC generation constants
pub(crate) const GC_UNTRACKED: u8 = 0xFF;
pub(crate) const GC_PERMANENT: u8 = 3;
/// Width of an interpreter's `gc_owner` tag.
///
/// Sized to the padding the header alignment already forces, so the tag costs
/// no space on either pointer width. Running out of tags is not an error: an
/// interpreter that gets none uses [`GC_NO_OWNER`] and its objects stay
/// collectable by every interpreter, which is how they behaved before tagging.
pub(crate) type GcOwner = u16;
/// `gc_owner` of an object that belongs to no single interpreter: everything
/// the shared context allocates, and anything allocated with no interpreter
/// current. Every interpreter collects these.
pub(crate) const GC_NO_OWNER: GcOwner = 0;
/// `gc_refs` of an object a running collection has proved reachable. One past
/// the largest count [`PyObject::start_gc_refs`] stores, so no real count can
/// be taken for it.
pub(crate) const GC_REACHABLE: u32 = u32::MAX;
/// Link implementation for GC intrusive linked list tracking
pub(crate) struct GcLink;
// SAFETY: PyObject (Py<Erased>) is heap-allocated and pinned in memory
// once created. gc_pointers is at a fixed offset in Py.
unsafe impl Link for GcLink {
type Handle = NonNull<PyObject>;
type Target = PyObject;
fn as_raw(handle: &NonNull<PyObject>) -> NonNull<PyObject> {
*handle
}
unsafe fn from_raw(ptr: NonNull<PyObject>) -> NonNull<PyObject> {
ptr
}
unsafe fn pointers(target: NonNull<PyObject>) -> NonNull<Pointers<PyObject>> {
let inner_ptr = target.as_ptr() as *mut Py<Erased>;
unsafe { NonNull::new_unchecked(&raw mut (*inner_ptr).gc_pointers) }
}
}
/// Extension fields for objects that need dict or member slots.
/// Allocated as a prefix before Py when needed (prefix allocation pattern).
/// Access via `Py::ext_ref()` using negative offset from the object pointer.
///
/// align(8) ensures size_of::<ObjExt>() is always a multiple of 8,
/// so the offset from Layout::extend equals size_of::<ObjExt>() for any
/// Py<T> alignment (important on wasm32 where pointers are 4 bytes
/// but some payloads like PyWeak have align 8 due to i64 fields).
#[repr(C, align(8))]
pub(super) struct ObjExt {
/// Always present. The dict cell is its first field, so
/// `dict_member_offset` addresses that pointer. Null when the type has
/// no dict slot.
pub(super) dict: InstanceDict,
}
impl ObjExt {
fn new(dict: Option<PyDictRef>, has_dict: bool, inline_values: bool) -> Self {
Self {
dict: if has_dict {
InstanceDict::from_opt(dict, inline_values)
} else {
InstanceDict::from_opt(None, false)
},
}
}
}
impl fmt::Debug for ObjExt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[ObjExt]")
}
}
/// Precomputed offset constants for prefix allocation.
/// `ObjExt` and `WeakRefList` are align(8) and their sizes are multiples of 8,
/// so `Layout::extend` adds no padding between them. Slot cells are packed
/// immediately in front of `ObjExt`; any alignment padding is before the cells.
const EXT_OFFSET: usize = core::mem::size_of::<ObjExt>();
/// Byte offset of member cell `index` from the start of `Py`.
/// Cells live in front of the object, so the offset is negative.
///
/// `ObjExt` stays flush with `Py`. A subclass that adds `__weakref__`
/// puts that list in front of the cells, so this offset does not move.
pub(crate) fn slot_member_offset(index: usize) -> isize {
// Cell 0 sits directly in front of ObjExt. Higher indexes extend further
// forward, so a base class offset stays valid on a subclass with more slots.
let cell = core::mem::size_of::<PyAtomicRef<Option<PyObject>>>();
-((EXT_OFFSET + (index + 1) * cell) as isize)
}
fn slot_region_layout(member_count: usize) -> Option<core::alloc::Layout> {
if member_count == 0 {
return None;
}
let cell = core::mem::size_of::<PyAtomicRef<Option<PyObject>>>();
let bytes = member_count * cell;
let align = core::mem::align_of::<ObjExt>();
// Padding goes in front of the cells so cell 0 stays flush with ObjExt.
// On wasm32 a pointer is 4 bytes and ObjExt is align 8, so an odd count
// would otherwise leave a gap where cell 0 is supposed to be.
let pad = (align - bytes % align) % align;
Some(core::alloc::Layout::from_size_align(pad + bytes, align).unwrap())
}
const WEAKREF_OFFSET: usize = core::mem::size_of::<WeakRefList>();
/// Distance from `Py` back to a `WeakRefList`.
/// Layout: `[WeakRefList?][slots?][ObjExt?][Py]`.
fn weakref_prefix_offset(has_ext: bool, member_count: usize) -> usize {
let ext = if has_ext { EXT_OFFSET } else { 0 };
let slots = slot_region_layout(member_count).map_or(0, |layout| layout.size());
ext + slots + WEAKREF_OFFSET
}
const _: () =
assert!(core::mem::size_of::<ObjExt>().is_multiple_of(core::mem::align_of::<ObjExt>()));
const _: () = assert!(core::mem::align_of::<ObjExt>() >= core::mem::align_of::<Py<()>>());
const _: () = assert!(
core::mem::size_of::<WeakRefList>().is_multiple_of(core::mem::align_of::<WeakRefList>())
);
const _: () = assert!(core::mem::align_of::<WeakRefList>() >= core::mem::align_of::<Py<()>>());
/// This is an actual python object. It consists of a `typ` which is the
/// python class, and carries some rust payload optionally. This rust
/// payload can be a rust float or rust int in case of float and int objects.
#[repr(C)]
pub struct Py<T> {
pub(super) ref_count: RefCount,
pub(super) vtable: &'static PyObjVTable,
/// GC bits for free-threading (like ob_gc_bits)
pub(super) gc_bits: PyAtomic<u8>,
/// GC generation index (0-2=gen, GC_PERMANENT=permanent, GC_UNTRACKED=not tracked).
/// Uses PyAtomic for interior mutability (writes happen through &self under list locks).
pub(super) gc_generation: PyAtomic<u8>,
/// Interpreter that tracked this object, or `GC_NO_OWNER`. Written by
/// `track_object`; read to scope a collection to one interpreter.
/// Sits in what would otherwise be padding, so it costs no space.
pub(super) gc_owner: PyAtomic<GcOwner>,
/// The count a running collection is working with: the strong count with
/// the references held from inside the candidate set taken off, or
/// [`GC_REACHABLE`] once the object has been proved reachable. Only
/// meaningful while `gc_bits` has [`GcBits::COLLECTING`].
pub(super) gc_refs: PyAtomic<u32>,
/// Intrusive linked list pointers for GC generational tracking
pub(super) gc_pointers: Pointers<PyObject>,
pub(super) typ: PyAtomicRef<PyType>, // __class__ member
pub(crate) payload: T,
}
pub const SIZEOF_PYOBJECT_HEAD: usize = core::mem::size_of::<Py<()>>();
/// Byte offset of the payload inside `Py<T>`.
#[must_use]
#[inline]
pub const fn payload_offset<T>() -> usize {
core::mem::offset_of!(Py<T>, payload)
}
/// Byte offset of the instance-dict pointer from the start of `Py`.
///
/// The pointer is the first field of `ObjExt`, which sits immediately in front
/// of `Py`. The cell owns the dict.
#[must_use]
#[inline]
pub const fn dict_member_offset() -> isize {
-(core::mem::size_of::<ObjExt>() as isize)
}
// ref_count, vtable, gc_pointers (two) and typ are one word each; the gc bits,
// generation, owner and refs take eight bytes between them. A 64-bit header had
// those eight as the padding its alignment forces, so they cost it nothing; a
// 32-bit header spends a word on them. Adding to that group is free only while
// this holds.
const _: () = assert!(SIZEOF_PYOBJECT_HEAD == 5 * core::mem::size_of::<usize>() + 8);
// `Py::drop_fields` names `payload` and `typ`; it is only complete while
// every other field stays trivially destructible.
const _: () = assert!(
!core::mem::needs_drop::<RefCount>()
&& !core::mem::needs_drop::<&'static PyObjVTable>()
&& !core::mem::needs_drop::<PyAtomic<u8>>()
&& !core::mem::needs_drop::<PyAtomic<u32>>()
&& !core::mem::needs_drop::<PyAtomic<GcOwner>>()
&& !core::mem::needs_drop::<Pointers<PyObject>>()
);
impl<T> Py<T> {
/// Read type flags and member_count via raw pointers to avoid Stacked Borrows
/// violations during bootstrap, where type objects have self-referential typ pointers.
#[inline(always)]
fn read_type_flags(&self) -> (crate::types::PyTypeFlags, usize) {
let typ_ptr = self.typ.load_raw();
let slots = unsafe { core::ptr::addr_of!((*typ_ptr).payload.slots) };
// SAFETY: `flags` is `PyAtomicTypeFlags`, transparent over `AtomicU64`.
// The type object is live. This load does not form a reference to it.
let bits = unsafe {
(*core::ptr::addr_of!((*slots).flags).cast::<core::sync::atomic::AtomicU64>())
.load(core::sync::atomic::Ordering::Acquire)
};
let member_count = unsafe { core::ptr::addr_of!((*slots).member_count).read() };
(
crate::types::PyTypeFlags::from_bits_truncate(bits),
member_count,
)
}
/// Access the ObjExt prefix at a negative offset from this Py.
/// Returns None if this object was allocated without dict/slots.
///
/// Layout: [WeakRefList?][slots?][ObjExt?][Py]
/// `ObjExt` is always immediately in front of `Py`.
#[inline(always)]
pub(super) fn ext_ref(&self) -> Option<&ObjExt> {
let (flags, member_count) = self.read_type_flags();
let has_ext = flags.has_feature(crate::types::PyTypeFlags::HAS_DICT) || member_count > 0;
if !has_ext {
return None;
}
let self_addr = (self as *const Self as *const u8).addr();
let ext_ptr =
core::ptr::with_exposed_provenance::<ObjExt>(self_addr.wrapping_sub(EXT_OFFSET));
Some(unsafe { &*ext_ptr })
}
/// Member cells are the pointer array immediately before [`ObjExt`].
/// Layout: `[WeakRefList?][PyAtomicRef<Option<PyObject>>; N][ObjExt?][Py]`.
pub(super) fn slot_cells(&self) -> &[PyAtomicRef<Option<PyObject>>] {
let Some(ext) = self.ext_ref() else {
return &[];
};
let (_, member_count) = self.read_type_flags();
if member_count == 0 {
return &[];
}
let cell = core::mem::size_of::<PyAtomicRef<Option<PyObject>>>();
// Index 0 is the cell adjacent to ObjExt; index i is i cells before it.
let first = (ext as *const ObjExt)
.addr()
.wrapping_sub(member_count * cell);
let ptr = core::ptr::with_exposed_provenance::<PyAtomicRef<Option<PyObject>>>(first);
unsafe { core::slice::from_raw_parts(ptr, member_count) }
}
/// Access the WeakRefList prefix at a fixed negative offset from this Py.
/// Returns None if the type does not support weakrefs.
///
/// Layout: [WeakRefList?][slots?][ObjExt?][Py]
/// The list sits in front of the slot cells so adding it on a subclass
/// does not move inherited member offsets.
#[inline(always)]
pub(super) fn weakref_list_ref(&self) -> Option<&WeakRefList> {
let (flags, member_count) = self.read_type_flags();
if !flags.has_feature(crate::types::PyTypeFlags::HAS_WEAKREF) {
return None;
}
let has_ext = flags.has_feature(crate::types::PyTypeFlags::HAS_DICT) || member_count > 0;
let self_addr = (self as *const Self as *const u8).addr();
let ptr = core::ptr::with_exposed_provenance::<WeakRefList>(
self_addr.wrapping_sub(weakref_prefix_offset(has_ext, member_count)),
);
Some(unsafe { &*ptr })
}
}
unsafe impl Traverse for PyObject {
/// DO notice that call `trace` on `PyObject` means apply `tracer_fn` on `PyObject`'s children,
/// not like call `trace` on `PyObjectRef` which apply `tracer_fn` on `PyObjectRef` itself
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
self.0.traverse(tracer_fn)
}
}
// === Stripe lock for weakref list protection (WEAKREF_LIST_LOCK) ===
#[cfg(feature = "threading")]
mod weakref_lock {
use core::sync::atomic::{AtomicU8, Ordering};
const NUM_WEAKREF_LOCKS: usize = 64;
static LOCKS: [AtomicU8; NUM_WEAKREF_LOCKS] = [const { AtomicU8::new(0) }; NUM_WEAKREF_LOCKS];
pub(super) struct WeakrefLockGuard {
idx: usize,
}
impl Drop for WeakrefLockGuard {
fn drop(&mut self) {
LOCKS[self.idx].store(0, Ordering::Release);
}
}
pub(super) fn lock(addr: usize) -> WeakrefLockGuard {
let idx = (addr >> 4) % NUM_WEAKREF_LOCKS;
loop {
if LOCKS[idx]
.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
return WeakrefLockGuard { idx };
}
core::hint::spin_loop();
}
}
/// Reset all weakref stripe locks after fork in child process.
/// Locks held by parent threads would cause infinite spin in the child.
#[cfg(all(unix, feature = "host_env"))]
pub(crate) fn reset_all_after_fork() {
for lock in &LOCKS {
lock.store(0, Ordering::Release);
}
}
}
#[cfg(not(feature = "threading"))]
mod weakref_lock {
pub(super) struct WeakrefLockGuard;
impl Drop for WeakrefLockGuard {
fn drop(&mut self) {}
}
pub(super) fn lock(_addr: usize) -> WeakrefLockGuard {
WeakrefLockGuard
}
}
/// Reset weakref stripe locks after fork. Must be called before any
/// Python code runs in the child process.
#[cfg(all(unix, feature = "threading", feature = "host_env"))]
pub(crate) fn reset_weakref_locks_after_fork() {
weakref_lock::reset_all_after_fork();
}
// === WeakRefList: inline on every object (tp_weaklist) ===
#[repr(C)]
pub(super) struct WeakRefList {
/// Head of the intrusive doubly-linked list of weakrefs.
head: PyAtomic<*mut Py<PyWeak>>,
/// Cached generic weakref (no callback, exact weakref type).
/// Matches try_reuse_basic_ref in weakrefobject.c.
generic: PyAtomic<*mut Py<PyWeak>>,
}
impl fmt::Debug for WeakRefList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WeakRefList").finish_non_exhaustive()
}
}
/// Unlink a node from the weakref list. Must be called under stripe lock.
///
/// # Safety
/// `node` must be a valid pointer to a node currently in the list owned by `wrl`.
unsafe fn unlink_weakref(wrl: &WeakRefList, node: NonNull<Py<PyWeak>>) {
unsafe {
let mut ptrs = WeakLink::pointers(node);
let prev = ptrs.as_ref().get_prev();
let next = ptrs.as_ref().get_next();
if let Some(prev) = prev {
WeakLink::pointers(prev).as_mut().set_next(next);
} else {
// node is the head
wrl.head.store(
next.map_or(ptr::null_mut(), |p| p.as_ptr()),
Ordering::Relaxed,
);
}
if let Some(next) = next {
WeakLink::pointers(next).as_mut().set_prev(prev);
}
ptrs.as_mut().set_prev(None);
ptrs.as_mut().set_next(None);
}
}
// try_reuse_basic_ref
unsafe fn try_reuse_weakref(ptr: *mut Py<PyWeak>) -> Option<PyRef<PyWeak>> {
if ptr.is_null() {
return None;
}
let node = unsafe { &*ptr };
node.ref_count
.safe_inc()
.then(|| unsafe { PyRef::from_raw(ptr) })
}
impl WeakRefList {
pub(super) fn new() -> Self {
Self {
head: Radium::new(ptr::null_mut()),
generic: Radium::new(ptr::null_mut()),
}
}
/// get_or_create_weakref
fn add(
&self,
obj: &PyObject,
cls: PyTypeRef,
cls_is_weakref: bool,
cls_is_weakproxy: bool,
callback: Option<PyObjectRef>,
dict: Option<PyDictRef>,
) -> PyRef<PyWeak> {
let is_generic = cls_is_weakref && callback.is_none();
let is_generic_proxy = cls_is_weakproxy && callback.is_none();
// Try reuse under lock first (fast path, no allocation)
{
let _lock = weakref_lock::lock(obj as *const PyObject as usize);
let existing = if is_generic {
unsafe { try_reuse_weakref(self.generic.load(Ordering::Relaxed)) }
} else if is_generic_proxy {
unsafe { try_reuse_weakref(self.find_generic_proxy_ptr()) }
} else {
None
};
if let Some(existing) = existing {
return existing;
}
}
// Allocate OUTSIDE the stripe lock. PyRef::new_ref may trigger
// maybe_collect → GC → WeakRefList::clear on another object that
// hashes to the same stripe, which would deadlock on the spinlock.
let weak_payload = PyWeak {
pointers: Pointers::new(),
wr_object: Radium::new(obj as *const PyObject as *mut PyObject),
callback: UnsafeCell::new(callback),
hash: Radium::new(crate::common::hash::SENTINEL),
};
let weak = PyRef::new_ref(weak_payload, cls, dict);
// Re-acquire lock for linked list insertion
let _lock = weakref_lock::lock(obj as *const PyObject as usize);
// Re-check: another thread may have inserted a generic ref/proxy
// while we were allocating outside the lock. If so, reuse it and
// drop ours.
let existing = if is_generic {
unsafe { try_reuse_weakref(self.generic.load(Ordering::Relaxed)) }
} else if is_generic_proxy {
unsafe { try_reuse_weakref(self.find_generic_proxy_ptr()) }
} else {
None
};
if let Some(existing) = existing {
// Nullify wr_object so drop_inner won't unlink an
// un-inserted node (which would corrupt the list head).
weak.wr_object.store(ptr::null_mut(), Ordering::Relaxed);
return existing;
}
// Insert into linked list under stripe lock
// (insert_weakref: generic ref at head, generic proxy right after it)
let node_ptr = NonNull::from(&*weak);
let after = if is_generic {
None
} else if is_generic_proxy {
NonNull::new(self.generic.load(Ordering::Relaxed))
} else {
NonNull::new(self.find_generic_proxy_ptr())
.or_else(|| NonNull::new(self.generic.load(Ordering::Relaxed)))
};
match after {
Some(after) => unsafe { self.insert_after(after, node_ptr) },
None => unsafe { self.insert_at_head(node_ptr) },
}
if is_generic {
self.generic.store(node_ptr.as_ptr(), Ordering::Relaxed);
}
weak
}
unsafe fn insert_at_head(&self, node_ptr: NonNull<Py<PyWeak>>) {
unsafe {
let mut ptrs = WeakLink::pointers(node_ptr);
let old_head = self.head.load(Ordering::Relaxed);
ptrs.as_mut().set_next(NonNull::new(old_head));
ptrs.as_mut().set_prev(None);
if let Some(old_head) = NonNull::new(old_head) {
WeakLink::pointers(old_head)
.as_mut()
.set_prev(Some(node_ptr));
}
self.head.store(node_ptr.as_ptr(), Ordering::Relaxed);
}
}
unsafe fn insert_after(&self, after: NonNull<Py<PyWeak>>, node_ptr: NonNull<Py<PyWeak>>) {
unsafe {
let mut ptrs = WeakLink::pointers(node_ptr);
let after_next = WeakLink::pointers(after).as_ref().get_next();
ptrs.as_mut().set_prev(Some(after));
ptrs.as_mut().set_next(after_next);
WeakLink::pointers(after).as_mut().set_next(Some(node_ptr));
if let Some(next) = after_next {
WeakLink::pointers(next).as_mut().set_prev(Some(node_ptr));
}
}
}
// get_basic_refs
fn find_generic_proxy_ptr(&self) -> *mut Py<PyWeak> {
let generic_ptr = self.generic.load(Ordering::Relaxed);
let candidate_ptr = if let Some(generic_node) = NonNull::new(generic_ptr) {
unsafe { WeakLink::pointers(generic_node).as_ref().get_next() }
.map_or(ptr::null_mut(), |n| n.as_ptr())
} else {
self.head.load(Ordering::Relaxed)
};
match NonNull::new(candidate_ptr) {
Some(candidate) => {
let node = unsafe { candidate.as_ref() };
let has_callback = unsafe { (&*node.payload.callback.get()).is_some() };
let node_cls = node.class();
// PyWeakref_CheckProxy: the basic-proxy slot is reserved for
// the canonical proxy type; subclasses and callback-less ref
// subclasses must not be mistaken for it.
let is_proxy = node_cls.is(crate::builtins::PyWeakProxy::static_type())
|| node_cls.is(crate::builtins::PyWeakCallableProxy::static_type());
if has_callback || !is_proxy {
ptr::null_mut()
} else {
candidate_ptr
}
}
None => ptr::null_mut(),
}
}
/// Clear all weakrefs and call their callbacks.
/// Called when the owner object is being dropped.
// PyObject_ClearWeakRefs
fn clear(&self, obj: &PyObject) {
let obj_addr = obj as *const PyObject as usize;
let _lock = weakref_lock::lock(obj_addr);
// Clear generic cache
self.generic.store(ptr::null_mut(), Ordering::Relaxed);
// Walk the list, collecting weakrefs with callbacks
let mut callbacks: Vec<(PyRef<PyWeak>, PyObjectRef)> = Vec::new();
let mut current = NonNull::new(self.head.load(Ordering::Relaxed));
while let Some(node) = current {
let next = unsafe { WeakLink::pointers(node).as_ref().get_next() };
let wr = unsafe { node.as_ref() };
// Mark weakref as dead
wr.payload
.wr_object
.store(ptr::null_mut(), Ordering::Relaxed);
// Unlink from list
unsafe {
let mut ptrs = WeakLink::pointers(node);
ptrs.as_mut().set_prev(None);
ptrs.as_mut().set_next(None);
}
// Collect callback only if we can still acquire a strong ref.
if wr.ref_count.safe_inc() {
let wr_ref = unsafe { PyRef::from_raw(wr as *const Py<PyWeak>) };
let cb = unsafe { wr.payload.callback.get().replace(None) };
if let Some(cb) = cb {
callbacks.push((wr_ref, cb));
}
}
current = next;
}
self.head.store(ptr::null_mut(), Ordering::Relaxed);
// Invoke callbacks outside the lock
drop(_lock);
for (wr, cb) in callbacks {
crate::vm::thread::with_vm(&cb, |vm| {
let _ = cb.call((wr.clone(),), vm);
});
}
}
/// Clear all weakrefs but DON'T call callbacks. Instead, return them for later invocation.
/// Used by GC to ensure ALL weakrefs are cleared BEFORE any callbacks are invoked.
/// handle_weakrefs() clears all weakrefs first, then invokes callbacks.
fn clear_for_gc_collect_callbacks(&self, obj: &PyObject) -> Vec<(PyRef<PyWeak>, PyObjectRef)> {
let obj_addr = obj as *const PyObject as usize;
let _lock = weakref_lock::lock(obj_addr);
// Clear generic cache
self.generic.store(ptr::null_mut(), Ordering::Relaxed);
let mut callbacks = Vec::new();
let mut current = NonNull::new(self.head.load(Ordering::Relaxed));
while let Some(node) = current {
let next = unsafe { WeakLink::pointers(node).as_ref().get_next() };
let wr = unsafe { node.as_ref() };
// Mark weakref as dead
wr.payload
.wr_object
.store(ptr::null_mut(), Ordering::Relaxed);
// Unlink from list
unsafe {
let mut ptrs = WeakLink::pointers(node);
ptrs.as_mut().set_prev(None);
ptrs.as_mut().set_next(None);
}
// Collect callback without invoking only if we can keep weakref alive.
if wr.ref_count.safe_inc() {
let wr_ref = unsafe { PyRef::from_raw(wr as *const Py<PyWeak>) };
let cb = unsafe { wr.payload.callback.get().replace(None) };
if let Some(cb) = cb {
callbacks.push((wr_ref, cb));
}
}
current = next;
}
self.head.store(ptr::null_mut(), Ordering::Relaxed);
callbacks
}
fn count(&self, obj: &PyObject) -> usize {
let _lock = weakref_lock::lock(obj as *const PyObject as usize);
let mut count = 0usize;
let mut current = NonNull::new(self.head.load(Ordering::Relaxed));
while let Some(node) = current {
if unsafe { node.as_ref() }.ref_count.get() > 0 {
count += 1;
}
current = unsafe { WeakLink::pointers(node).as_ref().get_next() };
}
count
}
fn get_weak_references(&self, obj: &PyObject) -> Vec<PyRef<PyWeak>> {
let _lock = weakref_lock::lock(obj as *const PyObject as usize);
let mut v = Vec::new();
let mut current = NonNull::new(self.head.load(Ordering::Relaxed));
while let Some(node) = current {
let wr = unsafe { node.as_ref() };
if wr.ref_count.safe_inc() {
v.push(unsafe { PyRef::from_raw(wr as *const Py<PyWeak>) });
}
current = unsafe { WeakLink::pointers(node).as_ref().get_next() };
}
v
}
}
impl Default for WeakRefList {
fn default() -> Self {
Self::new()
}
}
struct WeakLink;
unsafe impl Link for WeakLink {
type Handle = PyRef<PyWeak>;
type Target = Py<PyWeak>;
#[inline(always)]
fn as_raw(handle: &PyRef<PyWeak>) -> NonNull<Self::Target> {
NonNull::from(&**handle)