Skip to main content

speedyspec_php/
native.rs

1//! Native functions written as plain Rust closures over [`Value`]s.
2//!
3//! [`function`] builds a PHP function whose arguments arrive converted (objects and closures as `Value::Opaque`) and
4//! whose result or [`NativeError`] goes back to PHP. [`raw_function`] builds one that gets its arguments unconverted
5//! ([`Args`]): it converts only what it reads and passes the rest through as the zvals PHP gave it, for functions on
6//! a hot path. Every one runs through the same dispatcher, which finds the handler by the called function (by name
7//! the first time, then by the function itself) and goes through `boundary::native_entry`, so bailouts and panics
8//! never cross Rust frames. An area uses them from [`crate::NativeArea::functions`].
9
10use std::cell::RefCell;
11use std::collections::HashMap;
12use std::ffi::CString;
13use std::rc::Rc;
14
15use ext_php_rs::args::Arg;
16use ext_php_rs::builders::FunctionBuilder;
17use ext_php_rs::ffi::{
18    IS_ARRAY, IS_FALSE, IS_LONG, IS_OBJECT, ext_php_rs_executor_globals, zend_ce_exception,
19    zend_class_entry, zend_hash_index_find, zend_hash_str_find, zend_throw_exception, zval,
20};
21use ext_php_rs::flags::DataType;
22use ext_php_rs::types::Zval;
23use ext_php_rs::zend::ExecuteData;
24use speedyspec_hooks::Value;
25
26use crate::boundary;
27use crate::convert;
28
29/// How a native function fails in PHP.
30#[derive(Clone, Debug, PartialEq)]
31pub enum NativeError {
32    /// Throws `new $class($message)`; `\Exception` when the class is not declared.
33    Throw { class: String, message: String },
34    /// Rethrows a PHP exception object (a `Value::Opaque` from [`crate::call_catching`]).
35    Rethrow(Value),
36    /// PHP is unwinding (a bailout or `exit()`); throw nothing.
37    Silent,
38}
39
40impl NativeError {
41    pub fn throw(class: &str, message: impl Into<String>) -> NativeError {
42        NativeError::Throw {
43            class: class.to_owned(),
44            message: message.into(),
45        }
46    }
47}
48
49/// A native function's body: the arguments it was given, converted.
50pub type Handler = Rc<dyn Fn(&[Value]) -> Result<Value, NativeError>>;
51
52/// A native function's body that reads its arguments itself ([`Args`]).
53pub type RawHandler = Rc<dyn Fn(&Args<'_>) -> Result<Value, NativeError>>;
54
55#[derive(Clone)]
56enum Body {
57    Converted(Handler),
58    Raw(RawHandler),
59}
60
61thread_local! {
62    static HANDLERS: RefCell<HashMap<String, Body>> = RefCell::new(HashMap::new());
63    /// The handlers already found, by the called `zend_function` (internal functions live as long as the process).
64    static BY_FUNCTION: RefCell<HashMap<usize, Body>> = RefCell::new(HashMap::new());
65}
66
67fn register(name: &str, body: Body) -> FunctionBuilder<'static> {
68    HANDLERS.with(|h| h.borrow_mut().insert(name.to_ascii_lowercase(), body));
69    BY_FUNCTION.with(|h| h.borrow_mut().clear());
70    FunctionBuilder::new(name, dispatch)
71        .arg(Arg::new("args", DataType::Mixed).is_variadic())
72        .returns(DataType::Mixed, false, true)
73}
74
75/// A PHP function `name` (namespaced names allowed) that takes any arguments and runs `handler`.
76pub fn function(
77    name: &str,
78    handler: impl Fn(&[Value]) -> Result<Value, NativeError> + 'static,
79) -> FunctionBuilder<'static> {
80    register(name, Body::Converted(Rc::new(handler)))
81}
82
83/// A PHP function `name` that takes any arguments and runs `handler` over them unconverted. What it returns goes
84/// back to PHP; a value it passed through ([`Args::pass`]) goes back as the very same zval.
85pub fn raw_function(
86    name: &str,
87    handler: impl Fn(&Args<'_>) -> Result<Value, NativeError> + 'static,
88) -> FunctionBuilder<'static> {
89    register(name, Body::Raw(Rc::new(handler)))
90}
91
92/// The arguments of a [`raw_function`] call, as PHP passed them. Each accessor reads one argument; nothing is
93/// converted unless asked for.
94pub struct Args<'a> {
95    ex: &'a ExecuteData,
96    count: usize,
97}
98
99impl Args<'_> {
100    pub fn len(&self) -> usize {
101        self.count
102    }
103
104    pub fn is_empty(&self) -> bool {
105        self.count == 0
106    }
107
108    /// The `i`th argument's zval, references followed; `None` past the last argument.
109    fn slot(&self, i: usize) -> Option<*const zval> {
110        if i >= self.count {
111            return None;
112        }
113        // SAFETY: `i < num_args`, so the slot is inside the live frame.
114        let zv = unsafe { self.ex.zend_call_arg(i) }?;
115        // SAFETY: a live argument slot.
116        Some(unsafe { convert::deref(&raw const *zv) })
117    }
118
119    /// The `i`th argument converted, for Rust to read (`Value::Null` when it was not passed).
120    pub fn value(&self, i: usize) -> Result<Value, NativeError> {
121        let Some(zv) = self.slot(i) else {
122            return Ok(Value::Null);
123        };
124        // SAFETY: a live argument slot; the conversion takes its own references.
125        unsafe { convert::to_value(zv) }.map_err(|why| {
126            NativeError::throw(
127                "TypeError",
128                format!(
129                    "{}(): Argument #{} cannot be passed to Rust: {why}",
130                    frame(self.ex).0,
131                    i + 1
132                ),
133            )
134        })
135    }
136
137    /// The `i`th argument passed through unconverted (`Value::Null` when it was not passed).
138    pub fn pass(&self, i: usize) -> Value {
139        match self.slot(i) {
140            // SAFETY: a live argument slot; the handle takes its own reference.
141            Some(zv) => unsafe { convert::pass_through(zv) },
142            None => Value::Null,
143        }
144    }
145
146    /// Every argument from the `i`th on, passed through.
147    pub fn pass_from(&self, i: usize) -> Vec<Value> {
148        (i..self.count).map(|i| self.pass(i)).collect()
149    }
150
151    /// The elements of the `i`th argument, an array, each passed through, in order (empty when it is not an
152    /// array).
153    pub fn items(&self, i: usize) -> Vec<Value> {
154        let Some(zv) = self.slot(i) else {
155            return Vec::new();
156        };
157        // SAFETY: a live argument slot; an array zval's `arr` is its live table.
158        unsafe {
159            if u32::from(convert::type_of(zv)) != IS_ARRAY {
160                return Vec::new();
161            }
162            convert::array_values((*zv).value.arr)
163                .into_iter()
164                .map(|slot| convert::pass_through(slot))
165                .collect()
166        }
167    }
168
169    /// The hash PHP keeps for the `i`th argument, a string; `None` for anything else.
170    pub fn string_hash(&self, i: usize) -> Option<u64> {
171        // SAFETY: a live argument slot.
172        self.slot(i)
173            .and_then(|zv| unsafe { convert::string_hash(zv) })
174    }
175
176    /// The `i`th argument if it is an integer.
177    pub fn int(&self, i: usize) -> Option<i64> {
178        let zv = self.slot(i)?;
179        // SAFETY: a live argument slot.
180        unsafe { (u32::from(convert::type_of(zv)) == IS_LONG).then(|| (*zv).value.lval) }
181    }
182
183    /// True when the `i`th argument is `false`.
184    pub fn is_false(&self, i: usize) -> bool {
185        // SAFETY: a live argument slot.
186        self.slot(i)
187            .is_some_and(|zv| unsafe { u32::from(convert::type_of(zv)) == IS_FALSE })
188    }
189
190    /// The object of an `i`th argument that is `[$object]` (an array of one object, at key 0).
191    pub fn single_object(&self, i: usize) -> Option<Value> {
192        let zv = self.slot(i)?;
193        // SAFETY: a live argument slot; an array zval's `arr` is its live table, whose slot at index 0 is live.
194        unsafe {
195            if u32::from(convert::type_of(zv)) != IS_ARRAY {
196                return None;
197            }
198            let ht = (*zv).value.arr;
199            if (*ht).nNumOfElements != 1 {
200                return None;
201            }
202            let first = zend_hash_index_find(ht, 0);
203            if first.is_null() {
204                return None;
205            }
206            let first = convert::deref(first);
207            (u32::from(convert::type_of(first)) == IS_OBJECT).then(|| convert::pass_through(first))
208        }
209    }
210}
211
212extern "C" fn dispatch(ex: &mut ExecuteData, retval: &mut Zval) {
213    boundary::native_entry(ex, retval, dispatch_body);
214}
215
216/// The handler of the called function.
217fn body_of(ex: &ExecuteData) -> Result<Body, String> {
218    let func = ex.func as usize;
219    if let Some(body) = BY_FUNCTION.with(|h| h.borrow().get(&func).cloned()) {
220        return Ok(body);
221    }
222    let (name, _) = frame(ex);
223    let body = HANDLERS
224        .with(|h| h.borrow().get(&name.to_ascii_lowercase()).cloned())
225        .ok_or(name)?;
226    BY_FUNCTION.with(|h| h.borrow_mut().insert(func, body.clone()));
227    Ok(body)
228}
229
230fn dispatch_body(ex: &mut ExecuteData, retval: &mut Zval) {
231    let body = match body_of(ex) {
232        Ok(body) => body,
233        Err(name) => {
234            throw(NativeError::throw(
235                "Error",
236                format!("{name}() has no native handler"),
237            ));
238            return;
239        }
240    };
241    let result = match body {
242        Body::Raw(handler) => {
243            // SAFETY: all members of `This.u2` are the same u32.
244            let count = unsafe { ex.This.u2.num_args } as usize;
245            handler(&Args { ex, count })
246        }
247        Body::Converted(handler) => match converted_args(ex) {
248            Ok(args) => handler(&args),
249            Err(err) => Err(err),
250        },
251    };
252    write_result(ex, retval, result);
253}
254
255/// The arguments of a [`function`], converted.
256fn converted_args(ex: &ExecuteData) -> Result<Vec<Value>, NativeError> {
257    let (name, count) = frame(ex);
258    let mut args = Vec::with_capacity(count);
259    for i in 0..count {
260        // SAFETY: `i < num_args`, so the slot is inside the live frame.
261        let Some(zv) = (unsafe { ex.zend_call_arg(i) }) else {
262            args.push(Value::Null);
263            continue;
264        };
265        // SAFETY: a live argument slot, dereferenced; the conversion takes its own references.
266        match unsafe { convert::to_value(convert::deref(&raw const *zv)) } {
267            Ok(value) => args.push(value),
268            Err(why) => {
269                return Err(NativeError::throw(
270                    "TypeError",
271                    format!(
272                        "{name}(): Argument #{} cannot be passed to Rust: {why}",
273                        i + 1
274                    ),
275                ));
276            }
277        }
278    }
279    Ok(args)
280}
281
282/// Hands a handler's result (or error) to PHP.
283fn write_result(ex: &ExecuteData, retval: &mut Zval, result: Result<Value, NativeError>) {
284    match result {
285        Ok(value) => {
286            let out: *mut zval = retval;
287            // SAFETY: the engine set `retval` to null before calling us.
288            if unsafe { convert::write_without_engine(out, &value) } {
289                return;
290            }
291            let written = boundary::guard(|| {
292                // SAFETY: the engine set `retval` to null before calling us; `value` is owned by this frame.
293                unsafe { convert::write_value(out, &value) }
294            });
295            if let Ok(Err(why)) = written {
296                let (name, _) = frame(ex);
297                throw(NativeError::throw(
298                    "Error",
299                    format!("{name}(): the result cannot be returned to PHP: {why}"),
300                ));
301            }
302        }
303        Err(err) => throw(err),
304    }
305}
306
307/// The called function's name and argument count.
308fn frame(ex: &ExecuteData) -> (String, usize) {
309    // SAFETY: PHP called us with a live frame whose `func` is this function; all members of `This.u2` are the same
310    // u32.
311    unsafe {
312        let func = ex.func;
313        let mut name = String::new();
314        if !func.is_null() {
315            let fname = (*func).common.function_name;
316            if !fname.is_null() {
317                name = String::from_utf8_lossy(convert::str_bytes(fname)).into_owned();
318            }
319        }
320        (name, ex.This.u2.num_args as usize)
321    }
322}
323
324fn throw(err: NativeError) {
325    let (class, message) = match err {
326        NativeError::Throw { class, message } => (class, message),
327        NativeError::Rethrow(object) => {
328            if let Some(handle) = convert::handle_of(&object) {
329                // SAFETY: a live handle; the copy takes its own reference, which the engine takes over.
330                let copy = unsafe { convert::ZvalHandle::copy_of(handle.as_ptr()) };
331                boundary::rethrow(copy);
332            }
333            return;
334        }
335        NativeError::Silent => return,
336    };
337    if !boundary::can_enter() {
338        return;
339    }
340    let ce = find_class(&class);
341    let message = CString::new(message.replace('\0', "\\0")).unwrap_or_default();
342    let message_ptr = message.as_ptr();
343    let _ = boundary::guard(|| {
344        // SAFETY: throwing from inside a native function, with a message owned by the enclosing frame.
345        unsafe { zend_throw_exception(ce, message_ptr, 0) };
346    });
347}
348
349/// A declared class by name (no autoloading), or `\Exception`.
350fn find_class(name: &str) -> *mut zend_class_entry {
351    let key = name.trim_start_matches('\\').to_ascii_lowercase();
352    // SAFETY: a request is open, so the class table is live; it holds class entries as IS_PTR zvals.
353    unsafe {
354        let table = (*ext_php_rs_executor_globals()).class_table;
355        let zv = zend_hash_str_find(table, key.as_ptr().cast(), key.len());
356        if zv.is_null() {
357            zend_ce_exception
358        } else {
359            (*zv).value.ce
360        }
361    }
362}