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 speedyspec_hooks::set_opaque_writer(speedyspec_hooks::OpaqueWriter {
268 assign: crate::reference::assign,
269 });
270 php.request_setup()?;
271 Ok(php)
272 }
273
274 fn request_setup(&self) -> Result<(), PhpError> {
277 execute(
278 HOOK_EXCEPTION_LABEL,
279 HOOK_EXCEPTION_PHP.as_bytes(),
280 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
281 )?;
282 hook_class::find_exception_class()?;
283 execute(
284 STD_HANDLES_LABEL,
285 STD_HANDLES_PHP.as_bytes(),
286 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
287 )?;
288 for (name, source) in &self.preload {
289 execute(
290 name,
291 source.as_bytes(),
292 _zend_compile_position_ZEND_COMPILE_POSITION_AT_OPEN_TAG,
293 )?;
294 }
295 crate::area::request_start();
296 Ok(())
297 }
298
299 pub fn restart_request(&self) -> Result<(), PhpError> {
302 self.end_request();
303 self.start_request()?;
304 self.request_setup()
305 }
306
307 fn end_request(&self) {
309 if !crate::boundary::alive() {
310 return;
311 }
312 settle_stray();
313 unsafe { php_request_shutdown(ptr::null_mut()) };
315 ENGINE.with(|e| {
316 e.alive.set(false);
317 let queued = std::mem::take(&mut *e.releases.borrow_mut());
318 drop(queued); let current = e.take_current();
320 let saved = std::mem::take(&mut *e.contexts.borrow_mut());
321 drop(current);
322 drop(saved);
323 });
324 }
325
326 fn start_request(&self) -> Result<(), PhpError> {
328 unsafe {
330 if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
331 return Err(PhpError::Boot("php_request_startup failed".to_owned()));
332 }
333 (*ext_php_rs_compiler_globals()).skip_shebang = true;
334 request_started();
335 }
336 ENGINE.with(|e| e.alive.set(true));
337 Ok(())
338 }
339
340 pub fn serve(&self, request: &mut dyn crate::web::WebRequest, script: &Path) -> Served {
345 self.end_request();
346 let param = |name: &str| {
347 request
348 .params()
349 .iter()
350 .find(|(k, _)| k == name)
351 .map(|(_, v)| v.clone())
352 };
353 let c = |value: Option<String>| value.and_then(|v| CString::new(v).ok());
354 let method = c(param("REQUEST_METHOD").or(Some("GET".into())));
355 let query = c(param("QUERY_STRING"));
356 let uri = c(param("REQUEST_URI"));
357 let content_type = c(param("CONTENT_TYPE"));
358 let content_length = param("CONTENT_LENGTH")
359 .and_then(|v| v.parse::<i64>().ok())
360 .unwrap_or(-1);
361 let script_c = c(script.to_str().map(str::to_owned));
362 let ptr_of = |v: &Option<CString>| {
363 v.as_ref()
364 .map_or(ptr::null_mut(), |s| s.as_ptr().cast_mut())
365 };
366 crate::web::begin(request);
367 unsafe {
369 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
370 (*sg).server_context = (&raw mut SERVER_CONTEXT).cast();
371 (*sg).request_info.request_method = ptr_of(&method);
372 (*sg).request_info.query_string = ptr_of(&query);
373 (*sg).request_info.request_uri = ptr_of(&uri);
374 (*sg).request_info.content_type = ptr_of(&content_type);
375 (*sg).request_info.content_length = content_length;
376 (*sg).request_info.path_translated = ptr_of(&script_c);
377 (*sg).request_info.proto_num = 1001;
378 (*sg).sapi_headers.http_response_code = 200;
380 }
381 let started = self.start_request();
382 let mut served = Served {
383 result: Ok(()),
384 peak_memory: 0,
385 poisoned: false,
386 headers_sent: false,
387 };
388 match started {
389 Err(err) => served.result = Err(err),
390 Ok(()) => {
391 served.result = self
392 .request_setup()
393 .and_then(|()| self.require(script).map(|_| ()))
394 .or_else(|err| match err {
395 PhpError::Exit(_) => Ok(()),
396 other => Err(other),
397 });
398 if served.result.is_err() {
399 unsafe {
401 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
402 if (*sg).headers_sent == 0 {
403 (*sg).sapi_headers.http_response_code = 500;
404 }
405 }
406 }
407 served.peak_memory = unsafe { zend_memory_peak_usage(true) } as u64;
409 served.poisoned = self.poisoned();
410 self.end_request();
411 }
412 }
413 served.headers_sent = crate::web::STATE.with(|s| s.borrow().headers_sent);
414 crate::web::end();
415 unsafe {
417 let sg = &raw mut ext_php_rs::ffi::sapi_globals;
418 (*sg).server_context = ptr::null_mut();
419 (*sg).request_info.request_method = ptr::null();
420 (*sg).request_info.query_string = ptr::null_mut();
421 (*sg).request_info.request_uri = ptr::null_mut();
422 (*sg).request_info.content_type = ptr::null();
423 (*sg).request_info.content_length = 0;
424 (*sg).request_info.path_translated = ptr::null_mut();
425 (*sg).request_info.cookie_data = ptr::null_mut();
427 }
428 drop((method, query, uri, content_type, script_c));
429 served
430 }
431
432 pub fn eval(&self, label: &str, code: &str) -> Result<Value, PhpError> {
436 execute(
437 label,
438 code.as_bytes(),
439 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
440 )
441 }
442
443 pub fn require(&self, path: &Path) -> Result<Value, PhpError> {
448 let label = path
449 .to_str()
450 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
451 if label.contains('\0') {
452 return Err(PhpError::NulByte);
453 }
454 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
455 let absolute = absolute
456 .to_str()
457 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
458 let code = format!("return require {};", php_quote(absolute));
459 self.eval(label, &code)
460 }
461
462 pub fn run_file(&self, path: &Path, argv: &[String]) -> Result<i32, PhpError> {
468 let script = path
469 .to_str()
470 .ok_or_else(|| PhpError::NonUtf8Path(path.to_owned()))?;
471 if !path.is_file() {
472 return Err(PhpError::ScriptNotFound(path.to_owned()));
473 }
474
475 let mut code = String::from("$GLOBALS['argv'] = [");
476 for arg in std::iter::once(script).chain(argv.iter().map(String::as_str)) {
477 code.push_str(&php_quote(arg));
478 code.push(',');
479 }
480 code.push_str(
481 "]; $GLOBALS['argc'] = \\count($GLOBALS['argv']); \
482 $_SERVER['argv'] = $GLOBALS['argv']; $_SERVER['argc'] = $GLOBALS['argc'];",
483 );
484 let quoted = php_quote(script);
486 code.push_str(&format!(
487 " $_SERVER['SCRIPT_NAME'] = {quoted}; $_SERVER['SCRIPT_FILENAME'] = {quoted}; \
488 $_SERVER['PHP_SELF'] = {quoted};"
489 ));
490 self.eval("speedyspec://argv", &code)?;
491
492 unsafe { (*ext_php_rs_executor_globals()).exit_status = 0 };
494 match self.require(path) {
495 Ok(_) => Ok(0),
496 Err(PhpError::Exit(status)) => Ok(status),
497 Err(err) => Err(err),
498 }
499 }
500
501 pub fn call(&self, callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
504 call(callable, args)
505 }
506}
507
508pub fn call(callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
511 {
512 if !crate::boundary::alive() {
513 return Err(PhpError::Boot("no PHP request is open".to_owned()));
514 }
515 settle_stray();
516 let mut target = ManuallyDrop::new(Zval::new());
517 let target_ptr: *mut zval = &raw mut *target;
518 let written = guard(|| {
519 unsafe { convert::write_value(target_ptr, callable) }
521 });
522 let outcome = match written {
523 Ok(Ok(())) => call_php(target_ptr, args),
524 Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
525 Err(interrupted) => Err(CallError::Interrupted(interrupted)),
526 };
527 release_later(target);
528 settle_stray();
531 outcome.map_err(CallError::into_php_error)
532 }
533}
534
535#[derive(Debug)]
538pub struct CallFailure {
539 pub error: PhpError,
540 pub exception: Option<Value>,
541}
542
543pub fn call_catching(callable: &Value, args: &[Value]) -> Result<Value, CallFailure> {
545 let plain = |error: PhpError| CallFailure {
546 error,
547 exception: None,
548 };
549 if !crate::boundary::alive() {
550 return Err(plain(PhpError::Boot("no PHP request is open".to_owned())));
551 }
552 settle_stray();
553 let mut target = ManuallyDrop::new(Zval::new());
554 let target_ptr: *mut zval = &raw mut *target;
555 let written = guard(|| {
556 unsafe { convert::write_value(target_ptr, callable) }
558 });
559 let outcome = match written {
560 Ok(Ok(())) => call_php(target_ptr, args),
561 Ok(Err(why)) => Err(CallError::Convert(why.to_string())),
562 Err(interrupted) => Err(CallError::Interrupted(interrupted)),
563 };
564 release_later(target);
565 settle_stray();
566 outcome.map_err(failure_of)
567}
568
569pub(crate) fn failure_of(err: CallError) -> CallFailure {
571 match err {
572 CallError::Thrown(crate::boundary::Thrown::Exception {
573 object,
574 class,
575 message,
576 file,
577 line,
578 }) => CallFailure {
579 error: PhpError::Exception {
580 class,
581 message,
582 file,
583 line,
584 },
585 exception: Some(Value::Opaque(std::rc::Rc::new(object))),
586 },
587 other => CallFailure {
588 error: other.into_php_error(),
589 exception: None,
590 },
591 }
592}
593
594static EXTRA_INI: std::sync::OnceLock<&'static std::ffi::CStr> = std::sync::OnceLock::new();
596
597pub fn set_ini(settings: &[(String, String)]) -> Result<(), String> {
601 let mut entries = INI_ENTRIES.to_string_lossy().into_owned();
602 for (key, value) in settings {
603 let bad = |s: &str| s.contains(['"', '\n', '\r', '\0']) || s.is_empty();
604 if bad(key) || key.contains('=') || value.contains(['"', '\n', '\r', '\0']) {
605 return Err(format!(
606 "the INI setting {key:?} = {value:?} cannot be passed to PHP"
607 ));
608 }
609 entries.push_str(&format!("{key}=\"{value}\"\n"));
610 }
611 let entries = CString::new(entries).map_err(|err| err.to_string())?;
612 EXTRA_INI
613 .set(Box::leak(entries.into_boxed_c_str()))
614 .map_err(|_| "the INI settings are already set".to_string())
615}
616
617unsafe fn request_started() {
625 unsafe { ext_php_rs::ffi::core_globals.during_request_startup = false };
627}
628
629#[derive(Debug)]
631pub struct Served {
632 pub result: Result<(), PhpError>,
634 pub peak_memory: u64,
636 pub poisoned: bool,
638 pub headers_sent: bool,
639}
640
641static mut SERVER_CONTEXT: [u64; 4] = [0; 4];
643
644unsafe extern "C" {
645 fn zend_memory_peak_usage(real_usage: bool) -> usize;
646}
647
648pub fn global(name: &str) -> Option<Value> {
650 if !crate::boundary::alive() {
651 return None;
652 }
653 unsafe {
656 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
657 let slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
658 if slot.is_null() {
659 return None;
660 }
661 let value = convert::deref(slot);
662 if u32::from(convert::type_of(value)) == ext_php_rs::ffi::IS_UNDEF {
663 return None;
664 }
665 convert::to_value(value).ok()
666 }
667}
668
669pub fn set_global(name: &str, value: &Value) -> Result<(), PhpError> {
671 if !crate::boundary::alive() {
672 return Err(PhpError::Boot("no PHP request is open".to_owned()));
673 }
674 let mut fresh = ManuallyDrop::new(Zval::new());
675 let fresh_ptr: *mut zval = &raw mut *fresh;
676 let written = guard(|| {
677 unsafe { convert::write_value(fresh_ptr, value) }
679 });
680 match written {
681 Ok(Ok(())) => {}
682 Ok(Err(why)) => {
683 release_later(fresh);
684 return Err(PhpError::Conversion(why.to_string()));
685 }
686 Err(interrupted) => return Err(fatal_error(interrupted)),
687 }
688 let name_ptr = name.as_ptr();
689 let name_len = name.len();
690 let replaced = guard(|| {
691 unsafe {
694 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
695 let slot = ext_php_rs::ffi::zend_hash_str_find(table, name_ptr.cast(), name_len);
696 if slot.is_null() {
697 ext_php_rs::ffi::zend_hash_str_update(table, name_ptr.cast(), name_len, fresh_ptr);
698 return None;
699 }
700 let mut target = slot;
701 if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_INDIRECT {
702 target = (*target).value.zv;
703 }
704 if u32::from(convert::type_of(target)) == ext_php_rs::ffi::IS_REFERENCE {
705 target = &raw mut (*(*target).value.ref_).val;
706 }
707 let old: Zval = ptr::read(target);
708 (*target).value = (*fresh_ptr).value;
710 (*target).u1 = (*fresh_ptr).u1;
711 Some(old)
712 }
713 });
714 match replaced {
715 Ok(Some(old)) => {
716 release_later(ManuallyDrop::new(old));
717 settle_stray();
718 Ok(())
719 }
720 Ok(None) => Ok(()),
721 Err(interrupted) => Err(fatal_error(interrupted)),
722 }
723}
724
725pub(crate) unsafe fn global_slot(name: &str) -> Option<*mut zval> {
731 unsafe {
733 let table = &raw mut (*ext_php_rs_executor_globals()).symbol_table;
734 let mut slot = ext_php_rs::ffi::zend_hash_str_find(table, name.as_ptr().cast(), name.len());
735 if slot.is_null() {
736 return None;
737 }
738 if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_INDIRECT {
739 slot = (*slot).value.zv;
740 }
741 if u32::from(convert::type_of(slot)) == ext_php_rs::ffi::IS_REFERENCE {
742 slot = &raw mut (*(*slot).value.ref_).val;
743 }
744 Some(slot)
745 }
746}
747
748unsafe fn separate_array(zv: *mut zval) {
754 unsafe {
756 let ht = (*zv).value.arr;
757 let counted = u32::from((*zv).u1.v.type_flags) & ext_php_rs::ffi::IS_TYPE_REFCOUNTED != 0;
758 if counted && (*ht).gc.refcount == 1 {
759 return;
760 }
761 let dup = ext_php_rs::ffi::zend_array_dup(ht);
762 if counted {
763 (*ht).gc.refcount -= 1;
765 }
766 (*zv).value.arr = dup;
767 (*zv).u1.type_info = ext_php_rs::ffi::IS_ARRAY_EX;
768 }
769}
770
771pub fn global_push(name: &str, value: &Value) -> Result<bool, PhpError> {
774 if !crate::boundary::alive() {
775 return Err(PhpError::Boot("no PHP request is open".to_owned()));
776 }
777 let mut fresh = ManuallyDrop::new(Zval::new());
778 let fresh_ptr: *mut zval = &raw mut *fresh;
779 let pushed = guard(|| -> Result<bool, convert::Unconvertible> {
780 unsafe {
783 let Some(slot) = global_slot(name) else {
784 return Ok(false);
785 };
786 if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
787 return Ok(false);
788 }
789 convert::write_value(fresh_ptr, value)?;
790 separate_array(slot);
791 if ext_php_rs::ffi::zend_hash_next_index_insert((*slot).value.arr, fresh_ptr).is_null()
792 {
793 return Ok(false);
795 }
796 (*fresh_ptr).u1.type_info = ext_php_rs::ffi::IS_UNDEF;
797 Ok(true)
798 }
799 });
800 release_later(fresh);
801 match pushed {
802 Ok(Ok(done)) => Ok(done),
803 Ok(Err(why)) => Err(PhpError::Conversion(why.to_string())),
804 Err(interrupted) => Err(fatal_error(interrupted)),
805 }
806}
807
808pub fn global_pop(name: &str) -> Result<bool, PhpError> {
811 if !crate::boundary::alive() {
812 return Err(PhpError::Boot("no PHP request is open".to_owned()));
813 }
814 let popped = guard(|| {
815 unsafe {
818 let Some(slot) = global_slot(name) else {
819 return false;
820 };
821 if u32::from(convert::type_of(slot)) != ext_php_rs::ffi::IS_ARRAY {
822 return false;
823 }
824 if (*(*slot).value.arr).nNumOfElements == 0 {
825 return true;
826 }
827 separate_array(slot);
828 convert::pop_last((*slot).value.arr);
829 true
830 }
831 });
832 match popped {
833 Ok(done) => {
834 settle_stray();
835 Ok(done)
836 }
837 Err(interrupted) => Err(fatal_error(interrupted)),
838 }
839}
840
841pub fn object_id(value: &Value) -> Option<u64> {
843 let object = convert::handle_of(value)?.object()?;
844 Some(u64::from(unsafe { (*object).handle }))
846}
847
848impl Php {
849 pub fn construct(&self, class: &str, args: &[Value]) -> Result<Value, PhpError> {
852 let factory = self.eval(
855 "speedyspec:construct",
856 "return static fn (string $class, array $arguments) => new $class(...$arguments);",
857 )?;
858 let arguments = Value::Array(
859 args.iter()
860 .enumerate()
861 .map(|(index, value)| (Key::Int(index as i64), value.clone()))
862 .collect(),
863 );
864 self.call(&factory, &[Value::Str(class.to_owned()), arguments])
865 }
866
867 pub fn class_of(&self, value: &Value) -> Option<String> {
870 let obj = convert::handle_of(value)?.object()?;
871 Some(unsafe { class_name(obj) })
873 }
874
875 pub fn properties_of(&self, value: &Value) -> Option<Vec<(String, Value)>> {
879 let obj = convert::handle_of(value)?.object()?;
880 settle_stray();
881 let table = guard(|| {
883 unsafe { (*(*obj).handlers).get_properties.map(|get| get(obj)) }
886 });
887 let table = match table {
888 Ok(Some(table)) if !table.is_null() => table,
889 _ => return None,
890 };
891 if let Some(thrown) = take_thrown() {
892 drop(thrown);
893 settle_stray();
894 return None;
895 }
896 let mut props = Vec::new();
897 let read = unsafe { convert::to_value(&raw const *table_as_zval(table)) };
900 let Ok(Value::Array(items)) = read else {
901 return None;
902 };
903 for (key, item) in items {
904 match key {
905 speedyspec_hooks::Key::Str(name) if name.starts_with('\0') => {}
908 speedyspec_hooks::Key::Str(name) => props.push((name, item)),
909 speedyspec_hooks::Key::Int(i) => props.push((i.to_string(), item)),
910 }
911 }
912 Some(props)
913 }
914
915 pub fn poisoned(&self) -> bool {
931 ENGINE.with(|e| e.poisoned.get())
932 }
933
934 pub fn set_owner(&self, owner: Option<&str>) {
937 hook_class::set_owner(owner);
938 }
939
940 pub fn redirect_output(&self, to: Output) {
942 flush(ptr::null_mut());
943 OUTPUT_TO_STDERR.store(to == Output::Stderr, Ordering::SeqCst);
944 }
945
946 fn execute_in(
948 label: &str,
949 code: &[u8],
950 position: zend_compile_position,
951 ) -> Result<Value, PhpError> {
952 let label = CString::new(label).map_err(|_| PhpError::NulByte)?;
953 let label_ptr = label.as_ptr();
954 settle_stray();
955
956 let mut retval = ManuallyDrop::new(Zval::new());
958 let retval_ptr: *mut zval = &raw mut *retval;
959 let source: Cell<*mut zend_string> = Cell::new(ptr::null_mut());
960 let op_array: Cell<*mut zend_op_array> = Cell::new(ptr::null_mut());
961 let saved_options = unsafe { (*ext_php_rs_compiler_globals()).compiler_options };
963
964 let ran = guard(|| {
965 unsafe {
969 source.set(ext_php_rs_zend_string_init(
970 code.as_ptr().cast(),
971 code.len(),
972 false,
973 ));
974 let cg = ext_php_rs_compiler_globals();
975 (*cg).compiler_options = 0; let compile = zend_compile_string.expect("zend_compile_string is always set");
977 let op = compile(source.get(), label_ptr, position);
978 (*cg).compiler_options = saved_options;
979 if op.is_null() {
980 return; }
982 op_array.set(op);
983 (*op).scope = zend_get_executed_scope();
984 let eg = ext_php_rs_executor_globals();
985 (*eg).no_extensions = true;
986 zend_execute(op, retval_ptr);
987 (*eg).no_extensions = false;
988 handle_queued_oom();
989 zend_destroy_static_vars(op);
990 destroy_op_array(op);
991 efree(op.cast());
992 op_array.set(ptr::null_mut());
993 }
994 });
995
996 unsafe {
998 (*ext_php_rs_compiler_globals()).compiler_options = saved_options;
999 (*ext_php_rs_executor_globals()).no_extensions = false;
1000 }
1001 let fatal = ran.err().map(fatal_error);
1002 let op = op_array.get();
1003 if !op.is_null() {
1004 let _ = guard(|| {
1008 unsafe {
1010 destroy_op_array(op);
1011 efree(op.cast());
1012 }
1013 });
1014 }
1015 let src = source.get();
1016 if !src.is_null() {
1017 unsafe { ext_php_rs_zend_string_release(src) };
1020 }
1021
1022 let value = unsafe { convert::to_value(retval_ptr) };
1024 release_later(retval);
1025 drain();
1026 if let Some(fatal) = fatal {
1027 discard_exception();
1028 return Err(fatal);
1029 }
1030 if let Some(thrown) = take_thrown() {
1031 return Err(thrown.into_php_error());
1032 }
1033 value.map_err(|e| PhpError::Conversion(e.to_string()))
1034 }
1035}
1036
1037#[cfg(feature = "embed")]
1040fn start_engine(
1041 areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
1042) -> Result<*mut SapiModule, PhpError> {
1043 let sapi = sapi::SapiBuilder::new("speedyspec", "SpeedySpec")
1044 .ub_write_function(ub_write)
1045 .flush_function(flush)
1046 .log_message_function(log_message)
1047 .send_headers_function(crate::web::send_headers)
1048 .read_post_function(crate::web::read_post)
1049 .read_cookies_function(crate::web::read_cookies)
1050 .register_server_variables_function(crate::web::register_server_variables)
1051 .php_ini_ignore(1)
1052 .build()
1053 .map_err(|e| PhpError::Boot(format!("building the SAPI: {e}")))?;
1054 let sapi = Box::into_raw(Box::new(sapi));
1059
1060 unsafe {
1065 sapi::ext_php_rs_sapi_startup();
1066 sapi::sapi_startup(sapi);
1067 (*sapi).ini_entries = EXTRA_INI.get().copied().unwrap_or(INI_ENTRIES).as_ptr();
1068 crate::area::install(areas);
1069 if sapi::php_module_startup(sapi, hook_class::module_entry()) != ZEND_RESULT_CODE_SUCCESS {
1070 return Err(PhpError::Boot("php_module_startup failed".to_owned()));
1071 }
1072 if php_request_startup() != ZEND_RESULT_CODE_SUCCESS {
1073 return Err(PhpError::Boot("php_request_startup failed".to_owned()));
1074 }
1075 (*ext_php_rs_compiler_globals()).skip_shebang = true;
1077 request_started();
1078 }
1079 Ok(sapi)
1080}
1081
1082#[cfg(not(feature = "embed"))]
1084fn start_engine(_: Vec<std::rc::Rc<dyn crate::NativeArea>>) -> Result<*mut SapiModule, PhpError> {
1085 Err(PhpError::Boot(
1086 "speedyspec-php was built without its `embed` feature".to_owned(),
1087 ))
1088}
1089
1090impl Drop for Php {
1091 fn drop(&mut self) {
1092 settle_stray();
1096 if crate::boundary::alive() {
1100 unsafe { php_request_shutdown(ptr::null_mut()) };
1101 }
1102
1103 let parked_panic = ENGINE.with(|e| {
1110 e.alive.set(false);
1111 let queued = std::mem::take(&mut *e.releases.borrow_mut());
1112 drop(queued); let current = e.take_current();
1114 let saved = std::mem::take(&mut *e.contexts.borrow_mut());
1115 drop(current);
1116 drop(saved);
1117 e.panic.borrow_mut().take()
1118 });
1119 hook_class::uninstall();
1120 crate::area::uninstall();
1121
1122 unsafe {
1125 php_module_shutdown();
1126 sapi_shutdown();
1127 ext_php_rs_sapi_shutdown();
1128 cleanup_sapi_allocations(self.sapi);
1129 drop(Box::from_raw(self.sapi));
1130 }
1131
1132 if let Some(payload) = parked_panic
1134 && !std::thread::panicking()
1135 {
1136 resume_unwind(payload);
1137 }
1138 }
1139}
1140
1141fn php_quote(s: &str) -> String {
1143 let mut out = String::with_capacity(s.len() + 2);
1144 out.push('\'');
1145 for c in s.chars() {
1146 if c == '\\' || c == '\'' {
1147 out.push('\\');
1148 }
1149 out.push(c);
1150 }
1151 out.push('\'');
1152 out
1153}
1154
1155fn execute(label: &str, code: &[u8], position: zend_compile_position) -> Result<Value, PhpError> {
1157 Php::execute_in(label, code, position)
1158}
1159
1160pub fn eval(label: &str, code: &str) -> Result<Value, PhpError> {
1163 if !crate::boundary::alive() {
1164 return Err(PhpError::Boot("no PHP request is open".to_owned()));
1165 }
1166 execute(
1167 label,
1168 code.as_bytes(),
1169 _zend_compile_position_ZEND_COMPILE_POSITION_AFTER_OPEN_TAG,
1170 )
1171}