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 /// The other members of a union return type, see
35 /// [`FunctionBuilder::or_returns`].
36 ret_union: Vec<DataType>,
37 ret_as_ref: bool,
38 pub(crate) ret_as_null: bool,
39 pub(crate) docs: DocComments,
40}
41
42impl<'a> FunctionBuilder<'a> {
43 /// Creates a new function builder, used to build functions
44 /// to be exported to PHP.
45 ///
46 /// # Parameters
47 ///
48 /// * `name` - The name of the function.
49 /// * `handler` - The handler to be called when the function is invoked from
50 /// PHP.
51 pub fn new<T: Into<String>>(name: T, handler: FunctionHandler) -> Self {
52 Self {
53 name: name.into(),
54 function: FunctionEntry {
55 fname: ptr::null(),
56 // SAFETY: `*mut T` and `&mut T` have the same ABI as long as `*mut T` is non-null,
57 // aligned and pointing to a `T`. PHP guarantees that these conditions will be met.
58 handler: Some(unsafe {
59 mem::transmute::<FunctionHandler, FunctionPointerHandler>(handler)
60 }),
61 arg_info: ptr::null(),
62 num_args: 0,
63 flags: 0, // TBD?
64 #[cfg(php84)]
65 doc_comment: ptr::null(),
66 #[cfg(php84)]
67 frameless_function_infos: ptr::null(),
68 },
69 args: vec![],
70 n_req: None,
71 retval: None,
72 ret_union: Vec::new(),
73 ret_as_ref: false,
74 ret_as_null: false,
75 docs: &[],
76 }
77 }
78
79 /// Create a new function builder for an abstract function that can be used
80 /// on an abstract class or an interface.
81 ///
82 /// # Parameters
83 ///
84 /// * `name` - The name of the function.
85 pub fn new_abstract<T: Into<String>>(name: T) -> Self {
86 let mut function = FunctionEntry::end();
87 function.add_flags(MethodFlags::Abstract);
88 Self {
89 name: name.into(),
90 function,
91 args: vec![],
92 n_req: None,
93 retval: None,
94 ret_union: Vec::new(),
95 ret_as_ref: false,
96 ret_as_null: false,
97 docs: &[],
98 }
99 }
100
101 /// Creates a constructor builder, used to build the constructor
102 /// for classes.
103 ///
104 /// # Parameters
105 ///
106 /// * `handler` - The handler to be called when the function is invoked from
107 /// PHP.
108 pub fn constructor(handler: FunctionHandler) -> Self {
109 Self::new("__construct", handler)
110 }
111
112 /// The function's name and the zero-based offsets of its arguments marked
113 /// [`sensitive`](Arg::sensitive), or `None` when it has none.
114 pub(crate) fn sensitive(&self) -> Option<(String, Vec<u32>)> {
115 let offsets: Vec<u32> = self
116 .args
117 .iter()
118 .zip(0u32..)
119 .filter(|(arg, _)| arg.sensitive)
120 .map(|(_, offset)| offset)
121 .collect();
122 (!offsets.is_empty()).then(|| (self.name.clone(), offsets))
123 }
124
125 /// Adds an argument to the function.
126 ///
127 /// # Parameters
128 ///
129 /// * `arg` - The argument to add to the function.
130 pub fn arg(mut self, arg: Arg<'a>) -> Self {
131 self.args.push(arg);
132 self
133 }
134
135 /// Sets the rest of the given arguments as not required.
136 pub fn not_required(mut self) -> Self {
137 self.n_req = Some(self.args.len());
138 self
139 }
140
141 /// Sets how many leading arguments are required, see
142 /// [`required_count`](crate::args::required_count).
143 pub fn required_args(mut self, count: usize) -> Self {
144 self.n_req = Some(count);
145 self
146 }
147
148 /// Adds `type_` to the return type set with [`FunctionBuilder::returns`],
149 /// making it a union: `.returns(DataType::Long, false, false)
150 /// .or_returns(DataType::Double)` declares `: int|float`. The types are
151 /// those [`Arg::or`](crate::args::Arg::or) accepts; any other, or a union
152 /// without [`FunctionBuilder::returns`], fails [`FunctionBuilder::build`]
153 /// with [`Error::InvalidUnionType`].
154 ///
155 /// Debug builds of PHP check an internal function's return value against
156 /// its declared type and assert on a mismatch: the handler must return a
157 /// value of the union (`null` only when it holds `null`), including when
158 /// it throws on bad input.
159 pub fn or_returns(mut self, type_: DataType) -> Self {
160 self.ret_union.push(type_);
161 self
162 }
163
164 /// Sets the return value of the function.
165 ///
166 /// # Parameters
167 ///
168 /// * `type_` - The return type of the function.
169 /// * `as_ref` - Whether the function returns a reference.
170 /// * `allow_null` - Whether the function return value is nullable.
171 pub fn returns(mut self, type_: DataType, as_ref: bool, allow_null: bool) -> Self {
172 self.retval = Some(type_);
173 self.ret_as_ref = as_ref;
174 self.ret_as_null = allow_null && type_ != DataType::Void && type_ != DataType::Mixed;
175 self
176 }
177
178 /// Sets the documentation for the function.
179 /// This is used to generate the PHP stubs for the function.
180 ///
181 /// # Parameters
182 ///
183 /// * `docs` - The documentation for the function.
184 pub fn docs(mut self, docs: DocComments) -> Self {
185 self.docs = docs;
186 self
187 }
188
189 /// Builds the function converting it into a Zend function entry.
190 ///
191 /// Returns a result containing the function entry if successful.
192 ///
193 /// # Errors
194 ///
195 /// * `Error::InvalidCString` - If the function name is not a valid C
196 /// string.
197 /// * `Error::IntegerOverflow` - If the number of arguments is too large.
198 /// * If arg info for an argument could not be created.
199 /// * If the function name contains NUL bytes.
200 ///
201 /// # Ownership
202 ///
203 /// The returned `Box<[ArgInfo]>` is what `FunctionEntry::arg_info` points at.
204 /// The Zend engine borrows it for the life of the process, so the caller must
205 /// park it somewhere that lives that long — see `ClassMetadata::arg_info` and
206 /// `StaticModuleEntry`. Dropping it dangles the registered function.
207 pub fn build(mut self) -> Result<(FunctionEntry, Box<[ArgInfo]>)> {
208 let mut args = Vec::with_capacity(self.args.len() + 1);
209 let mut n_req = self.n_req.unwrap_or(self.args.len());
210 let variadic = self.args.last().is_some_and(|arg| arg.variadic);
211
212 if variadic {
213 self.function.add_flags(MethodFlags::Variadic);
214 n_req = n_req.saturating_sub(1);
215 }
216
217 // argument header, retval etc
218 // The first argument is used as `zend_internal_function_info` for the function.
219 // That struct shares the same memory as `zend_internal_arg_info` which is used
220 // for the arguments.
221 args.push(ArgInfo {
222 // required_num_args
223 name: n_req as *const _,
224 type_: match self.retval {
225 Some(retval) => {
226 let mut type_ =
227 ZendType::empty_from_type(retval, self.ret_as_ref, false, self.ret_as_null)
228 .ok_or(Error::ZvalConversion(retval))?;
229 ZendType::add_union(
230 &mut type_,
231 &format!("{}()", self.name),
232 retval,
233 &self.ret_union,
234 )?;
235 type_
236 }
237 None if !self.ret_union.is_empty() => {
238 return Err(Error::InvalidUnionType(format!(
239 "{}(): or_returns without a return type to join",
240 self.name
241 )));
242 }
243 None => ZendType::empty(false, false),
244 },
245 default_value: ptr::null(),
246 });
247
248 // arguments
249 args.extend(
250 self.args
251 .iter()
252 .enumerate()
253 .map(|(i, arg)| arg.as_arg_info(i >= n_req))
254 .collect::<Result<Vec<_>>>()?,
255 );
256
257 self.function.fname = CString::new(self.name)?.into_raw();
258 self.function.num_args = (args.len() - 1).try_into()?;
259
260 let args = args.into_boxed_slice();
261 self.function.arg_info = args.as_ptr();
262
263 Ok((self.function, args))
264 }
265}
266
267/// Frees a [`FunctionEntry`] table once the Zend engine has consumed it.
268///
269/// `zend_register_functions` interns every `fname`, and
270/// `do_register_internal_class` reads `zend_class_entry.info.internal.builtin_functions`
271/// exactly once and never frees it, so a class or enum method table is dead as
272/// soon as registration returns.
273///
274/// The `arg_info` arrays are deliberately left alone. The engine's copy of them
275/// is shallow, so `arg_info[i].name` and `.default_value` stay live for
276/// `ReflectionParameter`, and a function with no parameters and no return type
277/// keeps the array itself. They are owned by `ClassMetadata` or
278/// [`ModuleAllocations`](crate::zend::ModuleAllocations) instead.
279///
280/// # Safety
281///
282/// * `entries` must come from `Box::into_raw` on a NUL-terminated
283/// `Box<[FunctionEntry]>` whose entries were built by
284/// [`FunctionBuilder::build`].
285/// * Must be called exactly once, after the `zend_register_*` call that
286/// consumed the table.
287/// * Must never be called on a [`ModuleEntry::functions`] table: PHP re-reads
288/// that one from `module_destructor` after MSHUTDOWN and from
289/// `get_extension_funcs()` during a request.
290///
291/// [`ModuleEntry::functions`]: crate::zend::ModuleEntry
292pub(crate) unsafe fn free_registered_entries(entries: *mut [FunctionEntry]) {
293 let entries = unsafe { Box::from_raw(entries) };
294 for entry in &*entries {
295 if !entry.fname.is_null() {
296 drop(unsafe { CString::from_raw(entry.fname.cast_mut()) });
297 }
298 }
299}
300
301#[cfg(test)]
302mod union_tests {
303 use super::*;
304 use crate::test::test_function;
305
306 #[test]
307 fn or_returns_without_a_return_type_is_refused() {
308 let built = FunctionBuilder::new("f", test_function)
309 .or_returns(DataType::Long)
310 .build();
311 assert!(matches!(built, Err(Error::InvalidUnionType(message)) if message.contains("f()")));
312 }
313
314 #[test]
315 fn a_union_return_type_ors_the_members() {
316 let (entry, info) = FunctionBuilder::new("f", test_function)
317 .returns(DataType::Long, false, false)
318 .or_returns(DataType::Double)
319 .build()
320 .expect("a union of scalar types");
321 // `build` hands the name to the engine; nothing registers it here.
322 drop(unsafe { std::ffi::CString::from_raw(entry.fname.cast_mut()) });
323 assert_eq!(
324 info[0].type_.type_mask,
325 (1 << crate::ffi::IS_LONG) | (1 << crate::ffi::IS_DOUBLE)
326 );
327 }
328}