ext_php_rs/builders/function.rs
1use crate::{
2 args::{Arg, ArgInfo},
3 describe::DocComments,
4 error::{Error, Result},
5 flags::{DataType, MethodFlags},
6 types::Zval,
7 zend::{ExecuteData, FunctionEntry, ZendType},
8};
9use std::{ffi::CString, mem, ptr};
10
11/// Function representation in Rust.
12#[cfg(not(windows))]
13pub type FunctionHandler = extern "C" fn(execute_data: &mut ExecuteData, retval: &mut Zval);
14#[cfg(windows)]
15pub type FunctionHandler =
16 extern "vectorcall" fn(execute_data: &mut ExecuteData, retval: &mut Zval);
17
18/// Function representation in Rust using pointers.
19#[cfg(not(windows))]
20type FunctionPointerHandler = extern "C" fn(execute_data: *mut ExecuteData, retval: *mut Zval);
21#[cfg(windows)]
22type FunctionPointerHandler =
23 extern "vectorcall" fn(execute_data: *mut ExecuteData, retval: *mut Zval);
24
25/// Builder for registering a function in PHP.
26#[must_use]
27#[derive(Debug)]
28pub struct FunctionBuilder<'a> {
29 pub(crate) name: String,
30 function: FunctionEntry,
31 pub(crate) args: Vec<Arg<'a>>,
32 n_req: Option<usize>,
33 pub(crate) retval: Option<DataType>,
34 ret_as_ref: bool,
35 pub(crate) ret_as_null: bool,
36 pub(crate) docs: DocComments,
37}
38
39impl<'a> FunctionBuilder<'a> {
40 /// Creates a new function builder, used to build functions
41 /// to be exported to PHP.
42 ///
43 /// # Parameters
44 ///
45 /// * `name` - The name of the function.
46 /// * `handler` - The handler to be called when the function is invoked from
47 /// PHP.
48 pub fn new<T: Into<String>>(name: T, handler: FunctionHandler) -> Self {
49 Self {
50 name: name.into(),
51 function: FunctionEntry {
52 fname: ptr::null(),
53 // SAFETY: `*mut T` and `&mut T` have the same ABI as long as `*mut T` is non-null,
54 // aligned and pointing to a `T`. PHP guarantees that these conditions will be met.
55 handler: Some(unsafe {
56 mem::transmute::<FunctionHandler, FunctionPointerHandler>(handler)
57 }),
58 arg_info: ptr::null(),
59 num_args: 0,
60 flags: 0, // TBD?
61 #[cfg(php84)]
62 doc_comment: ptr::null(),
63 #[cfg(php84)]
64 frameless_function_infos: ptr::null(),
65 },
66 args: vec![],
67 n_req: None,
68 retval: None,
69 ret_as_ref: false,
70 ret_as_null: false,
71 docs: &[],
72 }
73 }
74
75 /// Create a new function builder for an abstract function that can be used
76 /// on an abstract class or an interface.
77 ///
78 /// # Parameters
79 ///
80 /// * `name` - The name of the function.
81 pub fn new_abstract<T: Into<String>>(name: T) -> Self {
82 let mut function = FunctionEntry::end();
83 function.add_flags(MethodFlags::Abstract);
84 Self {
85 name: name.into(),
86 function,
87 args: vec![],
88 n_req: None,
89 retval: None,
90 ret_as_ref: false,
91 ret_as_null: false,
92 docs: &[],
93 }
94 }
95
96 /// Creates a constructor builder, used to build the constructor
97 /// for classes.
98 ///
99 /// # Parameters
100 ///
101 /// * `handler` - The handler to be called when the function is invoked from
102 /// PHP.
103 pub fn constructor(handler: FunctionHandler) -> Self {
104 Self::new("__construct", handler)
105 }
106
107 /// The function's name and the zero-based offsets of its arguments marked
108 /// [`sensitive`](Arg::sensitive), or `None` when it has none.
109 pub(crate) fn sensitive(&self) -> Option<(String, Vec<u32>)> {
110 let offsets: Vec<u32> = self
111 .args
112 .iter()
113 .zip(0u32..)
114 .filter(|(arg, _)| arg.sensitive)
115 .map(|(_, offset)| offset)
116 .collect();
117 (!offsets.is_empty()).then(|| (self.name.clone(), offsets))
118 }
119
120 /// Adds an argument to the function.
121 ///
122 /// # Parameters
123 ///
124 /// * `arg` - The argument to add to the function.
125 pub fn arg(mut self, arg: Arg<'a>) -> Self {
126 self.args.push(arg);
127 self
128 }
129
130 /// Sets the rest of the given arguments as not required.
131 pub fn not_required(mut self) -> Self {
132 self.n_req = Some(self.args.len());
133 self
134 }
135
136 /// Sets how many leading arguments are required, see
137 /// [`required_count`](crate::args::required_count).
138 pub fn required_args(mut self, count: usize) -> Self {
139 self.n_req = Some(count);
140 self
141 }
142
143 /// Sets the return value of the function.
144 ///
145 /// # Parameters
146 ///
147 /// * `type_` - The return type of the function.
148 /// * `as_ref` - Whether the function returns a reference.
149 /// * `allow_null` - Whether the function return value is nullable.
150 pub fn returns(mut self, type_: DataType, as_ref: bool, allow_null: bool) -> Self {
151 self.retval = Some(type_);
152 self.ret_as_ref = as_ref;
153 self.ret_as_null = allow_null && type_ != DataType::Void && type_ != DataType::Mixed;
154 self
155 }
156
157 /// Sets the documentation for the function.
158 /// This is used to generate the PHP stubs for the function.
159 ///
160 /// # Parameters
161 ///
162 /// * `docs` - The documentation for the function.
163 pub fn docs(mut self, docs: DocComments) -> Self {
164 self.docs = docs;
165 self
166 }
167
168 /// Builds the function converting it into a Zend function entry.
169 ///
170 /// Returns a result containing the function entry if successful.
171 ///
172 /// # Errors
173 ///
174 /// * `Error::InvalidCString` - If the function name is not a valid C
175 /// string.
176 /// * `Error::IntegerOverflow` - If the number of arguments is too large.
177 /// * If arg info for an argument could not be created.
178 /// * If the function name contains NUL bytes.
179 ///
180 /// # Ownership
181 ///
182 /// The returned `Box<[ArgInfo]>` is what `FunctionEntry::arg_info` points at.
183 /// The Zend engine borrows it for the life of the process, so the caller must
184 /// park it somewhere that lives that long — see `ClassMetadata::arg_info` and
185 /// `StaticModuleEntry`. Dropping it dangles the registered function.
186 pub fn build(mut self) -> Result<(FunctionEntry, Box<[ArgInfo]>)> {
187 let mut args = Vec::with_capacity(self.args.len() + 1);
188 let mut n_req = self.n_req.unwrap_or(self.args.len());
189 let variadic = self.args.last().is_some_and(|arg| arg.variadic);
190
191 if variadic {
192 self.function.add_flags(MethodFlags::Variadic);
193 n_req = n_req.saturating_sub(1);
194 }
195
196 // argument header, retval etc
197 // The first argument is used as `zend_internal_function_info` for the function.
198 // That struct shares the same memory as `zend_internal_arg_info` which is used
199 // for the arguments.
200 args.push(ArgInfo {
201 // required_num_args
202 name: n_req as *const _,
203 type_: match self.retval {
204 Some(retval) => {
205 ZendType::empty_from_type(retval, self.ret_as_ref, false, self.ret_as_null)
206 .ok_or(Error::ZvalConversion(retval))?
207 }
208 None => ZendType::empty(false, false),
209 },
210 default_value: ptr::null(),
211 });
212
213 // arguments
214 args.extend(
215 self.args
216 .iter()
217 .enumerate()
218 .map(|(i, arg)| arg.as_arg_info(i >= n_req))
219 .collect::<Result<Vec<_>>>()?,
220 );
221
222 self.function.fname = CString::new(self.name)?.into_raw();
223 self.function.num_args = (args.len() - 1).try_into()?;
224
225 let args = args.into_boxed_slice();
226 self.function.arg_info = args.as_ptr();
227
228 Ok((self.function, args))
229 }
230}
231
232/// Frees a [`FunctionEntry`] table once the Zend engine has consumed it.
233///
234/// `zend_register_functions` interns every `fname`, and
235/// `do_register_internal_class` reads `zend_class_entry.info.internal.builtin_functions`
236/// exactly once and never frees it, so a class or enum method table is dead as
237/// soon as registration returns.
238///
239/// The `arg_info` arrays are deliberately left alone. The engine's copy of them
240/// is shallow, so `arg_info[i].name` and `.default_value` stay live for
241/// `ReflectionParameter`, and a function with no parameters and no return type
242/// keeps the array itself. They are owned by `ClassMetadata` or
243/// [`ModuleAllocations`](crate::zend::ModuleAllocations) instead.
244///
245/// # Safety
246///
247/// * `entries` must come from `Box::into_raw` on a NUL-terminated
248/// `Box<[FunctionEntry]>` whose entries were built by
249/// [`FunctionBuilder::build`].
250/// * Must be called exactly once, after the `zend_register_*` call that
251/// consumed the table.
252/// * Must never be called on a [`ModuleEntry::functions`] table: PHP re-reads
253/// that one from `module_destructor` after MSHUTDOWN and from
254/// `get_extension_funcs()` during a request.
255///
256/// [`ModuleEntry::functions`]: crate::zend::ModuleEntry
257pub(crate) unsafe fn free_registered_entries(entries: *mut [FunctionEntry]) {
258 let entries = unsafe { Box::from_raw(entries) };
259 for entry in &*entries {
260 if !entry.fname.is_null() {
261 drop(unsafe { CString::from_raw(entry.fname.cast_mut()) });
262 }
263 }
264}