use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::ffi::{CStr, c_void};
use std::io::Write;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::ptr;
use ext_php_rs::ffi::{
_call_user_function_impl, _zend_oom_state_ZEND_OOM_STATE_HANDLED,
_zend_oom_state_ZEND_OOM_STATE_NONE, _zend_oom_state_ZEND_OOM_STATE_PENDING, E_COMPILE_ERROR,
E_CORE_ERROR, E_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR, ZEND_RESULT_CODE_SUCCESS,
ext_php_rs_executor_globals, ext_php_rs_process_globals, zend_execute_data, zend_function,
zend_hash_str_find, zend_object, zend_read_property, zend_string, zval, zval_ptr_dtor,
};
use ext_php_rs::types::Zval;
use ext_php_rs::zend::{ExecuteData, bailout, try_catch};
use speedyspec_hooks::Value;
use crate::convert::{self, ConvertError, Unconvertible, ZvalHandle};
use crate::runtime::PhpError;
unsafe extern "C" {
fn zend_is_unwind_exit(ex: *const zend_object) -> bool;
fn zend_is_graceful_exit(ex: *const zend_object) -> bool;
fn zend_throw_exception_internal(exception: *mut zend_object);
fn zend_observer_fiber_init_register(handler: unsafe extern "C" fn(*mut c_void));
fn zend_observer_fiber_switch_register(handler: unsafe extern "C" fn(*mut c_void, *mut c_void));
fn zend_observer_fiber_destroy_register(handler: unsafe extern "C" fn(*mut c_void));
fn zend_handle_delayed_oom();
}
pub(crate) struct Engine {
native_depth: Cell<u32>,
unwinding: Cell<bool>,
pending_exit: Cell<*mut zend_object>,
frames: RefCell<Vec<Frame>>,
pub(crate) contexts: RefCell<BTreeMap<usize, ContextState>>,
pub(crate) alive: Cell<bool>,
pub(crate) panic: RefCell<Option<Box<dyn Any + Send>>>,
pub(crate) releases: RefCell<Vec<ManuallyDrop<Zval>>>,
entries: Cell<u64>,
pub(crate) poisoned: Cell<bool>,
pub(crate) dummy_func: Cell<*mut zend_function>,
oom_exit: RefCell<Option<(usize, Fatal)>>,
}
thread_local! {
pub(crate) static ENGINE: Engine = const {
Engine {
native_depth: Cell::new(0),
unwinding: Cell::new(false),
pending_exit: Cell::new(ptr::null_mut()),
frames: RefCell::new(Vec::new()),
contexts: RefCell::new(BTreeMap::new()),
alive: Cell::new(false),
panic: RefCell::new(None),
releases: RefCell::new(Vec::new()),
entries: Cell::new(0),
poisoned: Cell::new(false),
dummy_func: Cell::new(ptr::null_mut()),
oom_exit: RefCell::new(None),
}
};
}
pub(crate) struct Frame {
pub(crate) thrown: Option<(String, ZvalHandle)>,
}
#[derive(Default)]
pub(crate) struct ContextState {
native_depth: u32,
unwinding: bool,
pending_exit: Option<ZvalHandle>,
frames: Vec<Frame>,
}
impl Engine {
pub(crate) fn take_current(&self) -> ContextState {
let exit = self.pending_exit.replace(ptr::null_mut());
ContextState {
native_depth: self.native_depth.replace(0),
unwinding: self.unwinding.replace(false),
pending_exit: (!exit.is_null()).then(|| unsafe { ZvalHandle::adopt_object(exit) }),
frames: std::mem::take(&mut *self.frames.borrow_mut()),
}
}
fn load_current(&self, state: ContextState) {
let ContextState {
native_depth,
unwinding,
pending_exit,
frames,
} = state;
self.native_depth.set(native_depth);
self.unwinding.set(unwinding);
self.pending_exit.set(
pending_exit
.and_then(ZvalHandle::into_object)
.unwrap_or(ptr::null_mut()),
);
*self.frames.borrow_mut() = frames;
}
}
pub(crate) fn register_fiber_observers() {
unsafe {
zend_observer_fiber_init_register(on_fiber_init);
zend_observer_fiber_switch_register(on_fiber_switch);
zend_observer_fiber_destroy_register(on_fiber_destroy);
}
}
fn observer(f: impl FnOnce()) {
if catch_unwind(AssertUnwindSafe(f)).is_err() {
eprintln!("speedyspec-php: panic in a fiber observer");
std::process::abort();
}
}
unsafe extern "C" fn on_fiber_init(context: *mut c_void) {
observer(|| {
let stale = ENGINE.with(|e| e.contexts.borrow_mut().remove(&(context as usize)));
drop(stale);
});
}
unsafe extern "C" fn on_fiber_switch(from: *mut c_void, to: *mut c_void) {
observer(|| {
ENGINE.with(|e| {
let leaving = e.take_current();
let (stale, entering) = {
let mut contexts = e.contexts.borrow_mut();
let stale = contexts.insert(from as usize, leaving);
(stale, contexts.remove(&(to as usize)).unwrap_or_default())
};
e.load_current(entering);
drop(stale);
});
});
}
unsafe extern "C" fn on_fiber_destroy(context: *mut c_void) {
observer(|| {
let record = ENGINE.with(|e| e.contexts.borrow_mut().remove(&(context as usize)));
drop(record);
});
}
pub(crate) fn push_frame() {
ENGINE.with(|e| e.frames.borrow_mut().push(Frame { thrown: None }));
}
pub(crate) fn pop_frame() -> Option<Frame> {
ENGINE.with(|e| e.frames.borrow_mut().pop())
}
pub(crate) fn keep_in_top_frame(message: String, object: ZvalHandle) {
let replaced = ENGINE.with(|e| {
e.frames
.borrow_mut()
.last_mut()
.and_then(|frame| frame.thrown.replace((message, object)))
});
drop(replaced);
}
pub(crate) fn entries() -> u64 {
ENGINE.with(|e| e.entries.get())
}
pub(crate) fn fiber_records() -> usize {
ENGINE.with(|e| e.contexts.borrow().len())
}
pub(crate) fn execution_context() -> usize {
unsafe { (*ext_php_rs_executor_globals()).current_fiber_context as usize }
}
pub(crate) fn alive() -> bool {
ENGINE.with(|e| e.alive.get())
}
pub(crate) fn can_enter() -> bool {
alive() && !interrupted()
}
fn interrupted() -> bool {
ENGINE.with(|e| e.unwinding.get() || !e.pending_exit.get().is_null())
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Interrupted {
Bailout,
Refused,
}
pub(crate) fn guard<R>(f: impl FnOnce() -> R) -> Result<R, Interrupted> {
if !can_enter() {
return Err(Interrupted::Refused);
}
ENGINE.with(|e| e.entries.set(e.entries.get() + 1));
let outcome = try_catch(AssertUnwindSafe(|| catch_unwind(AssertUnwindSafe(f))));
match outcome {
Ok(Ok(value)) => Ok(value),
Ok(Err(payload)) => resume_unwind(payload),
Err(_) => {
ENGINE.with(|e| e.poisoned.set(true));
settle_delayed_oom();
if let Some(payload) = ENGINE.with(|e| e.panic.borrow_mut().take()) {
resume_unwind(payload);
}
ENGINE.with(|e| {
if e.native_depth.get() > 0 {
e.unwinding.set(true);
}
});
Err(Interrupted::Bailout)
}
}
}
pub(crate) fn native_entry(
ex: &mut ExecuteData,
retval: &mut Zval,
body: fn(&mut ExecuteData, &mut Zval),
) {
if run_native(ex, retval, body) {
unsafe { bailout() }
}
}
#[inline(never)]
fn run_native(
ex: &mut ExecuteData,
retval: &mut Zval,
body: fn(&mut ExecuteData, &mut Zval),
) -> bool {
ENGINE.with(|e| e.native_depth.set(e.native_depth.get() + 1));
let outcome = catch_unwind(AssertUnwindSafe(|| {
body(ex, retval);
drain();
}));
ENGINE.with(|e| e.native_depth.set(e.native_depth.get() - 1));
if let Err(payload) = outcome {
ENGINE.with(|e| *e.panic.borrow_mut() = Some(payload));
return true;
}
if ENGINE.with(|e| e.unwinding.replace(false)) {
return true;
}
let exit = ENGINE.with(|e| e.pending_exit.replace(ptr::null_mut()));
if !exit.is_null() {
unsafe { zend_throw_exception_internal(exit) };
}
false
}
pub(crate) fn release_later(zv: ManuallyDrop<Zval>) {
let counted =
unsafe { u32::from(zv.u1.v.type_flags) & ext_php_rs::ffi::IS_TYPE_REFCOUNTED != 0 };
if !counted {
return;
}
let _ = ENGINE.try_with(|e| {
if !e.alive.get() {
return;
}
let released = unsafe {
let ty = u32::from(zv.u1.v.type_);
let counted = zv.value.counted;
if (ty == ext_php_rs::ffi::IS_STRING || ty == ext_php_rs::ffi::IS_ARRAY)
&& (*counted).gc.refcount > 1
{
(*counted).gc.refcount -= 1;
true
} else {
false
}
};
if !released {
e.releases.borrow_mut().push(zv);
}
});
}
pub(crate) fn drain() {
let dummy_func = ENGINE.with(|e| e.dummy_func.get());
loop {
if !can_enter() {
return;
}
let Some(mut zv) = ENGINE.with(|e| e.releases.borrow_mut().pop()) else {
return;
};
let zv_ptr: *mut zval = &raw mut *zv;
let _ = guard(|| {
unsafe {
let eg = ext_php_rs_executor_globals();
let mut dummy = MaybeUninit::<zend_execute_data>::zeroed();
let installed = (*eg).current_execute_data.is_null() && !dummy_func.is_null();
if installed {
(*dummy.as_mut_ptr()).func = dummy_func;
(*eg).current_execute_data = dummy.as_mut_ptr();
}
zval_ptr_dtor(zv_ptr);
if installed {
(*eg).current_execute_data = ptr::null_mut();
}
}
});
}
}
pub(crate) enum Thrown {
Exit(i32),
Fatal(Fatal),
FiberDestroyed,
Exception {
object: ZvalHandle,
class: String,
message: String,
file: String,
line: u32,
},
}
impl Thrown {
pub(crate) fn into_php_error(self) -> PhpError {
match self {
Self::Exit(status) => PhpError::Exit(status),
Self::Fatal(fatal) => fatal.into_php_error(),
Self::FiberDestroyed => PhpError::Exception {
class: "GracefulExit".to_owned(),
message: "the fiber running this code was destroyed".to_owned(),
file: String::new(),
line: 0,
},
Self::Exception {
class,
message,
file,
line,
..
} => PhpError::Exception {
class,
message,
file,
line,
},
}
}
}
pub(crate) fn take_thrown() -> Option<Thrown> {
let obj = unsafe {
let eg = ext_php_rs_executor_globals();
let obj = (*eg).exception;
if obj.is_null() {
return None;
}
(*eg).exception = ptr::null_mut();
obj
};
let (unwind_exit, graceful_exit) =
unsafe { (zend_is_unwind_exit(obj), zend_is_graceful_exit(obj)) };
if unwind_exit || graceful_exit {
let status = unsafe { (*ext_php_rs_executor_globals()).exit_status };
let oom = if unwind_exit {
out_of_memory(obj)
} else {
None
};
ENGINE.with(|e| {
if e.native_depth.get() > 0 && e.pending_exit.get().is_null() {
e.pending_exit.set(obj);
if let Some(fatal) = &oom {
*e.oom_exit.borrow_mut() = Some((obj as usize, fatal.clone()));
}
} else {
e.oom_exit.borrow_mut().take();
drop(unsafe { ZvalHandle::adopt_object(obj) });
}
});
return Some(match (graceful_exit, oom) {
(true, _) => Thrown::FiberDestroyed,
(false, Some(fatal)) => Thrown::Fatal(fatal),
(false, None) => Thrown::Exit(status),
});
}
let object = unsafe { ZvalHandle::adopt_object(obj) };
let (class, message, file, line) = describe_throwable(obj);
Some(Thrown::Exception {
object,
class,
message,
file,
line,
})
}
pub(crate) fn settle_stray() {
if ENGINE.with(|e| e.native_depth.get()) > 0 {
return;
}
for _ in 0..8 {
drain();
let Some(thrown) = take_thrown() else {
return;
};
let what = match &thrown {
Thrown::Exception {
class,
message,
file,
line,
..
} => format!("an uncaught {class} ({message}) thrown in {file}:{line}"),
Thrown::Exit(status) => format!("exit({status})"),
Thrown::Fatal(fatal) => format!("a fatal error ({})", fatal.message),
Thrown::FiberDestroyed => "a fiber's unwinding".to_owned(),
};
let mut stderr = std::io::stderr().lock();
let _ = writeln!(
stderr,
"speedyspec: discarded {what} while releasing a PHP value outside any call"
);
drop(thrown);
}
}
pub(crate) fn discard_exception() {
unsafe {
let eg = ext_php_rs_executor_globals();
let obj = (*eg).exception;
if !obj.is_null() {
(*eg).exception = ptr::null_mut();
drop(ZvalHandle::adopt_object(obj));
}
}
}
pub(crate) fn rethrow(object: ZvalHandle) {
if let Some(obj) = object.into_object() {
unsafe { zend_throw_exception_internal(obj) };
}
}
fn describe_throwable(obj: *mut zend_object) -> (String, String, String, u32) {
let class = unsafe { class_name(obj) };
let message = read_property(obj, c"message")
.and_then(|v| match v {
Value::Str(s) => Some(s),
Value::Bytes(b) => Some(String::from_utf8_lossy(&b).into_owned()),
_ => None,
})
.unwrap_or_default();
let file = match read_property(obj, c"file") {
Some(Value::Str(s)) => s,
_ => String::new(),
};
let line = match read_property(obj, c"line") {
Some(Value::Int(n)) => u32::try_from(n).unwrap_or(0),
_ => 0,
};
(class, message, file, line)
}
fn read_property(obj: *mut zend_object, name: &CStr) -> Option<Value> {
let mut rv = ManuallyDrop::new(Zval::new());
rv.u1.type_info = ext_php_rs::ffi::IS_UNDEF;
let rv_ptr: *mut zval = &raw mut *rv;
let found = guard(|| {
unsafe {
zend_read_property(
(*obj).ce,
obj,
name.as_ptr(),
name.to_bytes().len(),
true,
rv_ptr,
)
}
})
.ok()
.filter(|zv| !zv.is_null());
let value = found.and_then(|zv| unsafe { convert::to_value(zv) }.ok());
release_later(rv);
value
}
pub(crate) unsafe fn class_name(obj: *mut zend_object) -> String {
unsafe { String::from_utf8_lossy(convert::str_bytes((*(*obj).ce).name)).into_owned() }
}
#[derive(Clone, Debug)]
pub(crate) struct Fatal {
message: String,
file: String,
line: u32,
}
impl Fatal {
fn into_php_error(self) -> PhpError {
PhpError::Fatal {
message: self.message,
file: self.file,
line: self.line,
}
}
}
pub(crate) fn fatal_error(interrupted: Interrupted) -> PhpError {
if let Interrupted::Refused = interrupted {
return PhpError::Fatal {
message: "PHP is unwinding from a fatal error or exit() and cannot run code".to_owned(),
file: String::new(),
line: 0,
};
}
last_fatal().into_php_error()
}
fn last_fatal() -> Fatal {
const FATAL: u32 =
E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE;
unsafe {
let pg = ext_php_rs_process_globals();
let kind = u32::try_from((*pg).last_error_type).unwrap_or(0);
if kind & FATAL == 0 || (*pg).last_error_message.is_null() {
return Fatal {
message: "PHP bailed out".to_owned(),
file: String::new(),
line: 0,
};
}
let text = |s: *mut zend_string| {
if s.is_null() {
String::new()
} else {
String::from_utf8_lossy(convert::str_bytes(s)).into_owned()
}
};
Fatal {
message: text((*pg).last_error_message),
file: text((*pg).last_error_file),
line: u32::try_from((*pg).last_error_lineno).unwrap_or(0),
}
}
}
fn settle_delayed_oom() -> bool {
let handled = unsafe {
let oom = &raw mut (*ext_php_rs_executor_globals()).delayed_oom;
if (*oom).state == _zend_oom_state_ZEND_OOM_STATE_HANDLED {
(*oom).state = _zend_oom_state_ZEND_OOM_STATE_NONE;
true
} else {
false
}
};
if handled {
ENGINE.with(|e| e.poisoned.set(true));
}
handled
}
fn out_of_memory(obj: *mut zend_object) -> Option<Fatal> {
if settle_delayed_oom() {
return Some(last_fatal());
}
ENGINE.with(|e| {
let marked = e.oom_exit.borrow();
match marked.as_ref() {
Some((address, fatal)) if *address == obj as usize => Some(fatal.clone()),
_ => None,
}
})
}
pub(crate) unsafe fn handle_queued_oom() {
unsafe {
if (*ext_php_rs_executor_globals()).delayed_oom.state
== _zend_oom_state_ZEND_OOM_STATE_PENDING
{
zend_handle_delayed_oom();
}
}
}
pub(crate) enum CallError {
Thrown(Thrown),
Interrupted(Interrupted),
Convert(String),
}
impl CallError {
pub(crate) fn into_php_error(self) -> PhpError {
match self {
Self::Thrown(thrown) => thrown.into_php_error(),
Self::Interrupted(interrupted) => fatal_error(interrupted),
Self::Convert(why) => PhpError::Conversion(why),
}
}
pub(crate) fn describe(&self) -> String {
match self {
Self::Thrown(Thrown::Exit(status)) => format!("PHP code called exit({status})"),
Self::Thrown(Thrown::Fatal(fatal)) => fatal.clone().into_php_error().to_string(),
Self::Thrown(Thrown::FiberDestroyed) => {
"the fiber running this callback was destroyed".to_owned()
}
Self::Thrown(Thrown::Exception {
class,
message,
file,
line,
..
}) => format!("{class}: {message} in {file}:{line}"),
Self::Interrupted(interrupted) => fatal_error(*interrupted).to_string(),
Self::Convert(why) => why.clone(),
}
}
}
pub(crate) fn call_php(callable: *mut zval, args: &[Value]) -> Result<Value, CallError> {
settle_stray();
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 called = guard(|| -> Result<bool, Unconvertible> {
unsafe {
for (i, arg) in args.iter().enumerate() {
convert::write_value(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 result = _call_user_function_impl(
ptr::null_mut(),
callable,
retval_ptr,
count,
params_ptr,
ptr::null_mut(),
);
if installed {
(*eg).current_execute_data = ptr::null_mut();
}
Ok(result == ZEND_RESULT_CODE_SUCCESS)
}
});
let value = unsafe { convert::to_value(retval_ptr) };
for param in params {
release_later(param);
}
release_later(retval);
let clear_before = matches!(called, Ok(Ok(true)))
&& unsafe { (*ext_php_rs_executor_globals()).exception.is_null() };
drain();
if clear_before {
settle_stray();
}
match called {
Err(interrupted) => {
discard_exception();
return Err(CallError::Interrupted(interrupted));
}
Ok(Err(why)) => return Err(CallError::Convert(why.to_string())),
Ok(Ok(true)) => {}
Ok(Ok(false)) => {
if let Some(thrown) = take_thrown() {
return Err(CallError::Thrown(thrown));
}
return Err(CallError::Convert(
"PHP refused the call (the executor is inactive)".to_owned(),
));
}
}
if let Some(thrown) = take_thrown() {
return Err(CallError::Thrown(thrown));
}
value
.map_err(|e: ConvertError| CallError::Convert(format!("the result cannot reach Rust: {e}")))
}
pub(crate) unsafe fn find_function(name: &str) -> *mut zend_function {
unsafe {
let table = (*ext_php_rs_executor_globals()).function_table;
let zv = zend_hash_str_find(table, name.as_ptr().cast(), name.len());
if zv.is_null() {
ptr::null_mut()
} else {
(*zv).value.func
}
}
}
pub(crate) fn table_as_zval(table: *mut ext_php_rs::ffi::zend_array) -> ManuallyDrop<Zval> {
let mut zv = ManuallyDrop::new(Zval::new());
zv.value.arr = table;
zv.u1.type_info = ext_php_rs::ffi::IS_ARRAY;
zv
}