ext-php-rs 0.16.5

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
//! Builder for creating functions and methods in PHP.

use std::{fmt::Debug, mem::MaybeUninit, os::raw::c_char, ptr};

use crate::{
    convert::IntoZvalDyn,
    error::Result,
    ffi::{
        HashTable, ZEND_INTERNAL_FUNCTION, zend_call_known_function, zend_fetch_function_str,
        zend_function, zend_function_entry, zend_hash_str_find_ptr_lc, zend_internal_function,
        zend_op_array,
    },
    flags::{FunctionType, MethodFlags},
    types::Zval,
};

use super::ClassEntry;

/// A Zend function entry.
pub type FunctionEntry = zend_function_entry;

impl Debug for FunctionEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("_zend_function_entry")
            .field("fname", &self.fname)
            .field("arg_info", &self.arg_info)
            .field("num_args", &self.num_args)
            .field("flags", &self.flags)
            .finish()
    }
}

impl FunctionEntry {
    /// Returns an empty function entry, signifing the end of a function list.
    #[must_use]
    pub fn end() -> Self {
        Self {
            fname: ptr::null::<c_char>(),
            handler: None,
            arg_info: ptr::null(),
            num_args: 0,
            flags: 0,
            #[cfg(php84)]
            doc_comment: ptr::null(),
            #[cfg(php84)]
            frameless_function_infos: ptr::null(),
        }
    }

    pub(crate) fn add_flags(&mut self, flags: MethodFlags) {
        cfg_if::cfg_if! {
            if #[cfg(php86)] {
                self.flags |= u64::from(flags.bits());
            } else {
                self.flags |= flags.bits();
            }
        }
    }
}

/// PHP function.
pub type Function = zend_function;

impl Function {
    /// Returns the function type.
    ///
    /// # Errors
    ///
    /// * [`Error::UnknownFunctionType`] - If the engine reports a function type
    ///   this crate does not model.
    ///
    /// [`Error::UnknownFunctionType`]: crate::error::Error::UnknownFunctionType
    pub fn function_type(&self) -> Result<FunctionType> {
        FunctionType::try_from(unsafe { self.type_ })
    }

    /// Attempts to fetch a [`Function`] from the function name.
    #[inline]
    #[must_use]
    pub fn try_from_function(name: &str) -> Option<Self> {
        unsafe {
            let res = zend_fetch_function_str(name.as_ptr().cast::<c_char>(), name.len());
            if res.is_null() {
                return None;
            }
            Some(copy_function(res))
        }
    }

    /// Attempts to fetch a [`Function`] from the class and method name.
    #[must_use]
    pub fn try_from_method(class: &str, name: &str) -> Option<Self> {
        match ClassEntry::try_find(class) {
            None => None,
            Some(ce) => unsafe {
                let res = zend_hash_str_find_ptr_lc(
                    &raw const ce.function_table,
                    name.as_ptr().cast::<c_char>(),
                    name.len(),
                )
                .cast::<zend_function>();
                if res.is_null() {
                    return None;
                }
                Some(copy_function(res))
            },
        }
    }

    /// Attempts to call the callable with a list of arguments to pass to the
    /// function.
    ///
    /// You should not call this function directly, rather through the
    /// [`call_user_func`] macro.
    ///
    /// # Parameters
    ///
    /// * `params` - A list of parameters to call the function with.
    ///
    /// # Returns
    ///
    /// Returns the result wrapped in [`Ok`] upon success.
    ///
    /// # Errors
    ///
    /// * If the function call fails, an [`Err`] is returned.
    /// * If the number of parameters is not a valid `u32` value.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ext_php_rs::types::ZendCallable;
    ///
    /// let strpos = ZendCallable::try_from_name("strpos").unwrap();
    /// let result = strpos.try_call(vec![&"hello", &"e"]).unwrap();
    /// assert_eq!(result.long(), Some(1));
    /// ```
    // TODO: Measure this
    #[allow(clippy::inline_always)]
    #[inline(always)]
    pub fn try_call(&self, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
        let mut retval = Zval::new();
        let len = params.len();
        let params = params
            .into_iter()
            .map(|val| val.as_zval(false))
            .collect::<Result<Vec<_>>>()?;
        let packed = params.into_boxed_slice();

        unsafe {
            zend_call_known_function(
                ptr::from_ref(self).cast_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                &raw mut retval,
                len.try_into()?,
                packed.as_ptr().cast_mut(),
                ptr::null_mut(),
            );
        };

        Ok(retval)
    }
}

