Skip to main content

speedyspec_php/
runtime.rs

1//! Boots the embedded PHP engine, runs code in it, and keeps PHP's error
2//! handling on PHP's side of the boundary.
3//!
4//! The engine runs under a small custom SAPI built with ext-php-rs's
5//! `SapiBuilder` rather than PHP's stock embed SAPI, because only
6//! `php_module_startup` lets us hand PHP our own module: that module is how
7//! functions and classes implemented in Rust become visible to PHP.
8//!
9//! The boundary rules (bailouts, exceptions, `exit()`, fibers) live in
10//! [`crate::boundary`]; the SAPI's INI entries and callbacks in [`crate::sapi`].
11
12use 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/// The SAPI and engine start and stop calls, which only ext-php-rs's `embed` feature provides.
37#[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/// Without the `embed` feature (the docs.rs build, whose ext-php-rs bindings lack the embed symbols) no engine can
50/// start: [`Php::boot`] fails before anything here could run, so none of these is ever called.
51#[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
85/// `SpeedySpec\Hooks\HookException`, evaluated at boot before the preload.
86const 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
96/// The CLI's `STDIN`, `STDOUT` and `STDERR` constants, evaluated at boot: PHP's
97/// CLI SAPI defines them (`sapi/cli/php_cli.c`, `cli_register_file_handles`)
98/// and scripts expect `fwrite(STDERR, ...)` to work. They are plain
99/// `php://std*` streams on the process's file descriptors, so a write to
100/// `STDOUT` reaches fd 1 directly and is not affected by
101/// [`Php::redirect_output`], exactly as `php://stdout` is not.
102const 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
107/// Stands in for the file name of [`STD_HANDLES_PHP`] in PHP's messages.
108const STD_HANDLES_LABEL: &str = "speedyspec://std-handles";
109
110/// Stands in for the file name of [`HOOK_EXCEPTION_PHP`] in PHP's messages.
111const HOOK_EXCEPTION_LABEL: &str = "speedyspec://hook-exception";
112
113/// An internal function whose `zend_function` gives a dummy frame something
114/// to point at; any internal function would do.
115const DUMMY_FRAME_FUNCTION: &str = "strlen";
116
117static BOOTED: AtomicBool = AtomicBool::new(false);
118
119/// Why PHP could not boot or run something.
120#[derive(Debug)]
121#[non_exhaustive]
122pub enum PhpError {
123    /// The engine could not start (or was already started in this process).
124    Boot(String),
125    /// PHP code threw something that nothing caught.
126    Exception {
127        class: String,
128        message: String,
129        file: String,
130        line: u32,
131    },
132    /// PHP hit a fatal error and abandoned the code it was running. The
133    /// engine is usable afterwards but degraded; see [`Php::poisoned`].
134    Fatal {
135        message: String,
136        file: String,
137        line: u32,
138    },
139    /// The code called `exit()` or `die()` with this status.
140    Exit(i32),
141    /// A label, code string or path contained a NUL byte.
142    NulByte,
143    /// The script passed to `run_file` does not exist.
144    ScriptNotFound(PathBuf),
145    /// The path is not valid UTF-8, so it cannot be handed to PHP as `$argv`.
146    NonUtf8Path(PathBuf),
147    /// A value could not be converted between PHP and Rust.
148    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/// Where PHP's output (`echo`, error display, ...) is written.
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
181pub enum Output {
182    #[default]
183    Stdout,
184    Stderr,
185}
186
187/// What [`Php::boot`] needs.
188pub struct BootOptions<'a> {
189    /// The hook registry PHP's `SpeedySpec\Hooks\Hook` uses.
190    pub hooks: SharedHooks,
191    /// `(file name, PHP source)` pairs evaluated at boot, in order, before
192    /// any other PHP code. The source is a file's content, `<?php` tag and
193    /// all; the name stands in for the file name in PHP's messages.
194    pub preload: &'a [(&'a str, &'a str)],
195    /// The extension's native areas: their functions and classes are registered at module startup, and their
196    /// request hooks run on every request.
197    pub areas: Vec<std::rc::Rc<dyn crate::NativeArea>>,
198}
199
200/// A booted PHP engine with one request open.
201///
202/// There is at most one per process, and it is neither `Send` nor `Sync`:
203/// the build is non-thread-safe, so PHP must only be touched from the thread
204/// that booted it. Dropping it shuts PHP down.
205///
206/// # PHP values that outlive the engine
207///
208/// Dropping `Php` first releases every PHP value Rust has already let go of,
209/// then ends the request, which destroys every PHP object, including those
210/// Rust still holds (PHP callbacks in the registry, `Value::Opaque`s kept by
211/// Rust code). Those handles are inert from then on: dropping one releases
212/// nothing (the engine freed the memory), and firing a hook whose callback is
213/// a PHP callable returns a `CallbackError` without touching PHP.
214pub struct Php {
215    sapi: *mut SapiModule,
216    /// The preload, kept to run again at the start of every later request.
217    preload: Vec<(String, String)>,
218    _not_send: PhantomData<*mut ()>,
219}
220
221impl Php {
222    /// Starts PHP, opens the request that all later calls run in, defines
223    /// `SpeedySpec\Hooks\HookException` and the CLI's `STDIN`, `STDOUT` and
224    /// `STDERR` constants, and evaluates `options.preload`.
225    ///
226    /// php.ini and the INI scan directory are never read. Like the PHP CLI,
227    /// the engine skips a leading `#!` line in every file it compiles.
228    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        // From here on, failing drops `php`, which shuts the engine down.
238        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        // SAFETY: the request is open, so the function table is populated
249        // and stays so until shutdown.
250        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        // Rust code reads a PHP string or array passed through it unconverted only when it looks at it.
262        speedyspec_hooks::set_opaque_reader(speedyspec_hooks::OpaqueReader {
263            readable: convert::readable_opaque,
264            read: convert::read_opaque,
265        });
266        // An `array( &$var )` element assigned to (`$args[0] = $value` in `WP_Hook::apply_filters()`) writes through.
267        speedyspec_hooks::set_opaque_writer(speedyspec_hooks::OpaqueWriter {
268            assign: crate::reference::assign,
269        });
270        php.request_setup()?;
271        Ok(php)
272    }
273
274    /// What every request gets before any other PHP code: `SpeedySpec\Hooks\HookException`, the `STDIN`,
275    /// `STDOUT` and `STDERR` constants, the preload, then each area's `request_start`.
276    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    /// Ends the current request and starts a fresh one, as a php-fpm worker does between requests: every PHP value
300    /// of the old request is freed (each area's `request_end` runs), and the new one runs the request setup again.
301    pub fn restart_request(&self) -> Result<(), PhpError> {
302        self.end_request();
303        self.start_request()?;
304        self.request_setup()
305    }
306
307    /// Ends the open request, if one is (after [`Php::serve`] none is).
308    fn end_request(&self) {
309        if !crate::boundary::alive() {
310            return;
311        }
312        settle_stray();
313        // SAFETY: ends the request on the booting thread, as `Drop` does; areas' request_end runs inside it.
314        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); // ManuallyDrop: the request freed them.
319            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    /// Starts a request on the booting thread, after the previous one ended.
327    fn start_request(&self) -> Result<(), PhpError> {
328        // SAFETY: the next request on the same thread, after the previous one ended.
329        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    /// Serves one web request: the open request (if any) ends, `request` becomes the request PHP sees (its
341    /// parameters as `$_SERVER`, its body as `php://input`, PHP's headers and output sent to it), the request setup
342    /// runs (each area's `request_start`), `script` runs, and the request ends (each area's `request_end`). No
343    /// request is open afterwards. An exception or fatal error before any output makes the response a 500.
344    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        // SAFETY: SG() on the booting thread between requests; the strings live until the request has ended.
368        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            // PHP never resets the status between requests; a SAPI does, as php-fpm does.
379            (*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                    // SAFETY: SG() during the request; PHP sends whatever code is set when the headers go out.
400                    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                // SAFETY: the engine is running a request on this thread.
408                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        // SAFETY: SG() between requests: the request's strings are about to be dropped.
416        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            // PHP read the cookies from `read_cookies` (a string freed with the request); a later request must not.
426            (*sg).request_info.cookie_data = ptr::null_mut();
427        }
428        drop((method, query, uri, content_type, script_c));
429        served
430    }
431
432    /// Runs PHP statements (no `<?php` tag) and returns what a top-level
433    /// `return` gives back, or null. `label` names the code in PHP's error
434    /// messages, where a file name would otherwise go.
435    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    /// `require`s a PHP file and returns its return value (1 if it returns
444    /// nothing). A relative path is resolved against the working directory,
445    /// never against `include_path`. Exceptions, fatal errors and `exit()`
446    /// come back as errors.
447    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    /// Runs a PHP file the way `php <path> <argv...>` would and returns its
463    /// exit status: 0 when it ends normally, `n` when it calls `exit(n)`.
464    /// `$_SERVER['SCRIPT_NAME']`, `SCRIPT_FILENAME` and `PHP_SELF` are the path.
465    /// `$argv` (and `$_SERVER['argv']`) is `[path, ...argv]` and `$argc` its
466    /// length. An uncaught exception or fatal error is an `Err`.
467    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        // As the PHP CLI sets them: a phar's stub runs only when it finds itself here.
485        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        // SAFETY: plain write to the executor globals on the engine's thread.
493        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    /// Calls a PHP callable (a function name, a `[class, method]` array, a
502    /// closure or an invokable object) with `args` and returns its result.
503    pub fn call(&self, callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
504        call(callable, args)
505    }
506}
507
508/// Calls a PHP callable from anywhere on the thread that booted PHP while a request is open, as [`Php::call`] does
509/// (an adapter of a port holds no `Php` handle). Fails without touching PHP when no request is open.
510pub 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            // SAFETY: `target` is fresh zval storage owned by this frame.
520            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        // Releasing the target can run a destructor; its exception is not
529        // this call's.
530        settle_stray();
531        outcome.map_err(CallError::into_php_error)
532    }
533}
534
535/// A PHP call that failed: the error, and the thrown object when PHP threw one (a `Value::Opaque`), so a native
536/// function can rethrow the original exception.
537#[derive(Debug)]
538pub struct CallFailure {
539    pub error: PhpError,
540    pub exception: Option<Value>,
541}
542
543/// As [`call`], keeping the exception object a failed call threw.
544pub 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        // SAFETY: `target` is fresh zval storage owned by this frame.
557        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
569/// A failed call as [`CallFailure`]: a thrown exception keeps its object.
570pub(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
594/// The SAPI's INI entries with [`set_ini`]'s settings after them, once set.
595static EXTRA_INI: std::sync::OnceLock<&'static std::ffi::CStr> = std::sync::OnceLock::new();
596
597/// INI settings for every request of this process, as php.ini would give them (so `PHP_INI_PERDIR` and
598/// `PHP_INI_SYSTEM` settings such as `upload_max_filesize` apply, which `ini_set()` cannot change). Call before
599/// [`Php::boot`], once. A key or value with a quote, a newline or a NUL is refused.
600pub 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
617/// Marks request startup as over, as `php_execute_script()` does before it runs a script. The runtime runs code
618/// without it, and while `PG(during_request_startup)` is set PHP names every diagnostic "PHP Request Startup" instead
619/// of the function that raised it.
620///
621/// # Safety
622///
623/// On the booting thread, right after a successful `php_request_startup()`.
624unsafe fn request_started() {
625    // SAFETY: the caller is on the booting thread; core_globals is the non-ZTS build's PG().
626    unsafe { ext_php_rs::ffi::core_globals.during_request_startup = false };
627}
628
629/// What serving one web request came to.
630#[derive(Debug)]
631pub struct Served {
632    /// The script's outcome; `exit()` is a normal end.
633    pub result: Result<(), PhpError>,
634    /// The engine's peak memory during the request, in bytes.
635    pub peak_memory: u64,
636    /// Whether a fatal error left the engine degraded (the worker should be replaced).
637    pub poisoned: bool,
638    pub headers_sent: bool,
639}
640
641/// `SG(server_context)` while a web request runs: PHP only reads the body and cookies when it is set.
642static mut SERVER_CONTEXT: [u64; 4] = [0; 4];
643
644unsafe extern "C" {
645    fn zend_memory_peak_usage(real_usage: bool) -> usize;
646}
647
648/// `$GLOBALS[$name]`, through references; `None` when it is not set or no request is open. Runs no PHP code.
649pub fn global(name: &str) -> Option<Value> {
650    if !crate::boundary::alive() {
651        return None;
652    }
653    // SAFETY: a request is open, so the symbol table is live; `to_value` neither runs PHP code nor allocates PHP
654    // memory.
655    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
669/// `$GLOBALS[$name] = $value`: a variable referencing the global sees the new value too.
670pub 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        // SAFETY: `fresh` is zval storage owned by this frame.
678        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        // SAFETY: a request is open; the slot found is live; the new value's ownership moves into the table or
692        // the slot, and the old value is handed back to be released.
693        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            // ZVAL_COPY_VALUE: the bucket keeps its `u2` (its hash chain).
709            (*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
725/// The global `name`'s value slot (indirect slots and references followed), if it is set.
726///
727/// # Safety
728///
729/// A request is open, on the engine's thread.
730pub(crate) unsafe fn global_slot(name: &str) -> Option<*mut zval> {
731    // SAFETY: the symbol table is live while a request is open; indirect and reference slots point to live zvals.
732    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
748/// `SEPARATE_ARRAY`: makes the array in `zv` one only `zv` holds, so changing it changes no copy.
749///
750/// # Safety
751///
752/// `zv` holds an array; inside a guard (duplicating allocates).
753unsafe fn separate_array(zv: *mut zval) {
754    // SAFETY: forwarded from the caller; an array's `arr` is its live table.
755    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            // Others still hold it: dropping our share frees nothing.
764            (*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
771/// `$GLOBALS[$name][] = $value`, in place, as WordPress pushes `$wp_current_filter`: one entry into PHP. False
772/// (nothing done) when the global is not an array.
773pub 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        // SAFETY: a request is open; `fresh` is zval storage owned by the enclosing frame, whose ownership moves into
781        // the array.
782        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                // No next index (PHP warns "Cannot add element"): the value stays ours to release.
794                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
808/// `array_pop($GLOBALS[$name])`, in place, as WordPress pops `$wp_current_filter`: one entry into PHP. False
809/// (nothing done) when the global is not an array.
810pub 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        // SAFETY: a request is open; the array's slots are read as `convert::array_values` does, and the last one is
816        // deleted through the hash API (which releases it, inside this guard).
817        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
841/// `spl_object_id($value)` for a PHP object held as a `Value::Opaque`.
842pub fn object_id(value: &Value) -> Option<u64> {
843    let object = convert::handle_of(value)?.object()?;
844    // SAFETY: the handle holds a reference to the object, so it is live.
845    Some(u64::from(unsafe { (*object).handle }))
846}
847
848impl Php {
849    /// Creates a PHP object: `new $class(...$args)`. An unknown class or a
850    /// constructor that throws is the exception PHP raised.
851    pub fn construct(&self, class: &str, args: &[Value]) -> Result<Value, PhpError> {
852        // Built in PHP rather than through the object API, so the constructor
853        // runs exactly as it would for a plugin's own `new`.
854        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    /// The class of a PHP object (`Value::Opaque` from PHP); `None` for
868    /// anything else.
869    pub fn class_of(&self, value: &Value) -> Option<String> {
870        let obj = convert::handle_of(value)?.object()?;
871        // SAFETY: the handle keeps the object, and so its class, alive.
872        Some(unsafe { class_name(obj) })
873    }
874
875    /// The public properties of a PHP object, in declaration then insertion
876    /// order; `None` for anything that is not a PHP object, or if one of the
877    /// properties cannot be converted.
878    pub fn properties_of(&self, value: &Value) -> Option<Vec<(String, Value)>> {
879        let obj = convert::handle_of(value)?.object()?;
880        settle_stray();
881        // Fetching the table can run PHP code (a lazy object initialises).
882        let table = guard(|| {
883            // SAFETY: the handle keeps `obj` alive; every object has handlers
884            // with a get_properties entry.
885            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        // SAFETY: the object owns `table` and is kept alive by the handle;
898        // reading it runs no PHP code.
899        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                // Protected and private names are mangled as "\0*\0name" and
906                // "\0Class\0name".
907                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    /// True once PHP has bailed out (a fatal error, memory exhaustion, or a
916    /// Rust panic carried through PHP) at least once; never cleared.
917    ///
918    /// The engine keeps working after a bailout, but degraded for the rest of
919    /// its single request: PHP turns the cycle collector off (`gc_protect`),
920    /// so reference cycles are no longer freed; a fatal error during
921    /// compilation leaves the file it was compiling open and its compiler
922    /// state behind; a fatal error part-way through an engine operation can
923    /// leave engine structures half-updated; and destructors of every object
924    /// that existed at the time of a fatal error never run. `exit()` does not
925    /// poison: in PHP 8 it unwinds as an exception, not a bailout. Memory
926    /// exhaustion does: PHP unwinds with the same object as `exit()`, but
927    /// reports a fatal error (a bailout of its own) on the way, and it is
928    /// returned as [`PhpError::Fatal`]. The caller decides whether to keep
929    /// going.
930    pub fn poisoned(&self) -> bool {
931        ENGINE.with(|e| e.poisoned.get())
932    }
933
934    /// Names the plugin that later `Hook::add` calls are registered for, until
935    /// changed. Hook errors from a failing callback name its owner.
936    pub fn set_owner(&self, owner: Option<&str>) {
937        hook_class::set_owner(owner);
938    }
939
940    /// Sends PHP's output to stdout (the default) or stderr.
941    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    /// Compiles `code` as `label` and runs it at the current scope.
947    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        // Owned here, outside every guard; the guards only see pointers.
957        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        // SAFETY: plain reads of the compiler globals on the engine's thread.
962        let saved_options = unsafe { (*ext_php_rs_compiler_globals()).compiler_options };
963
964        let ran = guard(|| {
965            // SAFETY: the sequence of zend_eval_stringl, keeping the op array
966            // so its top-level `return` reaches `retval`. All pointers are
967            // owned by the enclosing frame.
968            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; // ZEND_COMPILE_DEFAULT_FOR_EVAL
976                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; // A parse error is pending in EG(exception).
981                }
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        // SAFETY: restoring what the guard set, in case it bailed out early.
997        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            // A bailout during execution: free the op array as
1005            // zend_eval_stringl does. Refused if a re-raise is pending, in
1006            // which case it stays with the request until shutdown.
1007            let _ = guard(|| {
1008                // SAFETY: `op` was compiled above and not yet destroyed.
1009                unsafe {
1010                    destroy_op_array(op);
1011                    efree(op.cast());
1012                }
1013            });
1014        }
1015        let src = source.get();
1016        if !src.is_null() {
1017            // SAFETY: the reference created above; freeing a string runs no
1018            // PHP code.
1019            unsafe { ext_php_rs_zend_string_release(src) };
1020        }
1021
1022        // SAFETY: `retval` is either still null or what the code returned.
1023        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/// Builds the SAPI and starts the engine and its first request: the documented SAPI start sequence, which needs
1038/// ext-php-rs's `embed` feature.
1039#[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    // PHP copies the struct, but cleanup_sapi_allocations needs the
1055    // original after shutdown, so it lives on the heap until Drop. If
1056    // startup fails it is leaked: a half-started engine cannot be shut
1057    // down safely, and the process is about to report the error and exit.
1058    let sapi = Box::into_raw(Box::new(sapi));
1059
1060    // SAFETY: the documented SAPI start sequence, run once per process
1061    // (guarded by BOOTED) on this thread. `sapi_startup` clears
1062    // `ini_entries`, so it is set between the two startup calls, as
1063    // php-src's own SAPIs do. INI_ENTRIES is 'static.
1064    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        // As the CLI does; request startup has just reset it.
1076        (*ext_php_rs_compiler_globals()).skip_shebang = true;
1077        request_started();
1078    }
1079    Ok(sapi)
1080}
1081
1082/// Without the `embed` feature there is no engine to start.
1083#[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        // Release everything Rust has let go of while PHP code may still run,
1093        // and clear an exception a destructor left, which shutdown must not
1094        // find pending.
1095        settle_stray();
1096        // SAFETY: ends the request on the booting thread, if one is open (after `serve` none is). Native functions
1097        // still work during it (shutdown functions and destructors may fire hooks); PHP catches bailouts in each
1098        // shutdown step itself.
1099        if crate::boundary::alive() {
1100            unsafe { php_request_shutdown(ptr::null_mut()) };
1101        }
1102
1103        // The request freed every PHP value. Any reference Rust still holds
1104        // or has queued points into freed memory and must never be touched.
1105        // Per-context records of fibers that were never unwound (PHP only
1106        // abandons a suspended fiber without unwinding it when its destructor
1107        // is skipped, after a fatal error) are forgotten too: `alive` is false,
1108        // so dropping them releases nothing.
1109        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); // ManuallyDrop: nothing is released.
1113            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        // SAFETY: reverse of the start sequence in `boot`, on the same thread.
1123        // The SAPI module is reclaimed only after PHP no longer uses it.
1124        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        // A Rust panic inside a native function called during shutdown.
1133        if let Some(payload) = parked_panic
1134            && !std::thread::panicking()
1135        {
1136            resume_unwind(payload);
1137        }
1138    }
1139}
1140
1141/// `s` as a single-quoted PHP string literal.
1142fn 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
1155/// Compiles and runs `code` in the open request; for [`Php`]'s methods and the free [`eval`].
1156fn execute(label: &str, code: &[u8], position: zend_compile_position) -> Result<Value, PhpError> {
1157    Php::execute_in(label, code, position)
1158}
1159
1160/// Runs PHP statements (no `<?php` tag) from anywhere on the thread that booted PHP while a request is open, as
1161/// [`Php::eval`] does (a native area holds no `Php` handle). Fails without touching PHP when no request is open.
1162pub 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}