ext_php_rs/gc.rs
1//! Reports the PHP values held in the Rust fields of a class to the PHP cycle
2//! collector.
3//!
4//! The collector finds a cycle only when every object in it tells which
5//! values it holds. The [`macro@crate::php_class`] macro does this for each
6//! field whose type implements [`GcTrace`].
7
8use std::{
9 collections::{BTreeMap, HashMap},
10 os::raw::c_int,
11 ptr,
12};
13
14use crate::{
15 boxed::ZBox,
16 class::RegisteredClass,
17 ffi::{zend_get_gc_buffer, zend_get_gc_buffer_create, zend_get_gc_buffer_grow},
18 flags::ZvalTypeFlags,
19 types::{ZendClassObject, ZendObject, Zval},
20};
21
22/// The values that one object reports to the cycle collector.
23///
24/// Only the `get_gc` handler of a [`RegisteredClass`] creates it, and gives it
25/// to [`RegisteredClass::gc_trace`]. Only [`GcTrace`] implementations can add
26/// values to it.
27pub struct GcRoots {
28 buffer: *mut zend_get_gc_buffer,
29}
30
31impl GcRoots {
32 pub(crate) fn new() -> Self {
33 Self {
34 buffer: ptr::null_mut(),
35 }
36 }
37
38 pub(crate) fn is_empty(&self) -> bool {
39 self.buffer.is_null()
40 }
41
42 /// `zend_get_gc_buffer_add_zval`: copies `value` without a new reference.
43 pub(crate) fn push(&mut self, value: &Zval) {
44 // SAFETY: every variant of the `u1` union is a plain integer.
45 let type_info = unsafe { value.u1.type_info };
46 if ZvalTypeFlags::from_bits_retain(type_info).contains(ZvalTypeFlags::RefCounted) {
47 let slot = self.next_slot();
48 // SAFETY: `next_slot` returns a writable slot of the engine buffer.
49 unsafe {
50 (*slot).value = value.value;
51 (*slot).u1 = value.u1;
52 }
53 }
54 }
55
56 /// `zend_get_gc_buffer_add_obj`.
57 pub(crate) fn push_object(&mut self, object: &ZendObject) {
58 let slot = self.next_slot();
59 // SAFETY: `next_slot` returns a writable slot of the engine buffer.
60 unsafe {
61 (*slot).value.obj = ptr::from_ref(object).cast_mut();
62 (*slot).u1.type_info = ZvalTypeFlags::ObjectEx.bits();
63 }
64 }
65
66 fn next_slot(&mut self) -> *mut Zval {
67 // SAFETY: the collector calls `get_gc` with the engine running, and
68 // only one `get_gc` call is active at a time, so the buffer is ours.
69 unsafe {
70 if self.buffer.is_null() {
71 self.buffer = zend_get_gc_buffer_create();
72 }
73 let buffer = &mut *self.buffer;
74 if buffer.cur == buffer.end {
75 zend_get_gc_buffer_grow(buffer);
76 }
77 let slot = buffer.cur;
78 buffer.cur = buffer.cur.add(1);
79 slot
80 }
81 }
82
83 /// `zend_get_gc_buffer_use`.
84 ///
85 /// # Safety
86 ///
87 /// The roots must not be empty, and `table` and `n` must be the out
88 /// pointers of a `get_gc` call.
89 pub(crate) unsafe fn write_table(self, table: *mut *mut Zval, n: *mut c_int) {
90 // SAFETY: the caller guarantees a pushed value, so `buffer` is the
91 // engine buffer and `cur` is in the same allocation as `start`.
92 unsafe {
93 let buffer = &*self.buffer;
94 *table = buffer.start;
95 *n = c_int::try_from(buffer.cur.offset_from(buffer.start)).unwrap_or(c_int::MAX);
96 }
97 }
98}
99
100/// A value that holds references to PHP values.
101///
102/// [`macro@crate::php_class`] calls [`GcTrace::gc_trace`] for each field of
103/// the class whose type implements this trait. The PHP cycle collector can
104/// then free a cycle that goes through the field, for example an object that
105/// keeps a closure which captures the same object.
106///
107/// ext-php-rs implements it for [`Zval`], [`ZBox<ZendObject>`],
108/// [`ZBox<ZendClassObject<T>>`], an owned [`ZendCallable`] and the standard
109/// containers of these types. It does not implement it for
110/// `ZBox<ZendHashTable>`: keep an array in a [`Zval`] to make it visible.
111///
112/// # Safety
113///
114/// An implementation must report only the PHP references that `self` owns,
115/// each one time, and report the same values while `self` does not change. It
116/// must not call PHP code and must not panic. If a reference is reported two
117/// times, or is not owned, the collector can free a value that is still in
118/// use.
119///
120/// The collector reads the value while methods can hold shared borrows of
121/// it. Do not report values behind interior mutability (`RefCell`, `Cell`,
122/// `Mutex`): a shared borrow does not stop a change to them.
123///
124/// [`ZendCallable`]: crate::types::ZendCallable
125pub unsafe trait GcTrace {
126 /// Adds the PHP references owned by `self` to `roots`.
127 ///
128 /// # Safety
129 ///
130 /// Call it at most one time for each value during one `get_gc` call.
131 unsafe fn gc_trace(&self, roots: &mut GcRoots);
132}
133
134unsafe impl GcTrace for Zval {
135 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
136 roots.push(self);
137 }
138}
139
140unsafe impl GcTrace for ZBox<ZendObject> {
141 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
142 roots.push_object(self);
143 }
144}
145
146unsafe impl<T: RegisteredClass> GcTrace for ZBox<ZendClassObject<T>> {
147 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
148 roots.push_object(&self.std);
149 }
150}
151
152unsafe impl<T: GcTrace> GcTrace for Option<T> {
153 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
154 if let Some(value) = self {
155 // SAFETY: `self` owns its value, which nothing else reports.
156 unsafe { value.gc_trace(roots) };
157 }
158 }
159}
160
161unsafe impl<T: GcTrace + ?Sized> GcTrace for Box<T> {
162 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
163 // SAFETY: the box owns its value, which nothing else reports.
164 unsafe { (**self).gc_trace(roots) };
165 }
166}
167
168unsafe impl<T: GcTrace> GcTrace for [T] {
169 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
170 for value in self {
171 // SAFETY: each element is a distinct value, reported one time.
172 unsafe { value.gc_trace(roots) };
173 }
174 }
175}
176
177unsafe impl<T: GcTrace, const N: usize> GcTrace for [T; N] {
178 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
179 // SAFETY: the slice reports each element one time.
180 unsafe { self.as_slice().gc_trace(roots) };
181 }
182}
183
184unsafe impl<T: GcTrace> GcTrace for Vec<T> {
185 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
186 // SAFETY: the slice reports each element one time.
187 unsafe { self.as_slice().gc_trace(roots) };
188 }
189}
190
191unsafe impl<K, V: GcTrace, S> GcTrace for HashMap<K, V, S> {
192 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
193 for value in self.values() {
194 // SAFETY: each value is a distinct entry, reported one time.
195 unsafe { value.gc_trace(roots) };
196 }
197 }
198}
199
200unsafe impl<K, V: GcTrace> GcTrace for BTreeMap<K, V> {
201 unsafe fn gc_trace(&self, roots: &mut GcRoots) {
202 for value in self.values() {
203 // SAFETY: each value is a distinct entry, reported one time.
204 unsafe { value.gc_trace(roots) };
205 }
206 }
207}