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). An element that is a PHP reference (`array( &$var )`) stays one, so a callback given it changes the
153    /// variable.
154    pub fn items(&self, i: usize) -> Vec<Value> {
155        let Some(zv) = self.slot(i) else {
156            return Vec::new();
157        };
158        // SAFETY: a live argument slot; an array zval's `arr` is its live table.
159        unsafe {
160            if u32::from(convert::type_of(zv)) != IS_ARRAY {
161                return Vec::new();
162            }
163            convert::array_values((*zv).value.arr)
164                .into_iter()
165                .map(|slot| convert::pass_through_slot(slot))
166                .collect()
167        }
168    }
169
170    /// The hash PHP keeps for the `i`th argument, a string; `None` for anything else.
171    pub fn string_hash(&self, i: usize) -> Option<u64> {
172        // SAFETY: a live argument slot.
173        self.slot(i)
174            .and_then(|zv| unsafe { convert::string_hash(zv) })
175    }
176
177    /// The `i`th argument if it is an integer.
178    pub fn int(&self, i: usize) -> Option<i64> {
179        let zv = self.slot(i)?;
180        // SAFETY: a live argument slot.
181        unsafe { (u32::from(convert::type_of(zv)) == IS_LONG).then(|| (*zv).value.lval) }
182    }
183
184    /// True when the `i`th argument is `false`.
185    pub fn is_false(&self, i: usize) -> bool {
186        // SAFETY: a live argument slot.
187        self.slot(i)
188            .is_some_and(|zv| unsafe { u32::from(convert::type_of(zv)) == IS_FALSE })
189    }
190
191    /// The object of an `i`th argument that is `[$object]` (an array of one object, at key 0).
192    pub fn single_object(&self, i: usize) -> Option<Value> {
193        let zv = self.slot(i)?;
194        // SAFETY: a live argument slot; an array zval's `arr` is its live table, whose slot at index 0 is live.
195        unsafe {
196            if u32::from(convert::type_of(zv)) != IS_ARRAY {
197                return None;
198            }
199            let ht = (*zv).value.arr;
200            if (*ht).nNumOfElements != 1 {
201                return None;
202            }
203            let first = zend_hash_index_find(ht, 0);
204            if first.is_null() {
205                return None;
206            }
207            let first = convert::deref(first);
208            (u32::from(convert::type_of(first)) == IS_OBJECT).then(|| convert::pass_through(first))
209        }
210    }
211}
212
213extern "C" fn dispatch(ex: &mut ExecuteData, retval: &mut Zval) {
214    boundary::native_entry(ex, retval, dispatch_body);
215}
216
217/// The handler of the called function.
218fn body_of(ex: &ExecuteData) -> Result<Body, String> {
219    let func = ex.func as usize;
220    if let Some(body) = BY_FUNCTION.with(|h| h.borrow().get(&func).cloned()) {
221        return Ok(body);
222    }
223    let (name, _) = frame(ex);
224    let body = HANDLERS
225        .with(|h| h.borrow().get(&name.to_ascii_lowercase()).cloned())
226        .ok_or(name)?;
227    BY_FUNCTION.with(|h| h.borrow_mut().insert(func, body.clone()));
228    Ok(body)
229}
230
231fn dispatch_body(ex: &mut ExecuteData, retval: &mut Zval) {
232    let body = match body_of(ex) {
233        Ok(body) => body,
234        Err(name) => {
235            throw(NativeError::throw(
236                "Error",
237                format!("{name}() has no native handler"),
238            ));
239            return;
240        }
241    };
242    let result = match body {
243        Body::Raw(handler) => {
244            // SAFETY: all members of `This.u2` are the same u32.
245            let count = unsafe { ex.This.u2.num_args } as usize;
246            handler(&Args { ex, count })
247        }
248        Body::Converted(handler) => match converted_args(ex) {
249            Ok(args) => handler(&args),
250            Err(err) => Err(err),
251        },
252    };
253    write_result(ex, retval, result);
254}
255
256/// The arguments of a [`function`], converted.
257fn converted_args(ex: &ExecuteData) -> Result<Vec<Value>, NativeError> {
258    let (name, count) = frame(ex);
259    let mut args = Vec::with_capacity(count);
260    for i in 0..count {
261        // SAFETY: `i < num_args`, so the slot is inside the live frame.
262        let Some(zv) = (unsafe { ex.zend_call_arg(i) }) else {
263            args.push(Value::Null);
264            continue;
265        };
266        // SAFETY: a live argument slot, dereferenced; the conversion takes its own references.
267        match unsafe { convert::to_value(convert::deref(&raw const *zv)) } {
268            Ok(value) => args.push(value),
269            Err(why) => {
270                return Err(NativeError::throw(
271                    "TypeError",
272                    format!(
273                        "{name}(): Argument #{} cannot be passed to Rust: {why}",
274                        i + 1
275                    ),
276                ));
277            }
278        }
279    }
280    Ok(args)
281}
282
283/// Hands a handler's result (or error) to PHP.
284fn write_result(ex: &ExecuteData, retval: &mut Zval, result: Result<Value, NativeError>) {
285    match result {
286        Ok(value) => {
287            let out: *mut zval = retval;
288            // SAFETY: the engine set `retval` to null before calling us.
289            if unsafe { convert::write_without_engine(out, &value) } {
290                return;
291            }
292            let written = boundary::guard(|| {
293                // SAFETY: the engine set `retval` to null before calling us; `value` is owned by this frame.
294                unsafe { convert::write_value(out, &value) }
295            });
296            if let Ok(Err(why)) = written {
297                let (name, _) = frame(ex);
298                throw(NativeError::throw(
299                    "Error",
300                    format!("{name}(): the result cannot be returned to PHP: {why}"),
301                ));
302            }
303        }
304        Err(err) => throw(err),
305    }
306}
307
308/// The called function's name and argument count.
309fn frame(ex: &ExecuteData) -> (String, usize) {
310    // SAFETY: PHP called us with a live frame whose `func` is this function; all members of `This.u2` are the same
311    // u32.
312    unsafe {
313        let func = ex.func;
314        let mut name = String::new();
315        if !func.is_null() {
316            let fname = (*func).common.function_name;
317            if !fname.is_null() {
318                name = String::from_utf8_lossy(convert::str_bytes(fname)).into_owned();
319            }
320        }
321        (name, ex.This.u2.num_args as usize)
322    }
323}
324
325fn throw(err: NativeError) {
326    let (class, message) = match err {
327        NativeError::Throw { class, message } => (class, message),
328        NativeError::Rethrow(object) => {
329            if let Some(handle) = convert::handle_of(&object) {
330                // SAFETY: a live handle; the copy takes its own reference, which the engine takes over.
331                let copy = unsafe { convert::ZvalHandle::copy_of(handle.as_ptr()) };
332                boundary::rethrow(copy);
333            }
334            return;
335        }
336        NativeError::Silent => return,
337    };
338    if !boundary::can_enter() {
339        return;
340    }
341    let ce = find_class(&class);
342    let message = CString::new(message.replace('\0', "\\0")).unwrap_or_default();
343    let message_ptr = message.as_ptr();
344    let _ = boundary::guard(|| {
345        // SAFETY: throwing from inside a native function, with a message owned by the enclosing frame.
346        unsafe { zend_throw_exception(ce, message_ptr, 0) };
347    });
348}
349
350/// A declared class by name (no autoloading), or `\Exception`.
351fn find_class(name: &str) -> *mut zend_class_entry {
352    let key = name.trim_start_matches('\\').to_ascii_lowercase();
353    // SAFETY: a request is open, so the class table is live; it holds class entries as IS_PTR zvals.
354    unsafe {
355        let table = (*ext_php_rs_executor_globals()).class_table;
356        let zv = zend_hash_str_find(table, key.as_ptr().cast(), key.len());
357        if zv.is_null() {
358            zend_ce_exception
359        } else {
360            (*zv).value.ce
361        }
362    }
363}