Skip to main content

ext_php_rs/zend/
ex.rs

1use crate::ffi::{ZEND_MM_ALIGNMENT, ZEND_MM_ALIGNMENT_MASK, zend_execute_data};
2
3use crate::{
4    args::ArgParser,
5    class::RegisteredClass,
6    types::{ZendClassObject, ZendObject, Zval},
7};
8
9use super::function::Function;
10
11/// Execute data passed when a function is called from PHP.
12///
13/// This generally contains things related to the call, including but not
14/// limited to:
15///
16/// * Arguments
17/// * `$this` object reference
18/// * Reference to return value
19/// * Previous execute data
20pub type ExecuteData = zend_execute_data;
21
22impl ExecuteData {
23    /// Returns an [`ArgParser`] pre-loaded with the arguments contained inside
24    /// `self`.
25    ///
26    /// # Example
27    ///
28    /// ```no_run
29    /// use ext_php_rs::{types::Zval, zend::ExecuteData, args::Arg, flags::DataType};
30    ///
31    /// #[unsafe(no_mangle)]
32    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
33    ///     let mut a = Arg::new("a", DataType::Long);
34    ///
35    ///     // The `parse_args!()` macro can be used for this.
36    ///     let parser = ex.parser()
37    ///         .arg(&mut a)
38    ///         .parse();
39    ///
40    ///     if parser.is_err() {
41    ///         return;
42    ///     }
43    ///
44    ///     dbg!(a);
45    /// }
46    /// ```
47    pub fn parser(&mut self) -> ArgParser<'_, '_> {
48        self.parser_object().0
49    }
50
51    /// Returns an [`ArgParser`] pre-loaded with the arguments contained inside
52    /// `self`.
53    ///
54    /// A reference to `$this` is also returned in an [`Option`], which resolves
55    /// to [`None`] if this function is not called inside a method.
56    ///
57    /// # Example
58    ///
59    /// ```no_run
60    /// use ext_php_rs::{types::Zval, zend::ExecuteData, args::Arg, flags::DataType};
61    ///
62    /// #[unsafe(no_mangle)]
63    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
64    ///     let mut a = Arg::new("a", DataType::Long);
65    ///
66    ///     let (parser, this) = ex.parser_object();
67    ///     let parser = parser
68    ///         .arg(&mut a)
69    ///         .parse();
70    ///
71    ///     if parser.is_err() {
72    ///         return;
73    ///     }
74    ///
75    ///     dbg!(a, this);
76    /// }
77    /// ```
78    pub fn parser_object(&mut self) -> (ArgParser<'_, '_>, Option<&mut ZendObject>) {
79        // SAFETY: All fields of the `u2` union are the same type.
80        let n_args = unsafe { self.This.u2.num_args };
81        let mut args = vec![];
82
83        for i in 0..n_args {
84            // SAFETY: Function definition ensures arg lifetime doesn't exceed execution
85            // data lifetime.
86            let arg = unsafe { self.zend_call_arg(i as usize) };
87            args.push(arg);
88        }
89
90        let obj = self.This.object_mut();
91
92        (ArgParser::new(args), obj)
93    }
94
95    /// Returns an [`ArgParser`] pre-loaded with the arguments contained inside
96    /// `self`.
97    ///
98    /// A reference to `$this` is also returned in an [`Option`], which resolves
99    /// to [`None`] if this function is not called inside a method.
100    ///
101    /// This function differs from [`parse_object`] in the fact that it returns
102    /// a reference to a [`ZendClassObject`], which is an object that
103    /// contains an arbitrary Rust type at the start of the object. The
104    /// object will also resolve to [`None`] if the function is called
105    /// inside a method that does not belong to an object with type `T`.
106    /// An object without its Rust value is returned: borrowing it gives
107    /// [`BorrowError::Uninitialized`](crate::types::BorrowError::Uninitialized).
108    ///
109    /// # Example
110    ///
111    /// ```no_run
112    /// use ext_php_rs::{types::Zval, zend::ExecuteData, args::Arg, flags::DataType, prelude::*};
113    ///
114    /// #[php_class]
115    /// #[derive(Debug)]
116    /// struct Example;
117    ///
118    /// #[unsafe(no_mangle)]
119    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
120    ///     let mut a = Arg::new("a", DataType::Long);
121    ///
122    ///     let (parser, this) = ex.parser_method::<Example>();
123    ///     let parser = parser
124    ///         .arg(&mut a)
125    ///         .parse();
126    ///
127    ///     if parser.is_err() {
128    ///         return;
129    ///     }
130    ///
131    ///     dbg!(a, this);
132    /// }
133    ///
134    /// #[php_module]
135    /// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
136    ///     module
137    /// }
138    /// ```
139    ///
140    /// [`parse_object`]: #method.parse_object
141    pub fn parser_method<T: RegisteredClass>(
142        &mut self,
143    ) -> (ArgParser<'_, '_>, Option<&ZendClassObject<T>>) {
144        let (parser, obj) = self.parser_object();
145        (
146            parser,
147            obj.and_then(|obj| ZendClassObject::from_zend_obj_uninit(obj)),
148        )
149    }
150
151    /// Attempts to retrieve a reference to the underlying class object of the
152    /// Zend object.
153    ///
154    /// Returns a [`ZendClassObject`] if the execution data contained a valid
155    /// object of type `T`, otherwise returns [`None`].
156    ///
157    /// # Example
158    ///
159    /// ```no_run
160    /// use ext_php_rs::{types::Zval, zend::ExecuteData, prelude::*};
161    ///
162    /// #[php_class]
163    /// #[derive(Debug)]
164    /// struct Example;
165    ///
166    /// #[unsafe(no_mangle)]
167    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
168    ///     let this = ex.get_object::<Example>();
169    ///     dbg!(this);
170    /// }
171    ///
172    /// #[php_module]
173    /// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
174    ///     module
175    /// }
176    /// ```
177    #[must_use]
178    pub fn get_object<T: RegisteredClass>(&self) -> Option<&ZendClassObject<T>> {
179        ZendClassObject::from_zend_obj_uninit(self.This.object()?)
180    }
181
182    /// Attempts to retrieve the 'this' object, which can be used in class
183    /// methods to retrieve the underlying Zend object.
184    ///
185    /// # Example
186    ///
187    /// ```no_run
188    /// use ext_php_rs::{types::Zval, zend::ExecuteData};
189    ///
190    /// #[unsafe(no_mangle)]
191    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
192    ///     let this = ex.get_self();
193    ///     dbg!(this);
194    /// }
195    /// ```
196    pub fn get_self(&mut self) -> Option<&mut ZendObject> {
197        // TODO(david): This should be a `&mut self` function but we need to fix arg
198        // parser first.
199        self.This.object_mut()
200    }
201
202    /// Attempt to retrieve the function that is being called.
203    #[must_use]
204    pub fn function(&self) -> Option<&Function> {
205        unsafe { self.func.as_ref() }
206    }
207
208    /// Attempt to retrieve the previous execute data on the call stack.
209    #[must_use]
210    pub fn previous(&self) -> Option<&Self> {
211        unsafe { self.prev_execute_data.as_ref() }
212    }
213
214    /// Translation of macro `ZEND_CALL_ARG(call, n)`
215    /// zend_compile.h:578
216    ///
217    /// The resultant [`Zval`] reference has a lifetime equal to the lifetime of
218    /// `self`. This isn't specified because when you attempt to get a
219    /// reference to args and the `$this` object, Rust doesn't let you.
220    /// Since this is a private method it's up to the caller to ensure the
221    /// lifetime isn't exceeded.
222    #[doc(hidden)]
223    #[must_use]
224    #[expect(
225        clippy::expect_used,
226        reason = "argument counts are bounded by the engine's own u32 limit"
227    )]
228    pub unsafe fn zend_call_arg<'a>(&self, n: usize) -> Option<&'a mut Zval> {
229        let n = isize::try_from(n).expect("n is too large");
230        let ptr = unsafe { self.zend_call_var_num(n) };
231        unsafe { ptr.as_mut() }
232    }
233
234    /// Translation of macro `ZEND_CALL_VAR_NUM(call, n)`
235    /// zend_compile.h: 575
236    #[doc(hidden)]
237    unsafe fn zend_call_var_num(&self, n: isize) -> *mut Zval {
238        let ptr = std::ptr::from_ref(self) as *mut Zval;
239        unsafe { ptr.offset(Self::zend_call_frame_slot() + n) }
240    }
241
242    /// Translation of macro `ZEND_CALL_FRAME_SLOT`
243    /// zend_compile:573
244    #[doc(hidden)]
245    fn zend_call_frame_slot() -> isize {
246        (Self::zend_mm_aligned_size::<Self>() + Self::zend_mm_aligned_size::<Zval>() - 1)
247            / Self::zend_mm_aligned_size::<Zval>()
248    }
249
250    /// Translation of macro `ZEND_MM_ALIGNED_SIZE(size)`
251    /// zend_alloc.h:41
252    #[doc(hidden)]
253    #[expect(
254        clippy::expect_used,
255        reason = "the size of a type the engine can allocate fits in isize"
256    )]
257    fn zend_mm_aligned_size<T>() -> isize {
258        let size = isize::try_from(std::mem::size_of::<T>()).expect("size of T is too large");
259        (size + ZEND_MM_ALIGNMENT - 1) & ZEND_MM_ALIGNMENT_MASK
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::ExecuteData;
266
267    #[test]
268    fn test_zend_call_frame_slot() {
269        // PHP 8.0.2 (cli) (built: Feb 21 2021 11:51:33) ( NTS )
270        // Copyright (c) The PHP Group
271        // Zend Engine v4.0.2, Copyright (c) Zend Technologies
272        assert_eq!(ExecuteData::zend_call_frame_slot(), 5);
273    }
274}