use std::cell::Cell;
use std::ffi::CString;
use std::fmt;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::panic::resume_unwind;
use std::path::{Path, PathBuf};
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use ext_php_rs::alloc::efree;
use ext_php_rs::ffi::{
_zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
_zend_compile_position_ZEND_COMPILE_POSITION_AT_OPEN_TAG, ZEND_RESULT_CODE_SUCCESS,
destroy_op_array, ext_php_rs_compiler_globals, ext_php_rs_executor_globals,
ext_php_rs_zend_string_init, ext_php_rs_zend_string_release, sapi_shutdown,
zend_compile_position, zend_compile_string, zend_destroy_static_vars, zend_execute,
zend_get_executed_scope, zend_op_array, zend_string, zval,
};
use sapi::{
SapiModule, cleanup_sapi_allocations, ext_php_rs_sapi_shutdown, php_module_shutdown,
php_request_shutdown, php_request_startup,
};
#[cfg(feature = "embed")]
mod sapi {
pub(super) use ext_php_rs::builders::SapiBuilder;
pub(super) use ext_php_rs::embed::{
SapiModule, cleanup_sapi_allocations, ext_php_rs_sapi_shutdown, ext_php_rs_sapi_startup,
};
pub(super) use ext_php_rs::ffi::{
php_module_shutdown, php_module_startup, php_request_shutdown, php_request_startup,
sapi_startup,
};
}
#[cfg(not(feature = "embed"))]
mod sapi {
use std::os::raw::c_void;
pub(super) use ext_php_rs::ffi::sapi_module_struct as SapiModule;
use ext_php_rs::ffi::zend_result;
pub(super) unsafe fn php_request_startup() -> zend_result {
unreachable!("no PHP engine without the embed feature")
}
pub(super) unsafe fn php_request_shutdown(_: *mut c_void) {
unreachable!("no PHP engine without the embed feature")
}
pub(super) unsafe fn php_module_shutdown() {
unreachable!("no PHP engine without the embed feature")
}
pub(super) unsafe fn ext_php_rs_sapi_shutdown() {
unreachable!("no PHP engine without the embed feature")
}
pub(super) unsafe fn cleanup_sapi_allocations(_: *mut SapiModule) {
unreachable!("no PHP engine without the embed feature")
}
}
use ext_php_rs::types::Zval;
use speedyspec_hooks::{Key, SharedHooks, Value};
use crate::boundary::{
CallError, ENGINE, call_php, class_name, discard_exception, drain, fatal_error, find_function,
guard, handle_queued_oom, release_later, settle_stray, table_as_zval, take_thrown,
};
use crate::convert;
use crate::hook_class;
use crate::sapi::{INI_ENTRIES, OUTPUT_TO_STDERR, flush, log_message, ub_write};
const HOOK_EXCEPTION_PHP: &str = r"namespace SpeedySpec\Hooks;
/**
* Reports a hook failure that is not a callback's own exception, such as a broken backend.
*/
class HookException extends \RuntimeException
{
}
";
const STD_HANDLES_PHP: &str = r"\define('STDIN', \fopen('php://stdin', 'rb'));
\define('STDOUT', \fopen('php://stdout', 'wb'));
\define('STDERR', \fopen('php://stderr', 'wb'));
";
const STD_HANDLES_LABEL: &str = "speedyspec://std-handles";
const HOOK_EXCEPTION_LABEL: &str = "speedyspec://hook-exception";
const DUMMY_FRAME_FUNCTION: &str = "strlen";
static BOOTED: AtomicBool = AtomicBool::new(false);
#[derive(Debug)]
#[non_exhaustive]
pub enum PhpError {
Boot(String),
Exception {
class: String,
message: String,
file: String,
line: u32,
},
Fatal {
message: String,
file: String,
line: u32,
},
Exit(i32),
NulByte,
ScriptNotFound(PathBuf),
NonUtf8Path(PathBuf),
Conversion(String),
}
impl fmt::Display for PhpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Boot(why) => write!(f, "PHP failed to start: {why}"),
Self::Exception {
class,
message,
file,
line,
} => write!(f, "{file}:{line}: uncaught {class}: {message}"),
Self::Fatal {
message,
file,
line,
} => write!(f, "{file}:{line}: PHP fatal error: {message}"),
Self::Exit(status) => write!(f, "PHP code called exit({status})"),
Self::NulByte => f.write_str("PHP input contains a NUL byte"),
Self::ScriptNotFound(path) => write!(f, "PHP script not found: {}", path.display()),
Self::NonUtf8Path(path) => {
write!(f, "PHP script path is not valid UTF-8: {}", path.display())
}
Self::Conversion(why) => write!(f, "PHP value conversion failed: {why}"),
}
}
}
impl std::error::Error for PhpError {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Output {
#[default]
Stdout,
Stderr,
}
pub struct BootOptions<'a> {
pub hooks: SharedHooks,
pub preload: &'a [(&'a str, &'a str)],
pub areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
}
pub struct Php {
sapi: *mut SapiModule,
preload: Vec<(String, String)>,
_not_send: PhantomData<*mut ()>,
}
impl Php {
pub fn boot(options: BootOptions<'_>) -> Result<Self, PhpError> {
if BOOTED.swap(true, Ordering::SeqCst) {
return Err(PhpError::Boot(
"PHP is already booted in this process".to_owned(),
));
}
let sapi = start_engine(options.areas)?;
let php = Self {
sapi,
preload: options
.preload
.iter()
.map(|(name, source)| ((*name).to_owned(), (*source).to_owned()))
.collect(),
_not_send: PhantomData,
};
let dummy = unsafe { find_function(DUMMY_FRAME_FUNCTION) };
if dummy.is_null() {
return Err(PhpError::Boot(format!(
"the native function {DUMMY_FRAME_FUNCTION}() is not registered"
)));
}
ENGINE.with(|e| {
e.dummy_func.set(dummy);
e.alive.set(true);
});
hook_class::install(options.hooks);
speedyspec_hooks::set_opaque_reader(speedyspec_hooks::OpaqueReader {
readable: convert::readable_opaque,
read: convert::read_opaque,
});
php.request_setup()?;
Ok(php)
}
fn request_setup(&self) -> Result<(), PhpError> {
execute(
HOOK_EXCEPTION_LABEL,
HOOK_EXCEPTION_PHP.as_bytes(),
_zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
)?;
hook_class::find_exception_class()?;
execute(
STD_HANDLES_LABEL,
STD_HANDLES_PHP.as_bytes(),
_zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
)?;
for (name, source) in &self.preload {
execute(
name,
source.as_bytes(),
_zend_compile_position_ZEND_COMPILE_POSITION_AT_OPEN_TAG,
)?;
}
crate::area::request_start();
Ok(())
}
pub fn restart_request(&self) -> Result<(), PhpError> {
self.end_request();
self.start_request()?;
self.request_setup()
}
fn end_request(&self) {
if !crate::boundary::alive() {
return;
}
settle_stray();
unsafe { php_request_shutdown(ptr::null_mut()) };
ENGINE.with(|e| {
e.alive.set(false);
let queued = std::mem::take(&mut *e.releases.borrow_mut());
drop(queued); let current = e.take_current();
let saved = std::mem::take(&mut *e.contexts.borrow_mut());
drop(current);
drop(saved);
});
}
fn start_request(&self) -> Result<(), PhpError> {
unsafe {
if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
return Err(PhpError::Boot("php_request_startup failed".to_owned()));
}
(*ext_php_rs_compiler_globals()).skip_shebang = true;
request_started();
}
ENGINE.with(|e| e.alive.set(true));
Ok(())
}
pub fn serve(&self, request: &mut dyn crate::web::WebRequest, script: &Path) -> Served {
self.end_request();
let param = |name: &str| {
request
.params()
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.clone())
};
let c = |value: Option<String>| value.and_then(|v| CString::new(v).ok());
let method = c(param("REQUEST_METHOD").or(Some("GET".into())));
let query = c(param("QUERY_STRING"));
let uri = c(param("REQUEST_URI"));
let content_type = c(param("CONTENT_TYPE"));
let content_length = param("CONTENT_LENGTH")
.and_then(|v| v.parse::<i64>().ok())
.unwrap_or(-1);
let script_c = c(script.to_str().map(str::to_owned));
let ptr_of = |v: &Option<CString>| {
v.as_ref()
.map_or(ptr::null_mut(), |s| s.as_ptr().cast_mut())
};
crate::web::begin(request);
unsafe {
let sg = &raw mut ext_php_rs::ffi::sapi_globals;
(*sg).server_context = (&raw mut SERVER_CONTEXT).cast();
(*sg).request_info.request_method = ptr_of(&method);
(*sg).request_info.query_string = ptr_of(&query);
(*sg).request_info.request_uri = ptr_of(&uri);
(*sg).request_info.content_type = ptr_of(&content_type);
(*sg).request_info.content_length = content_length;
(*sg).request_info.path_translated = ptr_of(&script_c);
(*sg).request_info.proto_num = 1001;
(*sg).sapi_headers.http_response_code = 200;
}
let started = self.start_request();
let mut served = Served {
result: Ok(()),
peak_memory: 0,
poisoned: false,
headers_sent: false,
};
match started {
Err(err) => served.result = Err(err),
Ok(()) => {
served.result = self
.request_setup()
.and_then(|()| self.require(script).map(|_| ()))
.or_else(|err| match err {
PhpError::Exit(_) => Ok(()),
other => Err(other),
});
if served.result.is_err() {
unsafe {
let sg = &raw mut ext_php_rs::ffi::sapi_globals;
if (*sg).headers_sent == 0 {
(*sg).sapi_headers.http_response_code = 500;
}
}
}
served.peak_memory = unsafe { zend_memory_peak_usage(true) } as u64;
served.poisoned = self.poisoned();
self.end_request();
}
}
served.headers_sent = crate::web::STATE.with(|s| s.borrow().headers_sent);
crate::web::end();
unsafe {
let sg = &raw mut ext_php_rs::ffi::sapi_globals;
(*sg).server_context = ptr::null_mut();
(*sg).request_info.request_method = ptr::null();
(*sg).request_info.query_string = ptr::null_mut();
(*sg).request_info.request_uri = ptr::null_mut();
(*sg).request_info.content_type = ptr::null();
(*sg).request_info.content_length = 0;
(*sg).request_info.path_translated = ptr::null_mut();
(*sg).request_info.cookie_data = ptr::null_mut();
}
drop((method, query, uri, content_type, script_c));
served
}
pub fn eval(&self, label: &str, code: &str) -> Result<Value, PhpError> {
execute(
label,
code.as_bytes(),
_zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
)
}
pub fn require(&self, path: &Path) -> Result<Value, PhpError> {
let label = path
.to_str()
.ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
if label.contains('\0') {
return Err(PhpError::NulByte);
}
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
let absolute = absolute
.to_str()
.ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
let code = format!("return require {};", php_quote(absolute));
self.eval(label, &code)
}
pub fn run_file(&self, path: &Path, argv: &[String]) -> Result<i32, PhpError> {
let script = path
.to_str()
.ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
if !path.is_file() {
return Err(PhpError::ScriptNotFound(path.to_owned()));
}
let mut code = String::from("$GLOBALS['argv'] = [");
for arg in std::iter::once(script).chain(argv.iter().map(String::as_str)) {
code.push_str(&php_quote(arg));
code.push(',');
}
code.push_str(
"]; $GLOBALS['argc'] = \\count($GLOBALS['argv']); \
$_SERVER['argv'] = $GLOBALS['argv']; $_SERVER['argc'] = $GLOBALS['argc'];",
);
let quoted = php_quote(script);
code.push_str(&format!(
" $_SERVER['SCRIPT_NAME'] = {quoted}; $_SERVER['SCRIPT_FILENAME'] = {quoted}; \
$_SERVER['PHP_SELF'] = {quoted};"
));
self.eval("speedyspec://argv", &code)?;
unsafe { (*ext_php_rs_executor_globals()).exit_status = 0 };
match self.require(path) {
Ok(_) => Ok(0),
Err(PhpError::Exit(status)) => Ok(status),
Err(err) => Err(err),
}
}
pub fn call(&self, callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
call(callable, args)
}
}
pub fn call(callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
{
if !crate::boundary::alive() {
return Err(PhpError::Boot("no PHP request is open".to_owned()));
}
settle_stray();
let mut target = ManuallyDrop::new(Zval::new());
let target_ptr: *mut zval = &raw mut *target;
let written = guard(|| {
unsafe { convert::write_value(target_ptr, callable) }
});
let outcome = match written {
Ok(Ok(())) => call_php(target_ptr, args),
Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
Err(interrupted) => Err(CallError::Interrupted(interrupted)),
};
release_later(target);
settle_stray();
outcome.map_err(CallError::into_php_error)
}
}
#[derive(Debug)]
pub struct CallFailure {
pub error: PhpError,
pub exception: Option<Value>,
}
pub fn call_catching(callable: &Value, args: &[Value]) -> Result<Value, CallFailure> {
let plain = |error: PhpError| CallFailure {
error,
exception: None,
};
if !crate::boundary::alive() {
return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
}
settle_stray();
let mut target = ManuallyDrop::new(Zval::new());
let target_ptr: *mut zval = &raw mut *target;
let written = guard(|| {
unsafe { convert::write_value(target_ptr, callable) }
});
let outcome = match written {
Ok(Ok(())) => call_php(target_ptr, args),
Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
Err(interrupted) => Err(CallError::Interrupted(interrupted)),
};
release_later(target);
settle_stray();
outcome.map_err(failure_of)
}
pub(crate) fn failure_of(err: CallError) -> CallFailure {
match err {
CallError::Thrown(crate::boundary::Thrown::Exception {
object,
class,
message,
file,
line,
}) => CallFailure {
error: PhpError::Exception {
class,
message,
file,
line,
},
exception: Some(Value::Opaque(std::rc::Rc::new(object))),
},
other => CallFailure {
error: other.into_php_error(),
exception: None,
},
}
}
static EXTRA_INI: std::sync::OnceLock<&'static std::ffi::CStr> = std::sync::OnceLock::new();
pub fn set_ini(settings: &[(String, String)]) -> Result<(), String> {
let mut entries = INI_ENTRIES.to_string_lossy().into_owned();
for (key, value) in settings {
let bad = |s: &str| s.contains(['"', '\n', '\r', '\0']) || s.is_empty();
if bad(key) || key.contains('=') || value.contains(['"', '\n', '\r', '\0']) {
return Err(format!(
"the INI setting {key:?} = {value:?} cannot be passed to PHP"
));
}
entries.push_str(&format!("{key}=\"{value}\"\n"));
}
let entries = CString::new(entries).map_err(|err| err.to_string())?;
EXTRA_INI
.set(Box::leak(entries.into_boxed_c_str()))
.map_err(|_| "the INI settings are already set".to_string())
}
unsafe fn request_started() {
unsafe { ext_php_rs::ffi::core_globals.during_request_startup = false };
}
#[derive(Debug)]
pub struct Served {
pub result: Result<(), PhpError>,
pub peak_memory: u64,
pub poisoned: bool,
pub headers_sent: bool,
}
static mut SERVER_CONTEXT: [u64; 4] = [0; 4];
unsafe extern "C" {
fn zend_memory_peak_usage(real_usage: bool) -> usize;
}
pub fn global(name: &str) -> Option<Value> {
if !crate::boundary::alive() {
return None;
}
unsafe {
let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
let slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
if slot.is_null() {
return None;
}
let value = convert::deref(slot);
if u32::from(convert::type_of(value)) == ext_php_rs::ffi::IS_UNDEF {
return None;
}
convert::to_value(value).ok()
}
}
pub fn set_global(name: &str, value: &Value) -> Result<(), PhpError> {
if !crate::boundary::alive() {
return Err(PhpError::Boot("no PHP request is open".to_owned()));
}
let mut fresh = ManuallyDrop::new(Zval::new());
let fresh_ptr: *mut zval = &raw mut *fresh;
let written = guard(|| {
unsafe { convert::write_value(fresh_ptr, value) }
});
match written {
Ok(Ok(())) => {}
Ok(Err(why)) => {
release_later(fresh);
return Err(PhpError::Conversion(why.to_string()));
}
Err(interrupted) => return Err(fatal_error(interrupted)),
}
let name_ptr = name.as_ptr();
let name_len = name.len();
let replaced = guard(|| {
unsafe {
let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
let slot = ext_php_rs::ffi::zend_hash_str_find(table, name_ptr.cast(), name_len);
if slot.is_null() {
ext_php_rs::ffi::zend_hash_str_update(table, name_ptr.cast(), name_len, fresh_ptr);
return None;
}
let mut target = slot;
if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_INDIRECT {
target = (*target).value.zv;
}
if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_REFERENCE {
target = &raw mut (*(*target).value.ref_).val;
}
let old: Zval = ptr::read(target);
(*target).value = (*fresh_ptr).value;
(*target).u1 = (*fresh_ptr).u1;
Some(old)
}
});
match replaced {
Ok(Some(old)) => {
release_later(ManuallyDrop::new(old));
settle_stray();
Ok(())
}
Ok(None) => Ok(()),
Err(interrupted) => Err(fatal_error(interrupted)),
}
}
pub(crate) unsafe fn global_slot(name: &str) -> Option<*mut zval> {
unsafe {
let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
let mut slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
if slot.is_null() {
return None;
}
if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_INDIRECT {
slot = (*slot).value.zv;
}
if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_REFERENCE {
slot = &raw mut (*(*slot).value.ref_).val;
}
Some(slot)
}
}
unsafe fn separate_array(zv: *mut zval) {
unsafe {
let ht = (*zv).value.arr;
let counted = u32::from((*zv).u1.v.type_flags) & ext_php_rs::ffi::IS_TYPE_REFCOUNTED != 0;
if counted && (*ht).gc.refcount == 1 {
return;
}
let dup = ext_php_rs::ffi::zend_array_dup(ht);
if counted {
(*ht).gc.refcount -= 1;
}
(*zv).value.arr = dup;
(*zv).u1.type_info = ext_php_rs::ffi::IS_ARRAY_EX;
}
}
pub fn global_push(name: &str, value: &Value) -> Result<bool, PhpError> {
if !crate::boundary::alive() {
return Err(PhpError::Boot("no PHP request is open".to_owned()));
}
let mut fresh = ManuallyDrop::new(Zval::new());
let fresh_ptr: *mut zval = &raw mut *fresh;
let pushed = guard(|| -> Result<bool, convert::Unconvertible> {
unsafe {
let Some(slot) = global_slot(name) else {
return Ok(false);
};
if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
return Ok(false);
}
convert::write_value(fresh_ptr, value)?;
separate_array(slot);
if ext_php_rs::ffi::zend_hash_next_index_insert((*slot).value.arr, fresh_ptr).is_null()
{
return Ok(false);
}
(*fresh_ptr).u1.type_info = ext_php_rs::ffi::IS_UNDEF;
Ok(true)
}
});
release_later(fresh);
match pushed {
Ok(Ok(done)) => Ok(done),
Ok(Err(why)) => Err(PhpError::Conversion(why.to_string())),
Err(interrupted) => Err(fatal_error(interrupted)),
}
}
pub fn global_pop(name: &str) -> Result<bool, PhpError> {
if !crate::boundary::alive() {
return Err(PhpError::Boot("no PHP request is open".to_owned()));
}
let popped = guard(|| {
unsafe {
let Some(slot) = global_slot(name) else {
return false;
};
if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
return false;
}
if (*(*slot).value.arr).nNumOfElements == 0 {
return true;
}
separate_array(slot);
convert::pop_last((*slot).value.arr);
true
}
});
match popped {
Ok(done) => {
settle_stray();
Ok(done)
}
Err(interrupted) => Err(fatal_error(interrupted)),
}
}
pub fn object_id(value: &Value) -> Option<u64> {
let object = convert::handle_of(value)?.object()?;
Some(u64::from(unsafe { (*object).handle }))
}
impl Php {
pub fn construct(&self, class: &str, args: &[Value]) -> Result<Value, PhpError> {
let factory = self.eval(
"speedyspec:construct",
"return static fn (string $class, array $arguments) => new $class(...$arguments);",
)?;
let arguments = Value::Array(
args.iter()
.enumerate()
.map(|(index, value)| (Key::Int(index as i64), value.clone()))
.collect(),
);
self.call(&factory, &[Value::Str(class.to_owned()), arguments])
}
pub fn class_of(&self, value: &Value) -> Option<String> {
let obj = convert::handle_of(value)?.object()?;
Some(unsafe { class_name(obj) })
}
pub fn properties_of(&self, value: &Value) -> Option<Vec<(String, Value)>> {
let obj = convert::handle_of(value)?.object()?;
settle_stray();
let table = guard(|| {
unsafe { (*(*obj).handlers).get_properties.map(|get| get(obj)) }
});
let table = match table {
Ok(Some(table)) if !table.is_null() => table,
_ => return None,
};
if let Some(thrown) = take_thrown() {
drop(thrown);
settle_stray();
return None;
}
let mut props = Vec::new();
let read = unsafe { convert::to_value(&raw const *table_as_zval(table)) };
let Ok(Value::Array(items)) = read else {
return None;
};
for (key, item) in items {
match key {
speedyspec_hooks::Key::Str(name) if name.starts_with('\0') => {}
speedyspec_hooks::Key::Str(name) => props.push((name, item)),
speedyspec_hooks::Key::Int(i) => props.push((i.to_string(), item)),
}
}
Some(props)
}
pub fn poisoned(&self) -> bool {
ENGINE.with(|e| e.poisoned.get())
}
pub fn set_owner(&self, owner: Option<&str>) {
hook_class::set_owner(owner);
}
pub fn redirect_output(&self, to: Output) {
flush(ptr::null_mut());
OUTPUT_TO_STDERR.store(to == Output::Stderr, Ordering::SeqCst);
}
fn execute_in(
label: &str,
code: &[u8],
position: zend_compile_position,
) -> Result<Value, PhpError> {
let label = CString::new(label).map_err(|_| PhpError::NulByte)?;
let label_ptr = label.as_ptr();
settle_stray();
let mut retval = ManuallyDrop::new(Zval::new());
let retval_ptr: *mut zval = &raw mut *retval;
let source: Cell<*mut zend_string> = Cell::new(ptr::null_mut());
let op_array: Cell<*mut zend_op_array> = Cell::new(ptr::null_mut());
let saved_options = unsafe { (*ext_php_rs_compiler_globals()).compiler_options };
let ran = guard(|| {
unsafe {
source.set(ext_php_rs_zend_string_init(
code.as_ptr().cast(),
code.len(),
false,
));
let cg = ext_php_rs_compiler_globals();
(*cg).compiler_options = 0; let compile = zend_compile_string.expect("zend_compile_string is always set");
let op = compile(source.get(), label_ptr, position);
(*cg).compiler_options = saved_options;
if op.is_null() {
return; }
op_array.set(op);
(*op).scope = zend_get_executed_scope();
let eg = ext_php_rs_executor_globals();
(*eg).no_extensions = true;
zend_execute(op, retval_ptr);
(*eg).no_extensions = false;
handle_queued_oom();
zend_destroy_static_vars(op);
destroy_op_array(op);
efree(op.cast());
op_array.set(ptr::null_mut());
}
});
unsafe {
(*ext_php_rs_compiler_globals()).compiler_options = saved_options;
(*ext_php_rs_executor_globals()).no_extensions = false;
}
let fatal = ran.err().map(fatal_error);
let op = op_array.get();
if !op.is_null() {
let _ = guard(|| {
unsafe {
destroy_op_array(op);
efree(op.cast());
}
});
}
let src = source.get();
if !src.is_null() {
unsafe { ext_php_rs_zend_string_release(src) };
}
let value = unsafe { convert::to_value(retval_ptr) };
release_later(retval);
drain();
if let Some(fatal) = fatal {
discard_exception();
return Err(fatal);
}
if let Some(thrown) = take_thrown() {
return Err(thrown.into_php_error());
}
value.map_err(|e| PhpError::Conversion(e.to_string()))
}
}
#[cfg(feature = "embed")]
fn start_engine(
areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
) -> Result<*mut SapiModule, PhpError> {
let sapi = sapi::SapiBuilder::new("speedyspec", "SpeedySpec")
.ub_write_function(ub_write)
.flush_function(flush)
.log_message_function(log_message)
.send_headers_function(crate::web::send_headers)
.read_post_function(crate::web::read_post)
.read_cookies_function(crate::web::read_cookies)
.register_server_variables_function(crate::web::register_server_variables)
.php_ini_ignore(1)
.build()
.map_err(|e| PhpError::Boot(format!("building the SAPI: {e}")))?;
let sapi = Box::into_raw(Box::new(sapi));
unsafe {
sapi::ext_php_rs_sapi_startup();
sapi::sapi_startup(sapi);
(*sapi).ini_entries = EXTRA_INI.get().copied().unwrap_or(INI_ENTRIES).as_ptr();
crate::area::install(areas);
if sapi::php_module_startup(sapi, hook_class::module_entry()) != ZEND_RESULT_CODE_SUCCESS {
return Err(PhpError::Boot("php_module_startup failed".to_owned()));
}
if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
return Err(PhpError::Boot("php_request_startup failed".to_owned()));
}
(*ext_php_rs_compiler_globals()).skip_shebang = true;
request_started();
}
Ok(sapi)
}
#[cfg(not(feature = "embed"))]
fn start_engine(_: Vec<std::rc::Rc<dyn crate::NativeArea>>) -> Result<*mut SapiModule, PhpError> {
Err(PhpError::Boot(
"speedyspec-php was built without its `embed` feature".to_owned(),
))
}
impl Drop for Php {
fn drop(&mut self) {
settle_stray();
if crate::boundary::alive() {
unsafe { php_request_shutdown(ptr::null_mut()) };
}
let parked_panic = ENGINE.with(|e| {
e.alive.set(false);
let queued = std::mem::take(&mut *e.releases.borrow_mut());
drop(queued); let current = e.take_current();
let saved = std::mem::take(&mut *e.contexts.borrow_mut());
drop(current);
drop(saved);
e.panic.borrow_mut().take()
});
hook_class::uninstall();
crate::area::uninstall();
unsafe {
php_module_shutdown();
sapi_shutdown();
ext_php_rs_sapi_shutdown();
cleanup_sapi_allocations(self.sapi);
drop(Box::from_raw(self.sapi));
}
if let Some(payload) = parked_panic
&& !std::thread::panicking()
{
resume_unwind(payload);
}
}
}
fn php_quote(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('\'');
for c in s.chars() {
if c == '\\' || c == '\'' {
out.push('\\');
}
out.push(c);
}
out.push('\'');
out
}
fn execute(label: &str, code: &[u8], position: zend_compile_position) -> Result<Value, PhpError> {
Php::execute_in(label, code, position)
}
pub fn eval(label: &str, code: &str) -> Result<Value, PhpError> {
if !crate::boundary::alive() {
return Err(PhpError::Boot("no PHP request is open".to_owned()));
}
execute(
label,
code.as_bytes(),
_zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
)
}