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;
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 {
#[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();
}
}
}
}
pub type Function = zend_function;
impl Function {
pub fn function_type(&self) -> Result<FunctionType> {
FunctionType::try_from(unsafe { self.type_ })
}
#[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))
}
}
#[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))
},
}
}
#[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)
}
}
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()
}
}
pub(crate) type SensitiveParameters = Vec<(String, Vec<u32>)>;
pub(crate) fn mark_sensitive(table: *const HashTable, functions: &SensitiveParameters) {
#[cfg(php82)]
{
use crate::{ffi::zend_add_attribute, types::ZendStr};
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));
}
}