use std::cell::Cell;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ptr;
use ext_php_rs::ffi::{
IS_ARRAY, IS_OBJECT, IS_STRING, ZEND_ACC_CALL_VIA_TRAMPOLINE, ZEND_RESULT_CODE_SUCCESS,
ext_php_rs_executor_globals, zend_array, zend_execute_data, zend_fcall_info,
zend_fcall_info_cache, zend_hash_index_find, zend_is_callable_ex, zval,
};
use ext_php_rs::types::Zval;
use speedyspec_hooks::{Key, Value};
use crate::boundary::{
self, CallError, ENGINE, discard_exception, drain, guard, release_later, settle_stray,
take_thrown,
};
use crate::convert::{self, Unconvertible};
use crate::runtime::{CallFailure, PhpError, failure_of};
unsafe extern "C" {
fn zend_call_function(fci: *mut zend_fcall_info, fcc: *mut zend_fcall_info_cache) -> i32;
fn zend_release_fcall_info_cache(fcc: *mut zend_fcall_info_cache);
}
const SUPPRESS_DEPRECATIONS: u32 = 1 << 1;
thread_local! {
static GENERATION: Cell<u64> = const { Cell::new(0) };
}
pub(crate) fn new_request() {
GENERATION.with(|g| g.set(g.get().wrapping_add(1)));
}
fn generation() -> u64 {
GENERATION.with(Cell::get)
}
#[derive(Clone, Copy)]
enum Cached {
Unknown,
Resolved {
generation: u64,
fcc: zend_fcall_info_cache,
},
Uncacheable { generation: u64 },
}
pub struct Callable {
value: Value,
cache: Cell<Cached>,
shape_ok: bool,
}
impl Callable {
pub fn new(value: Value) -> Callable {
let shape_ok = cacheable_shape(&value);
Callable {
value,
cache: Cell::new(Cached::Unknown),
shape_ok,
}
}
pub fn value(&self) -> &Value {
&self.value
}
pub fn call(&self, args: &[Value]) -> Result<Value, CallFailure> {
let plain = |error: PhpError| CallFailure {
error,
exception: None,
};
if !boundary::alive() {
return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
}
let now = generation();
let fallback = !self.shape_ok
|| matches!(self.cache.get(), Cached::Uncacheable { generation } if generation == now);
if !fallback {
match self.call_fast(args, now) {
Fast::Called(result) => return result.map_err(failure_of),
Fast::Unresolved => {}
}
}
self.call_user_func(args)
}
fn call_user_func(&self, args: &[Value]) -> Result<Value, CallFailure> {
if args.is_empty() {
return crate::call_catching(
&Value::Str("call_user_func".into()),
std::slice::from_ref(&self.value),
);
}
let list = args
.iter()
.enumerate()
.map(|(i, v)| (Key::Int(i as i64), v.clone()))
.collect();
crate::call_catching(
&Value::Str("call_user_func_array".into()),
&[self.value.clone(), Value::Array(list)],
)
}
fn call_fast(&self, args: &[Value], now: u64) -> Fast {
settle_stray();
let handle = convert::handle_of(&self.value);
let mut written = ManuallyDrop::new(Zval::new());
let written_ptr: *mut zval = &raw mut *written;
let callable_ptr: *mut zval = match handle {
Some(handle) => handle.as_ptr().cast_mut(),
None => written_ptr,
};
let needs_write = handle.is_none();
let value = &self.value;
let mut params: Vec<ManuallyDrop<Zval>> = args
.iter()
.map(|_| ManuallyDrop::new(Zval::new()))
.collect();
let params_ptr: *mut zval = params.as_mut_ptr().cast();
let count = u32::try_from(params.len()).unwrap_or(u32::MAX);
let mut retval = ManuallyDrop::new(Zval::new());
let retval_ptr: *mut zval = &raw mut *retval;
let dummy_func = ENGINE.with(|e| e.dummy_func.get());
let cache = &self.cache;
let called = guard(|| -> Result<Option<bool>, Unconvertible> {
unsafe {
if needs_write {
convert::write_value(written_ptr, value)?;
}
for (i, arg) in args.iter().enumerate() {
convert::write_param(params_ptr.add(i), arg)?;
}
let eg = ext_php_rs_executor_globals();
let mut dummy = MaybeUninit::<zend_execute_data>::zeroed();
let installed = (*eg).current_execute_data.is_null();
if installed {
(*dummy.as_mut_ptr()).func = dummy_func;
(*eg).current_execute_data = dummy.as_mut_ptr();
}
let mut fcc = match cache.get() {
Cached::Resolved { generation, fcc } if generation == now => Some(fcc),
_ => resolve(callable_ptr, cache, now),
};
let result = fcc.as_mut().map(|fcc| {
let mut fci = zend_fcall_info {
size: std::mem::size_of::<zend_fcall_info>(),
function_name: Zval::new(),
retval: retval_ptr,
params: params_ptr,
object: fcc.object,
param_count: count,
named_params: ptr::null_mut(),
};
zend_call_function(&raw mut fci, fcc) == ZEND_RESULT_CODE_SUCCESS
});
if installed {
(*eg).current_execute_data = ptr::null_mut();
}
Ok(result)
}
});
if needs_write {
release_later(written);
}
for param in params {
release_later(param);
}
let outcome = match called {
Ok(Ok(Some(_))) => {
Some(unsafe { convert::pass_through_owned(retval) })
}
_ => {
release_later(retval);
None
}
};
let clear_before = matches!(called, Ok(Ok(Some(true))))
&& unsafe { (*ext_php_rs_executor_globals()).exception.is_null() };
drain();
if clear_before {
settle_stray();
}
match called {
Err(interrupted) => {
discard_exception();
Fast::Called(Err(CallError::Interrupted(interrupted)))
}
Ok(Err(why)) => Fast::Called(Err(CallError::Convert(why.to_string()))),
Ok(Ok(None)) => {
discard_exception();
Fast::Unresolved
}
Ok(Ok(Some(true))) => match take_thrown() {
Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
None => Fast::Called(Ok(outcome.unwrap_or(Value::Null))),
},
Ok(Ok(Some(false))) => match take_thrown() {
Some(thrown) => Fast::Called(Err(CallError::Thrown(thrown))),
None => Fast::Called(Err(CallError::Convert(
"PHP refused the call (the executor is inactive)".to_owned(),
))),
},
}
}
}
enum Fast {
Called(Result<Value, CallError>),
Unresolved,
}
unsafe fn resolve(
callable: *mut zval,
cache: &Cell<Cached>,
now: u64,
) -> Option<zend_fcall_info_cache> {
unsafe {
let mut fcc = MaybeUninit::<zend_fcall_info_cache>::zeroed().assume_init();
let ok = zend_is_callable_ex(
callable,
ptr::null_mut(),
SUPPRESS_DEPRECATIONS,
ptr::null_mut(),
&raw mut fcc,
ptr::null_mut(),
);
if !ok || fcc.function_handler.is_null() {
return None;
}
let flags = (*fcc.function_handler).common.fn_flags;
if flags & ZEND_ACC_CALL_VIA_TRAMPOLINE != 0 {
zend_release_fcall_info_cache(&raw mut fcc);
cache.set(Cached::Uncacheable { generation: now });
return None;
}
cache.set(Cached::Resolved {
generation: now,
fcc,
});
Some(fcc)
}
}
fn cacheable_shape(value: &Value) -> bool {
fn plain_class(class: &[u8]) -> bool {
!class.is_empty()
&& !["self", "parent", "static"]
.iter()
.any(|kw| class.eq_ignore_ascii_case(kw.as_bytes()))
}
fn plain_name(name: &[u8]) -> bool {
match name.windows(2).position(|w| w == b"::") {
None => !name.is_empty(),
Some(at) => {
let (class, method) = (&name[..at], &name[at + 2..]);
plain_class(class) && !method.is_empty() && !method.windows(2).any(|w| w == b"::")
}
}
}
fn method_ok(method: &[u8]) -> bool {
!method.is_empty() && !method.windows(2).any(|w| w == b"::")
}
match value {
Value::Str(name) => plain_name(name.as_bytes()),
Value::Bytes(name) => plain_name(name),
Value::Array(entries) => {
let at = |i: i64| {
entries
.iter()
.find(|(k, _)| *k == Key::Int(i))
.map(|(_, v)| v)
};
entries.len() == 2
&& match (at(0), at(1)) {
(Some(Value::Str(class)), Some(Value::Str(method))) => {
plain_class(class.as_bytes()) && method_ok(method.as_bytes())
}
(Some(Value::Opaque(_)), Some(Value::Str(method))) => {
method_ok(method.as_bytes())
}
_ => false,
}
}
Value::Opaque(_) => match convert::handle_of(value) {
Some(handle) => unsafe { zval_shape_ok(handle.as_ptr()) },
None => false,
},
_ => false,
}
}
unsafe fn zval_shape_ok(zv: *const zval) -> bool {
unsafe {
match u32::from(convert::type_of(zv)) {
IS_OBJECT => true,
IS_STRING | IS_ARRAY => match convert::to_value(zv) {
Ok(value @ (Value::Str(_) | Value::Bytes(_))) => cacheable_shape(&value),
Ok(Value::Array(_)) => {
let ht: *const zend_array = (*zv).value.arr;
if (*ht).nNumOfElements != 2 {
return false;
}
let (target, method) =
(zend_hash_index_find(ht, 0), zend_hash_index_find(ht, 1));
if target.is_null() || method.is_null() {
return false;
}
let (target, method) = (convert::deref(target), convert::deref(method));
let method = match convert::to_value(method) {
Ok(Value::Str(method)) => method,
_ => return false,
};
match u32::from(convert::type_of(target)) {
IS_OBJECT => !method.is_empty() && !method.contains("::"),
IS_STRING => match convert::to_value(target) {
Ok(class @ Value::Str(_)) => cacheable_shape(&Value::Array(vec![
(Key::Int(0), class),
(Key::Int(1), Value::Str(method)),
])),
_ => false,
},
_ => false,
}
}
_ => false,
},
_ => false,
}
}
}