ext_php_rs/zend/
function.rs1use 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
19pub 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 #[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
61pub type Function = zend_function;
63
64impl Function {
65 pub fn function_type(&self) -> Result<FunctionType> {
74 FunctionType::try_from(unsafe { self.type_ })
75 }
76
77 #[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 #[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 #[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
166unsafe 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
187pub(crate) type SensitiveParameters = Vec<(String, Vec<u32>)>;
190
191pub(crate) fn mark_sensitive(table: *const HashTable, functions: &SensitiveParameters) {
200 #[cfg(php82)]
201 {
202 use crate::{ffi::zend_add_attribute, types::ZendStr};
203
204 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}