Skip to main content

ext_php_rs/zend/
function.rs

1//! Builder for creating functions and methods in PHP.
2
3use std::{fmt::Debug, mem::MaybeUninit, os::raw::c_char, ptr};
4
5use crate::{
6    convert::IntoZvalDyn,
7    error::Result,
8    ffi::{
9        HashTable, ZEND_INTERNAL_FUNCTION, zend_call_known_function, zend_fetch_function_str,
10        zend_function, zend_function_entry, zend_hash_str_find_ptr_lc, zend_internal_function,
11        zend_op_array,
12    },
13    flags::{FunctionType, MethodFlags},
14    types::Zval,
15};
16
17use super::ClassEntry;
18
19/// A Zend function entry.
20pub type FunctionEntry = zend_function_entry;
21
22impl Debug for FunctionEntry {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.debug_struct("_zend_function_entry")
25            .field("fname", &self.fname)
26            .field("arg_info", &self.arg_info)
27            .field("num_args", &self.num_args)
28            .field("flags", &self.flags)
29            .finish()
30    }
31}
32
33impl FunctionEntry {
34    /// Returns an empty function entry, signifing the end of a function list.
35    #[must_use]
36    pub fn end() -> Self {
37        Self {
38            fname: ptr::null::<c_char>(),
39            handler: None,
40            arg_info: ptr::null(),
41            num_args: 0,
42            flags: 0,
43            #[cfg(php84)]
44            doc_comment: ptr::null(),
45            #[cfg(php84)]
46            frameless_function_infos: ptr::null(),
47        }
48    }
49
50    pub(crate) fn add_flags(&mut self, flags: MethodFlags) {
51        cfg_if::cfg_if! {
52            if #[cfg(php86)] {
53                self.flags |= u64::from(flags.bits());
54            } else {
55                self.flags |= flags.bits();
56            }
57        }
58    }
59}
60
61/// PHP function.
62pub type Function = zend_function;
63
64impl Function {
65    /// Returns the function type.
66    ///
67    /// # Errors
68    ///
69    /// * [`Error::UnknownFunctionType`] - If the engine reports a function type
70    ///   this crate does not model.
71    ///
72    /// [`Error::UnknownFunctionType`]: crate::error::Error::UnknownFunctionType
73    pub fn function_type(&self) -> Result<FunctionType> {
74        FunctionType::try_from(unsafe { self.type_ })
75    }
76
77    /// Attempts to fetch a [`Function`] from the function name.
78    #[inline]
79    #[must_use]
80    pub fn try_from_function(name: &str) -> Option<Self> {
81        unsafe {
82            let res = zend_fetch_function_str(name.as_ptr().cast::<c_char>(), name.len());
83            if res.is_null() {
84                return None;
85            }
86            Some(copy_function(res))
87        }
88    }
89
90    /// Attempts to fetch a [`Function`] from the class and method name.
91    #[must_use]
92    pub fn try_from_method(class: &str, name: &str) -> Option<Self> {
93        match ClassEntry::try_find(class) {
94            None => None,
95            Some(ce) => unsafe {
96                let res = zend_hash_str_find_ptr_lc(
97                    &raw const ce.function_table,
98                    name.as_ptr().cast::<c_char>(),
99                    name.len(),
100                )
101                .cast::<zend_function>();
102                if res.is_null() {
103                    return None;
104                }
105                Some(copy_function(res))
106            },
107        }
108    }
109
110    /// Attempts to call the callable with a list of arguments to pass to the
111    /// function.
112    ///
113    /// You should not call this function directly, rather through the
114    /// [`call_user_func`] macro.
115    ///
116    /// # Parameters
117    ///
118    /// * `params` - A list of parameters to call the function with.
119    ///
120    /// # Returns
121    ///
122    /// Returns the result wrapped in [`Ok`] upon success.
123    ///
124    /// # Errors
125    ///
126    /// * If the function call fails, an [`Err`] is returned.
127    /// * If the number of parameters is not a valid `u32` value.
128    ///
129    /// # Example
130    ///
131    /// ```no_run
132    /// use ext_php_rs::types::ZendCallable;
133    ///
134    /// let strpos = ZendCallable::try_from_name("strpos").unwrap();
135    /// let result = strpos.try_call(vec![&"hello", &"e"]).unwrap();
136    /// assert_eq!(result.long(), Some(1));
137    /// ```
138    // TODO: Measure this
139    #[allow(clippy::inline_always)]
140    #[inline(always)]
141    pub fn try_call(&self, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
142        let mut retval = Zval::new();
143        let len = params.len();
144        let params = params
145            .into_iter()
146            .map(|val| val.as_zval(false))
147            .collect::<Result<Vec<_>>>()?;
148        let packed = params.into_boxed_slice();
149
150        unsafe {
151            zend_call_known_function(
152                ptr::from_ref(self).cast_mut(),
153                ptr::null_mut(),
154                ptr::null_mut(),
155                &raw mut retval,
156                len.try_into()?,
157                packed.as_ptr().cast_mut(),
158                ptr::null_mut(),
159            );
160        };
161
162        Ok(retval)
163    }
164}
165
166/// Copies the engine's function at `func`. The engine allocates an internal
167/// function with the size of `zend_internal_function` and a user function with
168/// the size of `zend_op_array`, so only that many bytes are read. The rest of
169/// the `zend_function` union stays zeroed.
170///
171/// # Safety
172///
173/// `func` must point to a function the engine registered.
174unsafe fn copy_function(func: *const zend_function) -> Function {
175    let size = if u32::from(unsafe { (*func).type_ }) == ZEND_INTERNAL_FUNCTION {
176        size_of::<zend_internal_function>()
177    } else {
178        size_of::<zend_op_array>()
179    };
180    let mut copy = MaybeUninit::<Function>::zeroed();
181    unsafe {
182        ptr::copy_nonoverlapping(func.cast::<u8>(), copy.as_mut_ptr().cast::<u8>(), size);
183        copy.assume_init()
184    }
185}
186
187/// Parameters to mark `#[\SensitiveParameter]`: a function's name and the
188/// zero-based offsets of its sensitive parameters.
189pub(crate) type SensitiveParameters = Vec<(String, Vec<u32>)>;
190
191/// Marks each listed parameter of the functions in `table` (a class's or the
192/// engine's function table) `#[\SensitiveParameter]`, as `gen_stub.php` does
193/// for PHP's own functions, so exception traces hide their values. Names
194/// missing from `table` are skipped.
195///
196/// It must run during module startup, after the functions are registered. The
197/// attributes are allocated persistently, and the engine frees them with the
198/// functions.
199pub(crate) fn mark_sensitive(table: *const HashTable, functions: &SensitiveParameters) {
200    #[cfg(php82)]
201    {
202        use crate::{ffi::zend_add_attribute, types::ZendStr};
203
204        /// `ZEND_ATTRIBUTE_PERSISTENT`, a macro bindgen does not see.
205        const PERSISTENT: u32 = 1 << 0;
206
207        if functions.is_empty() {
208            return;
209        }
210        let mut attribute = ZendStr::new_interned("SensitiveParameter", true);
211        for (name, offsets) in functions {
212            let func = unsafe {
213                zend_hash_str_find_ptr_lc(table, name.as_ptr().cast::<c_char>(), name.len())
214            }
215            .cast::<zend_function>();
216            if func.is_null() {
217                continue;
218            }
219            for &offset in offsets {
220                unsafe {
221                    zend_add_attribute(
222                        &raw mut (*func).common.attributes,
223                        &raw mut *attribute,
224                        0,
225                        PERSISTENT,
226                        offset + 1,
227                        0,
228                    );
229                }
230            }
231        }
232    }
233    #[cfg(not(php82))]
234    let _ = (table, functions);
235}
236
237#[cfg(test)]
238#[cfg(feature = "embed")]
239mod tests {
240    use super::*;
241    use crate::embed::Embed;
242
243    #[test]
244    fn calls_an_internal_function_found_by_name() {
245        let length = Embed::run(|| {
246            Function::try_from_function("strlen")
247                .and_then(|strlen| strlen.try_call(vec![&"hello"]).ok())
248                .and_then(|retval| retval.long())
249        });
250        assert_eq!(length, Some(5));
251    }
252
253    #[test]
254    fn finds_an_internal_method_by_name() {
255        let ty = Embed::run(|| {
256            Function::try_from_method("ArrayObject", "count")
257                .and_then(|count| count.function_type().ok())
258        });
259        assert_eq!(ty, Some(FunctionType::Internal));
260    }
261}