Skip to main content

speedyspec_php/
callable.rs

1//! A PHP callable that Rust calls many times (a hook callback), through Zend's fast path.
2//!
3//! `call_user_func_array()` resolves its callable on every call (looks the function or method up, checks it) and
4//! copies its arguments into a new array. A [`Callable`] resolves once, with `zend_is_callable_ex()`, keeps the
5//! resulting `zend_fcall_info_cache`, and from then on calls `zend_call_function()` with it directly. The cache lives
6//! for the request: functions, classes and the objects the callable holds do not outlive it, so a new request
7//! resolves again.
8//!
9//! Arguments go to PHP as they are (a value passed through Rust unconverted is the very same zval), and the result
10//! comes back unconverted ([`crate::convert::pass_through_owned`]). One call is one entry into PHP.
11//!
12//! What cannot be cached is called as before, through `call_user_func_array()` (or `call_user_func()` with no
13//! arguments), so its errors and deprecations are PHP's own: a callable that does not resolve (yet), one that needs
14//! a calling scope or is deprecated (`self::`, `parent::`, `static::`, `"A::parent::b"`), and one PHP calls through a
15//! trampoline (`__call()`, `__callStatic()`), whose resolution is single-use.
16
17use std::cell::Cell;
18use std::mem::{ManuallyDrop, MaybeUninit};
19use std::ptr;
20
21use ext_php_rs::ffi::{
22    IS_ARRAY, IS_OBJECT, IS_STRING, ZEND_ACC_CALL_VIA_TRAMPOLINE, ZEND_RESULT_CODE_SUCCESS,
23    ext_php_rs_executor_globals, zend_array, zend_execute_data, zend_fcall_info,
24    zend_fcall_info_cache, zend_hash_index_find, zend_is_callable_ex, zval,
25};
26use ext_php_rs::types::Zval;
27use speedyspec_hooks::{Key, Value};
28
29use crate::boundary::{
30    self, CallError, ENGINE, discard_exception, drain, guard, release_later, settle_stray,
31    take_thrown,
32};
33use crate::convert::{self, Unconvertible};
34use crate::runtime::{CallFailure, PhpError, failure_of};
35
36// Engine functions that ext-php-rs's bindings leave out; ZEND_API symbols of the linked libphp.
37unsafe extern "C" {
38    fn zend_call_function(fci: *mut zend_fcall_info, fcc: *mut zend_fcall_info_cache) -> i32;
39    fn zend_release_fcall_info_cache(fcc: *mut zend_fcall_info_cache);
40}
41
42/// `IS_CALLABLE_SUPPRESS_DEPRECATIONS` (`Zend/zend_API.h`): the callables that would warn are not cached anyway.
43const SUPPRESS_DEPRECATIONS: u32 = 1 << 1;
44
45thread_local! {
46    /// The request the engine runs now; a cache from an earlier one is stale.
47    static GENERATION: Cell<u64> = const { Cell::new(0) };
48}
49
50/// A new request: every cached resolution is stale.
51pub(crate) fn new_request() {
52    GENERATION.with(|g| g.set(g.get().wrapping_add(1)));
53}
54
55fn generation() -> u64 {
56    GENERATION.with(Cell::get)
57}
58
59#[derive(Clone, Copy)]
60enum Cached {
61    /// Not resolved in this request yet.
62    Unknown,
63    Resolved {
64        generation: u64,
65        fcc: zend_fcall_info_cache,
66    },
67    /// Called through `call_user_func_array()` for the rest of the request.
68    Uncacheable { generation: u64 },
69}
70
71/// A PHP callable held by Rust, called through Zend's fast path. See the module docs.
72pub struct Callable {
73    value: Value,
74    cache: Cell<Cached>,
75    /// The callable's shape allows caching at all.
76    shape_ok: bool,
77}
78
79impl Callable {
80    /// `value` is the callable as PHP gave it; best passed through unconverted (`Value::Opaque`), so calling it never
81    /// writes it back to PHP.
82    pub fn new(value: Value) -> Callable {
83        let shape_ok = cacheable_shape(&value);
84        Callable {
85            value,
86            cache: Cell::new(Cached::Unknown),
87            shape_ok,
88        }
89    }
90
91    pub fn value(&self) -> &Value {
92        &self.value
93    }
94
95    /// Calls the callable with `args`, as WordPress's `call_user_func_array()` would; the result is passed through.
96    pub fn call(&self, args: &[Value]) -> Result<Value, CallFailure> {
97        let plain = |error: PhpError| CallFailure {
98            error,
99            exception: None,
100        };
101        if !boundary::alive() {
102            return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
103        }
104        let now = generation();
105        let fallback = !self.shape_ok
106            || matches!(self.cache.get(), Cached::Uncacheable { generation } if generation == now);
107        if !fallback {
108            match self.call_fast(args, now) {
109                Fast::Called(result) => return result.map_err(failure_of),
110                Fast::Unresolved => {}
111            }
112        }
113        self.call_user_func(args)
114    }
115
116    /// As WordPress calls a callback, through `call_user_func()` / `call_user_func_array()`.
117    fn call_user_func(&self, args: &[Value]) -> Result<Value, CallFailure> {
118        if args.is_empty() {
119            return crate::call_catching(
120                &Value::Str("call_user_func".into()),
121                std::slice::from_ref(&self.value),
122            );
123        }
124        let list = args
125            .iter()
126            .enumerate()
127            .map(|(i, v)| (Key::Int(i as i64), v.clone()))
128            .collect();
129        crate::call_catching(
130            &Value::Str("call_user_func_array".into()),
131            &[self.value.clone(), Value::Array(list)],
132        )
133    }
134
135    fn call_fast(&self, args: &[Value], now: u64) -> Fast {
136        settle_stray();
137        let handle = convert::handle_of(&self.value);
138        // A callable Rust converted (not passed through) is written for the call.
139        let mut written = ManuallyDrop::new(Zval::new());
140        let written_ptr: *mut zval = &raw mut *written;
141        let callable_ptr: *mut zval = match handle {
142            Some(handle) => handle.as_ptr().cast_mut(),
143            None => written_ptr,
144        };
145        let needs_write = handle.is_none();
146        let value = &self.value;
147
148        let mut params: Vec<ManuallyDrop<Zval>> = args
149            .iter()
150            .map(|_| ManuallyDrop::new(Zval::new()))
151            .collect();
152        let params_ptr: *mut zval = params.as_mut_ptr().cast();
153        let count = u32::try_from(params.len()).unwrap_or(u32::MAX);
154        let mut retval = ManuallyDrop::new(Zval::new());
155        let retval_ptr: *mut zval = &raw mut *retval;
156        let dummy_func = ENGINE.with(|e| e.dummy_func.get());
157        let cache = &self.cache;
158
159        let called = guard(|| -> Result<Option<bool>, Unconvertible> {
160            // SAFETY: every pointer is to zval storage owned by the enclosing frame (`params` has `count` slots;
161            // ManuallyDrop<Zval> is a transparent Zval) or to the live callable the handle holds. The dummy frame
162            // lives in this frame for the duration of the call; a bailout resets EG(current_execute_data) itself.
163            unsafe {
164                if needs_write {
165                    convert::write_value(written_ptr, value)?;
166                }
167                for (i, arg) in args.iter().enumerate() {
168                    convert::write_value(params_ptr.add(i), arg)?;
169                }
170                let eg = ext_php_rs_executor_globals();
171                let mut dummy = MaybeUninit::<zend_execute_data>::zeroed();
172                let installed = (*eg).current_execute_data.is_null();
173                if installed {
174                    (*dummy.as_mut_ptr()).func = dummy_func;
175                    (*eg).current_execute_data = dummy.as_mut_ptr();
176                }
177                let mut fcc = match cache.get() {
178                    Cached::Resolved { generation, fcc } if generation == now => Some(fcc),
179                    _ => resolve(callable_ptr, cache, now),
180                };
181                let result = fcc.as_mut().map(|fcc| {
182                    let mut fci = zend_fcall_info {
183                        size: std::mem::size_of::<zend_fcall_info>(),
184                        // Left empty: the cache names the function, and zend_call_function releases a string it
185                        // finds here (a borrowed view of the callable would lose a reference on every call).
186                        function_name: Zval::new(),
187                        retval: retval_ptr,
188                        params: params_ptr,
189                        object: fcc.object,
190                        param_count: count,
191                        named_params: ptr::null_mut(),
192                    };
193                    zend_call_function(&raw mut fci, fcc) == ZEND_RESULT_CODE_SUCCESS
194                });
195                if installed {
196                    (*eg).current_execute_data = ptr::null_mut();
197                }
198                Ok(result)
199            }
200        });
201
202        if needs_write {
203            release_later(written);
204        }
205        for param in params {
206            release_later(param);
207        }
208        let outcome = match called {
209            Ok(Ok(Some(_))) => {
210                // SAFETY: `retval` holds what the callable returned (or null); its reference moves to the value.
211                Some(unsafe { convert::pass_through_owned(retval) })
212            }
213            _ => {
214                release_later(retval);
215                None
216            }
217        };
218        // SAFETY: a plain read of the executor globals on the engine's thread.
219        let clear_before = matches!(called, Ok(Ok(Some(true))))
220            && unsafe { (*ext_php_rs_executor_globals()).exception.is_null() };
221        drain();
222        if clear_before {
223            settle_stray();
224        }
225        match called {
226            Err(interrupted) => {
227                discard_exception();
228                Fast::Called(Err(CallError::Interrupted(interrupted)))
229            }
230            Ok(Err(why)) => Fast::Called(Err(CallError::Convert(why.to_string()))),
231            Ok(Ok(None)) => {
232                // Not resolved: nothing ran. Anything resolving threw (an autoloader) is the fallback's to raise
233                // again, from PHP's own call.
234                discard_exception();
235                Fast::Unresolved
236            }
237            Ok(Ok(Some(true))) => match take_thrown() {
238                Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
239                None => Fast::Called(Ok(outcome.unwrap_or(Value::Null))),
240            },
241            Ok(Ok(Some(false))) => match take_thrown() {
242                Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
243                None => Fast::Called(Err(CallError::Convert(
244                    "PHP refused the call (the executor is inactive)".to_owned(),
245                ))),
246            },
247        }
248    }
249}
250
251enum Fast {
252    Called(Result<Value, CallError>),
253    /// The callable did not resolve to something cacheable; nothing ran.
254    Unresolved,
255}
256
257/// Resolves `callable` and caches the result for this request; `None` when it cannot be cached (it is then called
258/// as WordPress calls it).
259///
260/// # Safety
261///
262/// Inside a guard, on the engine's thread; `callable` is a live zval.
263unsafe fn resolve(
264    callable: *mut zval,
265    cache: &Cell<Cached>,
266    now: u64,
267) -> Option<zend_fcall_info_cache> {
268    // SAFETY: forwarded from the caller; a zeroed fcc is what zend_is_callable_ex fills in.
269    unsafe {
270        let mut fcc = MaybeUninit::<zend_fcall_info_cache>::zeroed().assume_init();
271        let ok = zend_is_callable_ex(
272            callable,
273            ptr::null_mut(),
274            SUPPRESS_DEPRECATIONS,
275            ptr::null_mut(),
276            &raw mut fcc,
277            ptr::null_mut(),
278        );
279        if !ok || fcc.function_handler.is_null() {
280            // Maybe defined later in the request: try again next time.
281            return None;
282        }
283        let flags = (*fcc.function_handler).common.fn_flags;
284        if flags & ZEND_ACC_CALL_VIA_TRAMPOLINE != 0 {
285            zend_release_fcall_info_cache(&raw mut fcc);
286            cache.set(Cached::Uncacheable { generation: now });
287            return None;
288        }
289        cache.set(Cached::Resolved {
290            generation: now,
291            fcc,
292        });
293        Some(fcc)
294    }
295}
296
297/// True for the callables whose resolution needs no calling scope and raises no deprecation: a function name,
298/// `"Class::method"`, a closure or invokable object, `[$object, 'method']` and `['Class', 'method']`, with no
299/// `self`, `parent` or `static` and no `::` in the method.
300fn cacheable_shape(value: &Value) -> bool {
301    fn plain_class(class: &[u8]) -> bool {
302        !class.is_empty()
303            && !["self", "parent", "static"]
304                .iter()
305                .any(|kw| class.eq_ignore_ascii_case(kw.as_bytes()))
306    }
307    fn plain_name(name: &[u8]) -> bool {
308        match name.windows(2).position(|w| w == b"::") {
309            None => !name.is_empty(),
310            Some(at) => {
311                let (class, method) = (&name[..at], &name[at + 2..]);
312                plain_class(class) && !method.is_empty() && !method.windows(2).any(|w| w == b"::")
313            }
314        }
315    }
316    fn method_ok(method: &[u8]) -> bool {
317        !method.is_empty() && !method.windows(2).any(|w| w == b"::")
318    }
319    match value {
320        Value::Str(name) => plain_name(name.as_bytes()),
321        Value::Bytes(name) => plain_name(name),
322        Value::Array(entries) => {
323            let at = |i: i64| {
324                entries
325                    .iter()
326                    .find(|(k, _)| *k == Key::Int(i))
327                    .map(|(_, v)| v)
328            };
329            entries.len() == 2
330                && match (at(0), at(1)) {
331                    (Some(Value::Str(class)), Some(Value::Str(method))) => {
332                        plain_class(class.as_bytes()) && method_ok(method.as_bytes())
333                    }
334                    (Some(Value::Opaque(_)), Some(Value::Str(method))) => {
335                        method_ok(method.as_bytes())
336                    }
337                    _ => false,
338                }
339        }
340        Value::Opaque(_) => match convert::handle_of(value) {
341            // SAFETY: the handle holds a live zval.
342            Some(handle) => unsafe { zval_shape_ok(handle.as_ptr()) },
343            None => false,
344        },
345        _ => false,
346    }
347}
348
349/// [`cacheable_shape`] of a callable PHP passed through.
350///
351/// # Safety
352///
353/// `zv` is a live zval.
354unsafe fn zval_shape_ok(zv: *const zval) -> bool {
355    // SAFETY: the caller guarantees `zv` is live; reading runs no PHP code.
356    unsafe {
357        match u32::from(convert::type_of(zv)) {
358            IS_OBJECT => true,
359            IS_STRING | IS_ARRAY => match convert::to_value(zv) {
360                Ok(value @ (Value::Str(_) | Value::Bytes(_))) => cacheable_shape(&value),
361                Ok(Value::Array(_)) => {
362                    let ht: *const zend_array = (*zv).value.arr;
363                    if (*ht).nNumOfElements != 2 {
364                        return false;
365                    }
366                    let (target, method) =
367                        (zend_hash_index_find(ht, 0), zend_hash_index_find(ht, 1));
368                    if target.is_null() || method.is_null() {
369                        return false;
370                    }
371                    let (target, method) = (convert::deref(target), convert::deref(method));
372                    let method = match convert::to_value(method) {
373                        Ok(Value::Str(method)) => method,
374                        _ => return false,
375                    };
376                    match u32::from(convert::type_of(target)) {
377                        IS_OBJECT => !method.is_empty() && !method.contains("::"),
378                        IS_STRING => match convert::to_value(target) {
379                            Ok(class @ Value::Str(_)) => cacheable_shape(&Value::Array(vec![
380                                (Key::Int(0), class),
381                                (Key::Int(1), Value::Str(method)),
382                            ])),
383                            _ => false,
384                        },
385                        _ => false,
386                    }
387                }
388                _ => false,
389            },
390            _ => false,
391        }
392    }
393}