/// Copies the engine's function at `func`. The engine allocates an internal
/// function with the size of `zend_internal_function` and a user function with
/// the size of `zend_op_array`, so only that many bytes are read. The rest of
/// the `zend_function` union stays zeroed.
///
/// # Safety
///
/// `func` must point to a function the engine registered.
unsafe fn copy_function(func: *const zend_function) -> Function {
    let size = if u32::from(unsafe { (*func).type_ }) == ZEND_INTERNAL_FUNCTION {
        size_of::<zend_internal_function>()
    } else {
        size_of::<zend_op_array>()
    };
    let mut copy = MaybeUninit::<Function>::zeroed();
    unsafe {
        ptr::copy_nonoverlapping(func.cast::<u8>(), copy.as_mut_ptr().cast::<u8>(), size);
        copy.assume_init()
    }
}

/// Parameters to mark `#[\SensitiveParameter]`: a function's name and the
/// zero-based offsets of its sensitive parameters.
pub(crate) type SensitiveParameters = Vec<(String, Vec<u32>)>;

/// Marks each listed parameter of the functions in `table` (a class's or the
/// engine's function table) `#[\SensitiveParameter]`, as `gen_stub.php` does
/// for PHP's own functions, so exception traces hide their values. Names
/// missing from `table` are skipped.
///
/// It must run during module startup, after the functions are registered. The
/// attributes are allocated persistently, and the engine frees them with the
/// functions.
pub(crate) fn mark_sensitive(table: *const HashTable, functions: &SensitiveParameters) {
    #[cfg(php82)]
    {
        use crate::{ffi::zend_add_attribute, types::ZendStr};

        /// `ZEND_ATTRIBUTE_PERSISTENT`, a macro bindgen does not see.
        const PERSISTENT: u32 = 1 << 0;

        if functions.is_empty() {
            return;
        }
        let mut attribute = ZendStr::new_interned("SensitiveParameter", true);
        for (name, offsets) in functions {
            let func = unsafe {
                zend_hash_str_find_ptr_lc(table, name.as_ptr().cast::<c_char>(), name.len())
            }
            .cast::<zend_function>();
            if func.is_null() {
                continue;
            }
            for &offset in offsets {
                unsafe {
                    zend_add_attribute(
                        &raw mut (*func).common.attributes,
                        &raw mut *attribute,
                        0,
                        PERSISTENT,
                        offset + 1,
                        0,
                    );
                }
            }
        }
    }
    #[cfg(not(php82))]
    let _ = (table, functions);
}

#[cfg(test)]
#[cfg(feature = "embed")]
mod tests {
    use super::*;
    use crate::embed::Embed;

    #[test]
    fn calls_an_internal_function_found_by_name() {
        let length = Embed::run(|| {
            Function::try_from_function("strlen")
                .and_then(|strlen| strlen.try_call(vec![&"hello"]).ok())
                .and_then(|retval| retval.long())
        });
        assert_eq!(length, Some(5));
    }

    #[test]
    fn finds_an_internal_method_by_name() {
        let ty = Embed::run(|| {
            Function::try_from_method("ArrayObject", "count")
                .and_then(|count| count.function_type().ok())
        });
        assert_eq!(ty, Some(FunctionType::Internal));
    }
}