1use std::cell::Cell;
13use std::ffi::CString;
14use std::fmt;
15use std::marker::PhantomData;
16use std::mem::ManuallyDrop;
17use std::panic::resume_unwind;
18use std::path::{Path, PathBuf};
19use std::ptr;
20use std::sync::atomic::{AtomicBool, Ordering};
21
22use ext_php_rs::alloc::efree;
23use ext_php_rs::ffi::{
24 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
25 _zend_compile_position_ZEND_COMPILE_POSITION_AT_OPEN_TAG, ZEND_RESULT_CODE_SUCCESS,
26 destroy_op_array, ext_php_rs_compiler_globals, ext_php_rs_executor_globals,
27 ext_php_rs_zend_string_init, ext_php_rs_zend_string_release, sapi_shutdown,
28 zend_compile_position, zend_compile_string, zend_destroy_static_vars, zend_execute,
29 zend_get_executed_scope, zend_op_array, zend_string, zval,
30};
31use sapi::{
32 SapiModule, cleanup_sapi_allocations, ext_php_rs_sapi_shutdown, php_module_shutdown,
33 php_request_shutdown, php_request_startup,
34};
35
36#[cfg(feature = "embed")]
38mod sapi {
39 pub(super) use ext_php_rs::builders::SapiBuilder;
40 pub(super) use ext_php_rs::embed::{
41 SapiModule, cleanup_sapi_allocations, ext_php_rs_sapi_shutdown, ext_php_rs_sapi_startup,
42 };
43 pub(super) use ext_php_rs::ffi::{
44 php_module_shutdown, php_module_startup, php_request_shutdown, php_request_startup,
45 sapi_startup,
46 };
47}
48
49#[cfg(not(feature = "embed"))]
52mod sapi {
53 use std::os::raw::c_void;
54
55 pub(super) use ext_php_rs::ffi::sapi_module_struct as SapiModule;
56 use ext_php_rs::ffi::zend_result;
57
58 pub(super) unsafe fn php_request_startup() -> zend_result {
59 unreachable!("no PHP engine without the embed feature")
60 }
61 pub(super) unsafe fn php_request_shutdown(_: *mut c_void) {
62 unreachable!("no PHP engine without the embed feature")
63 }
64 pub(super) unsafe fn php_module_shutdown() {
65 unreachable!("no PHP engine without the embed feature")
66 }
67 pub(super) unsafe fn ext_php_rs_sapi_shutdown() {
68 unreachable!("no PHP engine without the embed feature")
69 }
70 pub(super) unsafe fn cleanup_sapi_allocations(_: *mut SapiModule) {
71 unreachable!("no PHP engine without the embed feature")
72 }
73}
74use ext_php_rs::types::Zval;
75use speedyspec_hooks::{Key, SharedHooks, Value};
76
77use crate::boundary::{
78 CallError, ENGINE, call_php, class_name, discard_exception, drain, fatal_error, find_function,
79 guard, handle_queued_oom, release_later, settle_stray, table_as_zval, take_thrown,
80};
81use crate::convert;
82use crate::hook_class;
83use crate::sapi::{INI_ENTRIES, OUTPUT_TO_STDERR, flush, log_message, ub_write};
84
85const HOOK_EXCEPTION_PHP: &str = r"namespace SpeedySpec\Hooks;
87
88/**
89 * Reports a hook failure that is not a callback's own exception, such as a broken backend.
90 */
91class HookException extends \RuntimeException
92{
93}
94";
95
96const STD_HANDLES_PHP: &str = r"\define('STDIN', \fopen('php://stdin', 'rb'));
103\define('STDOUT', \fopen('php://stdout', 'wb'));
104\define('STDERR', \fopen('php://stderr', 'wb'));
105";
106
107const STD_HANDLES_LABEL: &str = "speedyspec://std-handles";
109
110const HOOK_EXCEPTION_LABEL: &str = "speedyspec://hook-exception";
112
113const DUMMY_FRAME_FUNCTION: &str = "strlen";
116
117static BOOTED: AtomicBool = AtomicBool::new(false);
118
119#[derive(Debug)]
121#[non_exhaustive]
122pub enum PhpError {
123 Boot(String),
125 Exception {
127 class: String,
128 message: String,
129 file: String,
130 line: u32,
131 },
132 Fatal {
135 message: String,
136 file: String,
137 line: u32,
138 },
139 Exit(i32),
141 NulByte,
143 ScriptNotFound(PathBuf),
145 NonUtf8Path(PathBuf),
147 Conversion(String),
149}
150
151impl fmt::Display for PhpError {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 match self {
154 Self::Boot(why) => write!(f, "PHP failed to start: {why}"),
155 Self::Exception {
156 class,
157 message,
158 file,
159 line,
160 } => write!(f, "{file}:{line}: uncaught {class}: {message}"),
161 Self::Fatal {
162 message,
163 file,
164 line,
165 } => write!(f, "{file}:{line}: PHP fatal error: {message}"),
166 Self::Exit(status) => write!(f, "PHP code called exit({status})"),
167 Self::NulByte => f.write_str("PHP input contains a NUL byte"),
168 Self::ScriptNotFound(path) => write!(f, "PHP script not found: {}", path.display()),
169 Self::NonUtf8Path(path) => {
170 write!(f, "PHP script path is not valid UTF-8: {}", path.display())
171 }
172 Self::Conversion(why) => write!(f, "PHP value conversion failed: {why}"),
173 }
174 }
175}
176
177impl std::error::Error for PhpError {}
178
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
181pub enum Output {
182 #[default]
183 Stdout,
184 Stderr,
185}
186
187pub struct BootOptions<'a> {
189 pub hooks: SharedHooks,
191 pub preload: &'a [(&'a str, &'a str)],
195 pub areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
198}
199
200pub struct Php {
215 sapi: *mut SapiModule,
216 preload: Vec<(String, String)>,
218 _not_send: PhantomData<*mut ()>,
219}
220
221impl Php {
222 pub fn boot(options: BootOptions<'_>) -> Result<Self, PhpError> {
229 if BOOTED.swap(true, Ordering::SeqCst) {
230 return Err(PhpError::Boot(
231 "PHP is already booted in this process".to_owned(),
232 ));
233 }
234
235 let sapi = start_engine(options.areas)?;
236
237 let php = Self {
239 sapi,
240 preload: options
241 .preload
242 .iter()
243 .map(|(name, source)| ((*name).to_owned(), (*source).to_owned()))
244 .collect(),
245 _not_send: PhantomData,
246 };
247
248 let dummy = unsafe { find_function(DUMMY_FRAME_FUNCTION) };
251 if dummy.is_null() {
252 return Err(PhpError::Boot(format!(
253 "the native function {DUMMY_FRAME_FUNCTION}() is not registered"
254 )));
255 }
256 ENGINE.with(|e| {
257 e.dummy_func.set(dummy);
258 e.alive.set(true);
259 });
260 hook_class::install(options.hooks);
261 speedyspec_hooks::set_opaque_reader(speedyspec_hooks::OpaqueReader {
263 readable: convert::readable_opaque,
264 read: convert::read_opaque,
265 });
266 php.request_setup()?;
267 Ok(php)
268 }
269
270 fn request_setup(&self) -> Result<(), PhpError> {
273 execute(
274 HOOK_EXCEPTION_LABEL,
275 HOOK_EXCEPTION_PHP.as_bytes(),
276 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
277 )?;
278 hook_class::find_exception_class()?;
279 execute(
280 STD_HANDLES_LABEL,
281 STD_HANDLES_PHP.as_bytes(),
282 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
283 )?;
284 for (name, source) in &self.preload {
285 execute(
286 name,
287 source.as_bytes(),
288 _zend_compile_position_ZEND_COMPILE_POSITION_AT_OPEN_TAG,
289 )?;
290 }
291 crate::area::request_start();
292 Ok(())
293 }
294
295 pub fn restart_request(&self) -> Result<(), PhpError> {
298 self.end_request();
299 self.start_request()?;
300 self.request_setup()
301 }
302
303 fn end_request(&self) {
305 if !crate::boundary::alive() {
306 return;
307 }
308 settle_stray();
309 unsafe { php_request_shutdown(ptr::null_mut()) };
311 ENGINE.with(|e| {
312 e.alive.set(false);
313 let queued = std::mem::take(&mut *e.releases.borrow_mut());
314 drop(queued); let current = e.take_current();
316 let saved = std::mem::take(&mut *e.contexts.borrow_mut());
317 drop(current);
318 drop(saved);
319 });
320 }
321
322 fn start_request(&self) -> Result<(), PhpError> {
324 unsafe {
326 if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
327 return Err(PhpError::Boot("php_request_startup failed".to_owned()));
328 }
329 (*ext_php_rs_compiler_globals()).skip_shebang = true;
330 request_started();
331 }
332 ENGINE.with(|e| e.alive.set(true));
333 Ok(())
334 }
335
336 pub fn serve(&self, request: &mut dyn crate::web::WebRequest, script: &Path) -> Served {
341 self.end_request();
342 let param = |name: &str| {
343 request
344 .params()
345 .iter()
346 .find(|(k, _)| k == name)
347 .map(|(_, v)| v.clone())
348 };
349 let c = |value: Option<String>| value.and_then(|v| CString::new(v).ok());
350 let method = c(param("REQUEST_METHOD").or(Some("GET".into())));
351 let query = c(param("QUERY_STRING"));
352 let uri = c(param("REQUEST_URI"));
353 let content_type = c(param("CONTENT_TYPE"));
354 let content_length = param("CONTENT_LENGTH")
355 .and_then(|v| v.parse::<i64>().ok())
356 .unwrap_or(-1);
357 let script_c = c(script.to_str().map(str::to_owned));
358 let ptr_of = |v: &Option<CString>| {
359 v.as_ref()
360 .map_or(ptr::null_mut(), |s| s.as_ptr().cast_mut())
361 };
362 crate::web::begin(request);
363 unsafe {
365 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
366 (*sg).server_context = (&raw mut SERVER_CONTEXT).cast();
367 (*sg).request_info.request_method = ptr_of(&method);
368 (*sg).request_info.query_string = ptr_of(&query);
369 (*sg).request_info.request_uri = ptr_of(&uri);
370 (*sg).request_info.content_type = ptr_of(&content_type);
371 (*sg).request_info.content_length = content_length;
372 (*sg).request_info.path_translated = ptr_of(&script_c);
373 (*sg).request_info.proto_num = 1001;
374 (*sg).sapi_headers.http_response_code = 200;
376 }
377 let started = self.start_request();
378 let mut served = Served {
379 result: Ok(()),
380 peak_memory: 0,
381 poisoned: false,
382 headers_sent: false,
383 };
384 match started {
385 Err(err) => served.result = Err(err),
386 Ok(()) => {
387 served.result = self
388 .request_setup()
389 .and_then(|()| self.require(script).map(|_| ()))
390 .or_else(|err| match err {
391 PhpError::Exit(_) => Ok(()),
392 other => Err(other),
393 });
394 if served.result.is_err() {
395 unsafe {
397 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
398 if (*sg).headers_sent == 0 {
399 (*sg).sapi_headers.http_response_code = 500;
400 }
401 }
402 }
403 served.peak_memory = unsafe { zend_memory_peak_usage(true) } as u64;
405 served.poisoned = self.poisoned();
406 self.end_request();
407 }
408 }
409 served.headers_sent = crate::web::STATE.with(|s| s.borrow().headers_sent);
410 crate::web::end();
411 unsafe {
413 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
414 (*sg).server_context = ptr::null_mut();
415 (*sg).request_info.request_method = ptr::null();
416 (*sg).request_info.query_string = ptr::null_mut();
417 (*sg).request_info.request_uri = ptr::null_mut();
418 (*sg).request_info.content_type = ptr::null();
419 (*sg).request_info.content_length = 0;
420 (*sg).request_info.path_translated = ptr::null_mut();
421 (*sg).request_info.cookie_data = ptr::null_mut();
423 }
424 drop((method, query, uri, content_type, script_c));
425 served
426 }
427
428 pub fn eval(&self, label: &str, code: &str) -> Result<Value, PhpError> {
432 execute(
433 label,
434 code.as_bytes(),
435 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
436 )
437 }
438
439 pub fn require(&self, path: &Path) -> Result<Value, PhpError> {
444 let label = path
445 .to_str()
446 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
447 if label.contains('\0') {
448 return Err(PhpError::NulByte);
449 }
450 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
451 let absolute = absolute
452 .to_str()
453 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
454 let code = format!("return require {};", php_quote(absolute));
455 self.eval(label, &code)
456 }
457
458 pub fn run_file(&self, path: &Path, argv: &[String]) -> Result<i32, PhpError> {
464 let script = path
465 .to_str()
466 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
467 if !path.is_file() {
468 return Err(PhpError::ScriptNotFound(path.to_owned()));
469 }
470
471 let mut code = String::from("$GLOBALS['argv'] = [");
472 for arg in std::iter::once(script).chain(argv.iter().map(String::as_str)) {
473 code.push_str(&php_quote(arg));
474 code.push(',');
475 }
476 code.push_str(
477 "]; $GLOBALS['argc'] = \\count($GLOBALS['argv']); \
478 $_SERVER['argv'] = $GLOBALS['argv']; $_SERVER['argc'] = $GLOBALS['argc'];",
479 );
480 let quoted = php_quote(script);
482 code.push_str(&format!(
483 " $_SERVER['SCRIPT_NAME'] = {quoted}; $_SERVER['SCRIPT_FILENAME'] = {quoted}; \
484 $_SERVER['PHP_SELF'] = {quoted};"
485 ));
486 self.eval("speedyspec://argv", &code)?;
487
488 unsafe { (*ext_php_rs_executor_globals()).exit_status = 0 };
490 match self.require(path) {
491 Ok(_) => Ok(0),
492 Err(PhpError::Exit(status)) => Ok(status),
493 Err(err) => Err(err),
494 }
495 }
496
497 pub fn call(&self, callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
500 call(callable, args)
501 }
502}
503
504pub fn call(callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
507 {
508 if !crate::boundary::alive() {
509 return Err(PhpError::Boot("no PHP request is open".to_owned()));
510 }
511 settle_stray();
512 let mut target = ManuallyDrop::new(Zval::new());
513 let target_ptr: *mut zval = &raw mut *target;
514 let written = guard(|| {
515 unsafe { convert::write_value(target_ptr, callable) }
517 });
518 let outcome = match written {
519 Ok(Ok(())) => call_php(target_ptr, args),
520 Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
521 Err(interrupted) => Err(CallError::Interrupted(interrupted)),
522 };
523 release_later(target);
524 settle_stray();
527 outcome.map_err(CallError::into_php_error)
528 }
529}
530
531#[derive(Debug)]
534pub struct CallFailure {
535 pub error: PhpError,
536 pub exception: Option<Value>,
537}
538
539pub fn call_catching(callable: &Value, args: &[Value]) -> Result<Value, CallFailure> {
541 let plain = |error: PhpError| CallFailure {
542 error,
543 exception: None,
544 };
545 if !crate::boundary::alive() {
546 return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
547 }
548 settle_stray();
549 let mut target = ManuallyDrop::new(Zval::new());
550 let target_ptr: *mut zval = &raw mut *target;
551 let written = guard(|| {
552 unsafe { convert::write_value(target_ptr, callable) }
554 });
555 let outcome = match written {
556 Ok(Ok(())) => call_php(target_ptr, args),
557 Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
558 Err(interrupted) => Err(CallError::Interrupted(interrupted)),
559 };
560 release_later(target);
561 settle_stray();
562 outcome.map_err(failure_of)
563}
564
565pub(crate) fn failure_of(err: CallError) -> CallFailure {
567 match err {
568 CallError::Thrown(crate::boundary::Thrown::Exception {
569 object,
570 class,
571 message,
572 file,
573 line,
574 }) => CallFailure {
575 error: PhpError::Exception {
576 class,
577 message,
578 file,
579 line,
580 },
581 exception: Some(Value::Opaque(std::rc::Rc::new(object))),
582 },
583 other => CallFailure {
584 error: other.into_php_error(),
585 exception: None,
586 },
587 }
588}
589
590static EXTRA_INI: std::sync::OnceLock<&'static std::ffi::CStr> = std::sync::OnceLock::new();
592
593pub fn set_ini(settings: &[(String, String)]) -> Result<(), String> {
597 let mut entries = INI_ENTRIES.to_string_lossy().into_owned();
598 for (key, value) in settings {
599 let bad = |s: &str| s.contains(['"', '\n', '\r', '\0']) || s.is_empty();
600 if bad(key) || key.contains('=') || value.contains(['"', '\n', '\r', '\0']) {
601 return Err(format!(
602 "the INI setting {key:?} = {value:?} cannot be passed to PHP"
603 ));
604 }
605 entries.push_str(&format!("{key}=\"{value}\"\n"));
606 }
607 let entries = CString::new(entries).map_err(|err| err.to_string())?;
608 EXTRA_INI
609 .set(Box::leak(entries.into_boxed_c_str()))
610 .map_err(|_| "the INI settings are already set".to_string())
611}
612
613unsafe fn request_started() {
621 unsafe { ext_php_rs::ffi::core_globals.during_request_startup = false };
623}
624
625#[derive(Debug)]
627pub struct Served {
628 pub result: Result<(), PhpError>,
630 pub peak_memory: u64,
632 pub poisoned: bool,
634 pub headers_sent: bool,
635}
636
637static mut SERVER_CONTEXT: [u64; 4] = [0; 4];
639
640unsafe extern "C" {
641 fn zend_memory_peak_usage(real_usage: bool) -> usize;
642}
643
644pub fn global(name: &str) -> Option<Value> {
646 if !crate::boundary::alive() {
647 return None;
648 }
649 unsafe {
652 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
653 let slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
654 if slot.is_null() {
655 return None;
656 }
657 let value = convert::deref(slot);
658 if u32::from(convert::type_of(value)) == ext_php_rs::ffi::IS_UNDEF {
659 return None;
660 }
661 convert::to_value(value).ok()
662 }
663}
664
665pub fn set_global(name: &str, value: &Value) -> Result<(), PhpError> {
667 if !crate::boundary::alive() {
668 return Err(PhpError::Boot("no PHP request is open".to_owned()));
669 }
670 let mut fresh = ManuallyDrop::new(Zval::new());
671 let fresh_ptr: *mut zval = &raw mut *fresh;
672 let written = guard(|| {
673 unsafe { convert::write_value(fresh_ptr, value) }
675 });
676 match written {
677 Ok(Ok(())) => {}
678 Ok(Err(why)) => {
679 release_later(fresh);
680 return Err(PhpError::Conversion(why.to_string()));
681 }
682 Err(interrupted) => return Err(fatal_error(interrupted)),
683 }
684 let name_ptr = name.as_ptr();
685 let name_len = name.len();
686 let replaced = guard(|| {
687 unsafe {
690 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
691 let slot = ext_php_rs::ffi::zend_hash_str_find(table, name_ptr.cast(), name_len);
692 if slot.is_null() {
693 ext_php_rs::ffi::zend_hash_str_update(table, name_ptr.cast(), name_len, fresh_ptr);
694 return None;
695 }
696 let mut target = slot;
697 if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_INDIRECT {
698 target = (*target).value.zv;
699 }
700 if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_REFERENCE {
701 target = &raw mut (*(*target).value.ref_).val;
702 }
703 let old: Zval = ptr::read(target);
704 ptr::copy_nonoverlapping(fresh_ptr, target, 1);
705 Some(old)
706 }
707 });
708 match replaced {
709 Ok(Some(old)) => {
710 release_later(ManuallyDrop::new(old));
711 settle_stray();
712 Ok(())
713 }
714 Ok(None) => Ok(()),
715 Err(interrupted) => Err(fatal_error(interrupted)),
716 }
717}
718
719pub(crate) unsafe fn global_slot(name: &str) -> Option<*mut zval> {
725 unsafe {
727 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
728 let mut slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
729 if slot.is_null() {
730 return None;
731 }
732 if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_INDIRECT {
733 slot = (*slot).value.zv;
734 }
735 if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_REFERENCE {
736 slot = &raw mut (*(*slot).value.ref_).val;
737 }
738 Some(slot)
739 }
740}
741
742unsafe fn separate_array(zv: *mut zval) {
748 unsafe {
750 let ht = (*zv).value.arr;
751 let counted = u32::from((*zv).u1.v.type_flags) & ext_php_rs::ffi::IS_TYPE_REFCOUNTED != 0;
752 if counted && (*ht).gc.refcount == 1 {
753 return;
754 }
755 let dup = ext_php_rs::ffi::zend_array_dup(ht);
756 if counted {
757 (*ht).gc.refcount -= 1;
759 }
760 (*zv).value.arr = dup;
761 (*zv).u1.type_info = ext_php_rs::ffi::IS_ARRAY_EX;
762 }
763}
764
765pub fn global_push(name: &str, value: &Value) -> Result<bool, PhpError> {
768 if !crate::boundary::alive() {
769 return Err(PhpError::Boot("no PHP request is open".to_owned()));
770 }
771 let mut fresh = ManuallyDrop::new(Zval::new());
772 let fresh_ptr: *mut zval = &raw mut *fresh;
773 let pushed = guard(|| -> Result<bool, convert::Unconvertible> {
774 unsafe {
777 let Some(slot) = global_slot(name) else {
778 return Ok(false);
779 };
780 if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
781 return Ok(false);
782 }
783 convert::write_value(fresh_ptr, value)?;
784 separate_array(slot);
785 if ext_php_rs::ffi::zend_hash_next_index_insert((*slot).value.arr, fresh_ptr).is_null()
786 {
787 return Ok(false);
789 }
790 (*fresh_ptr).u1.type_info = ext_php_rs::ffi::IS_UNDEF;
791 Ok(true)
792 }
793 });
794 release_later(fresh);
795 match pushed {
796 Ok(Ok(done)) => Ok(done),
797 Ok(Err(why)) => Err(PhpError::Conversion(why.to_string())),
798 Err(interrupted) => Err(fatal_error(interrupted)),
799 }
800}
801
802pub fn global_pop(name: &str) -> Result<bool, PhpError> {
805 if !crate::boundary::alive() {
806 return Err(PhpError::Boot("no PHP request is open".to_owned()));
807 }
808 let popped = guard(|| {
809 unsafe {
812 let Some(slot) = global_slot(name) else {
813 return false;
814 };
815 if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
816 return false;
817 }
818 if (*(*slot).value.arr).nNumOfElements == 0 {
819 return true;
820 }
821 separate_array(slot);
822 convert::pop_last((*slot).value.arr);
823 true
824 }
825 });
826 match popped {
827 Ok(done) => {
828 settle_stray();
829 Ok(done)
830 }
831 Err(interrupted) => Err(fatal_error(interrupted)),
832 }
833}
834
835pub fn object_id(value: &Value) -> Option<u64> {
837 let object = convert::handle_of(value)?.object()?;
838 Some(u64::from(unsafe { (*object).handle }))
840}
841
842impl Php {
843 pub fn construct(&self, class: &str, args: &[Value]) -> Result<Value, PhpError> {
846 let factory = self.eval(
849 "speedyspec:construct",
850 "return static fn (string $class, array $arguments) => new $class(...$arguments);",
851 )?;
852 let arguments = Value::Array(
853 args.iter()
854 .enumerate()
855 .map(|(index, value)| (Key::Int(index as i64), value.clone()))
856 .collect(),
857 );
858 self.call(&factory, &[Value::Str(class.to_owned()), arguments])
859 }
860
861 pub fn class_of(&self, value: &Value) -> Option<String> {
864 let obj = convert::handle_of(value)?.object()?;
865 Some(unsafe { class_name(obj) })
867 }
868
869 pub fn properties_of(&self, value: &Value) -> Option<Vec<(String, Value)>> {
873 let obj = convert::handle_of(value)?.object()?;
874 settle_stray();
875 let table = guard(|| {
877 unsafe { (*(*obj).handlers).get_properties.map(|get| get(obj)) }
880 });
881 let table = match table {
882 Ok(Some(table)) if !table.is_null() => table,
883 _ => return None,
884 };
885 if let Some(thrown) = take_thrown() {
886 drop(thrown);
887 settle_stray();
888 return None;
889 }
890 let mut props = Vec::new();
891 let read = unsafe { convert::to_value(&raw const *table_as_zval(table)) };
894 let Ok(Value::Array(items)) = read else {
895 return None;
896 };
897 for (key, item) in items {
898 match key {
899 speedyspec_hooks::Key::Str(name) if name.starts_with('\0') => {}
902 speedyspec_hooks::Key::Str(name) => props.push((name, item)),
903 speedyspec_hooks::Key::Int(i) => props.push((i.to_string(), item)),
904 }
905 }
906 Some(props)
907 }
908
909 pub fn poisoned(&self) -> bool {
925 ENGINE.with(|e| e.poisoned.get())
926 }
927
928 pub fn set_owner(&self, owner: Option<&str>) {
931 hook_class::set_owner(owner);
932 }
933
934 pub fn redirect_output(&self, to: Output) {
936 flush(ptr::null_mut());
937 OUTPUT_TO_STDERR.store(to == Output::Stderr, Ordering::SeqCst);
938 }
939
940 fn execute_in(
942 label: &str,
943 code: &[u8],
944 position: zend_compile_position,
945 ) -> Result<Value, PhpError> {
946 let label = CString::new(label).map_err(|_| PhpError::NulByte)?;
947 let label_ptr = label.as_ptr();
948 settle_stray();
949
950 let mut retval = ManuallyDrop::new(Zval::new());
952 let retval_ptr: *mut zval = &raw mut *retval;
953 let source: Cell<*mut zend_string> = Cell::new(ptr::null_mut());
954 let op_array: Cell<*mut zend_op_array> = Cell::new(ptr::null_mut());
955 let saved_options = unsafe { (*ext_php_rs_compiler_globals()).compiler_options };
957
958 let ran = guard(|| {
959 unsafe {
963 source.set(ext_php_rs_zend_string_init(
964 code.as_ptr().cast(),
965 code.len(),
966 false,
967 ));
968 let cg = ext_php_rs_compiler_globals();
969 (*cg).compiler_options = 0; let compile = zend_compile_string.expect("zend_compile_string is always set");
971 let op = compile(source.get(), label_ptr, position);
972 (*cg).compiler_options = saved_options;
973 if op.is_null() {
974 return; }
976 op_array.set(op);
977 (*op).scope = zend_get_executed_scope();
978 let eg = ext_php_rs_executor_globals();
979 (*eg).no_extensions = true;
980 zend_execute(op, retval_ptr);
981 (*eg).no_extensions = false;
982 handle_queued_oom();
983 zend_destroy_static_vars(op);
984 destroy_op_array(op);
985 efree(op.cast());
986 op_array.set(ptr::null_mut());
987 }
988 });
989
990 unsafe {
992 (*ext_php_rs_compiler_globals()).compiler_options = saved_options;
993 (*ext_php_rs_executor_globals()).no_extensions = false;
994 }
995 let fatal = ran.err().map(fatal_error);
996 let op = op_array.get();
997 if !op.is_null() {
998 let _ = guard(|| {
1002 unsafe {
1004 destroy_op_array(op);
1005 efree(op.cast());
1006 }
1007 });
1008 }
1009 let src = source.get();
1010 if !src.is_null() {
1011 unsafe { ext_php_rs_zend_string_release(src) };
1014 }
1015
1016 let value = unsafe { convert::to_value(retval_ptr) };
1018 release_later(retval);
1019 drain();
1020 if let Some(fatal) = fatal {
1021 discard_exception();
1022 return Err(fatal);
1023 }
1024 if let Some(thrown) = take_thrown() {
1025 return Err(thrown.into_php_error());
1026 }
1027 value.map_err(|e| PhpError::Conversion(e.to_string()))
1028 }
1029}
1030
1031#[cfg(feature = "embed")]
1034fn start_engine(
1035 areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
1036) -> Result<*mut SapiModule, PhpError> {
1037 let sapi = sapi::SapiBuilder::new("speedyspec", "SpeedySpec")
1038 .ub_write_function(ub_write)
1039 .flush_function(flush)
1040 .log_message_function(log_message)
1041 .send_headers_function(crate::web::send_headers)
1042 .read_post_function(crate::web::read_post)
1043 .read_cookies_function(crate::web::read_cookies)
1044 .register_server_variables_function(crate::web::register_server_variables)
1045 .php_ini_ignore(1)
1046 .build()
1047 .map_err(|e| PhpError::Boot(format!("building the SAPI: {e}")))?;
1048 let sapi = Box::into_raw(Box::new(sapi));
1053
1054 unsafe {
1059 sapi::ext_php_rs_sapi_startup();
1060 sapi::sapi_startup(sapi);
1061 (*sapi).ini_entries = EXTRA_INI.get().copied().unwrap_or(INI_ENTRIES).as_ptr();
1062 crate::area::install(areas);
1063 if sapi::php_module_startup(sapi, hook_class::module_entry()) != ZEND_RESULT_CODE_SUCCESS {
1064 return Err(PhpError::Boot("php_module_startup failed".to_owned()));
1065 }
1066 if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
1067 return Err(PhpError::Boot("php_request_startup failed".to_owned()));
1068 }
1069 (*ext_php_rs_compiler_globals()).skip_shebang = true;
1071 request_started();
1072 }
1073 Ok(sapi)
1074}
1075
1076#[cfg(not(feature = "embed"))]
1078fn start_engine(_: Vec<std::rc::Rc<dyn crate::NativeArea>>) -> Result<*mut SapiModule, PhpError> {
1079 Err(PhpError::Boot(
1080 "speedyspec-php was built without its `embed` feature".to_owned(),
1081 ))
1082}
1083
1084impl Drop for Php {
1085 fn drop(&mut self) {
1086 settle_stray();
1090 if crate::boundary::alive() {
1094 unsafe { php_request_shutdown(ptr::null_mut()) };
1095 }
1096
1097 let parked_panic = ENGINE.with(|e| {
1104 e.alive.set(false);
1105 let queued = std::mem::take(&mut *e.releases.borrow_mut());
1106 drop(queued); let current = e.take_current();
1108 let saved = std::mem::take(&mut *e.contexts.borrow_mut());
1109 drop(current);
1110 drop(saved);
1111 e.panic.borrow_mut().take()
1112 });
1113 hook_class::uninstall();
1114 crate::area::uninstall();
1115
1116 unsafe {
1119 php_module_shutdown();
1120 sapi_shutdown();
1121 ext_php_rs_sapi_shutdown();
1122 cleanup_sapi_allocations(self.sapi);
1123 drop(Box::from_raw(self.sapi));
1124 }
1125
1126 if let Some(payload) = parked_panic
1128 && !std::thread::panicking()
1129 {
1130 resume_unwind(payload);
1131 }
1132 }
1133}
1134
1135fn php_quote(s: &str) -> String {
1137 let mut out = String::with_capacity(s.len() + 2);
1138 out.push('\'');
1139 for c in s.chars() {
1140 if c == '\\' || c == '\'' {
1141 out.push('\\');
1142 }
1143 out.push(c);
1144 }
1145 out.push('\'');
1146 out
1147}
1148
1149fn execute(label: &str, code: &[u8], position: zend_compile_position) -> Result<Value, PhpError> {
1151 Php::execute_in(label, code, position)
1152}
1153
1154pub fn eval(label: &str, code: &str) -> Result<Value, PhpError> {
1157 if !crate::boundary::alive() {
1158 return Err(PhpError::Boot("no PHP request is open".to_owned()));
1159 }
1160 execute(
1161 label,
1162 code.as_bytes(),
1163 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
1164 )
1165}