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        php.request_setup()?;
267        Ok(php)
268    }
269
270    /// What every request gets before any other PHP code: `SpeedySpec\Hooks\HookException`, the `STDIN`,
271    /// `STDOUT` and `STDERR` constants, the preload, then each area's `request_start`.
272    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    /// Ends the current request and starts a fresh one, as a php-fpm worker does between requests: every PHP value
296    /// of the old request is freed (each area's `request_end` runs), and the new one runs the request setup again.
297    pub fn restart_request(&self) -> Result<(), PhpError> {
298        self.end_request();
299        self.start_request()?;
300        self.request_setup()
301    }
302
303    /// Ends the open request, if one is (after [`Php::serve`] none is).
304    fn end_request(&self) {
305        if !crate::boundary::alive() {
306            return;
307        }
308        settle_stray();
309        // SAFETY: ends the request on the booting thread, as `Drop` does; areas' request_end runs inside it.
310        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); // ManuallyDrop: the request freed them.
315            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    /// Starts a request on the booting thread, after the previous one ended.
323    fn start_request(&self) -> Result<(), PhpError> {
324        // SAFETY: the next request on the same thread, after the previous one ended.
325        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    /// Serves one web request: the open request (if any) ends, `request` becomes the request PHP sees (its
337    /// parameters as `$_SERVER`, its body as `php://input`, PHP's headers and output sent to it), the request setup
338    /// runs (each area's `request_start`), `script` runs, and the request ends (each area's `request_end`). No
339    /// request is open afterwards. An exception or fatal error before any output makes the response a 500.
340    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        // SAFETY: SG() on the booting thread between requests; the strings live until the request has ended.
364        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            // PHP never resets the status between requests; a SAPI does, as php-fpm does.
375            (*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                    // SAFETY: SG() during the request; PHP sends whatever code is set when the headers go out.
396                    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                // SAFETY: the engine is running a request on this thread.
404                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        // SAFETY: SG() between requests: the request's strings are about to be dropped.
412        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            // PHP read the cookies from `read_cookies` (a string freed with the request); a later request must not.
422            (*sg).request_info.cookie_data = ptr::null_mut();
423        }
424        drop((method, query, uri, content_type, script_c));
425        served
426    }
427
428    /// Runs PHP statements (no `<?php` tag) and returns what a top-level
429    /// `return` gives back, or null. `label` names the code in PHP's error
430    /// messages, where a file name would otherwise go.
431    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    /// `require`s a PHP file and returns its return value (1 if it returns
440    /// nothing). A relative path is resolved against the working directory,
441    /// never against `include_path`. Exceptions, fatal errors and `exit()`
442    /// come back as errors.
443    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    /// Runs a PHP file the way `php <path> <argv...>` would and returns its
459    /// exit status: 0 when it ends normally, `n` when it calls `exit(n)`.
460    /// `$_SERVER['SCRIPT_NAME']`, `SCRIPT_FILENAME` and `PHP_SELF` are the path.
461    /// `$argv` (and `$_SERVER['argv']`) is `[path, ...argv]` and `$argc` its
462    /// length. An uncaught exception or fatal error is an `Err`.
463    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        // As the PHP CLI sets them: a phar's stub runs only when it finds itself here.
481        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        // SAFETY: plain write to the executor globals on the engine's thread.
489        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    /// Calls a PHP callable (a function name, a `[class, method]` array, a
498    /// closure or an invokable object) with `args` and returns its result.
499    pub fn call(&self, callable: &Value, args: &[Value]) -> Result<Value, PhpError> {
500        call(callable, args)
501    }
502}
503
504/// Calls a PHP callable from anywhere on the thread that booted PHP while a request is open, as [`Php::call`] does
505/// (an adapter of a port holds no `Php` handle). Fails without touching PHP when no request is open.
506pub 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            // SAFETY: `target` is fresh zval storage owned by this frame.
516            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        // Releasing the target can run a destructor; its exception is not
525        // this call's.
526        settle_stray();
527        outcome.map_err(CallError::into_php_error)
528    }
529}
530
531/// A PHP call that failed: the error, and the thrown object when PHP threw one (a `Value::Opaque`), so a native
532/// function can rethrow the original exception.
533#[derive(Debug)]
534pub struct CallFailure {
535    pub error: PhpError,
536    pub exception: Option<Value>,
537}
538
539/// As [`call`], keeping the exception object a failed call threw.
540pub 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        // SAFETY: `target` is fresh zval storage owned by this frame.
553        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
565/// A failed call as [`CallFailure`]: a thrown exception keeps its object.
566pub(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
590/// The SAPI's INI entries with [`set_ini`]'s settings after them, once set.
591static EXTRA_INI: std::sync::OnceLock<&'static std::ffi::CStr> = std::sync::OnceLock::new();
592
593/// INI settings for every request of this process, as php.ini would give them (so `PHP_INI_PERDIR` and
594/// `PHP_INI_SYSTEM` settings such as `upload_max_filesize` apply, which `ini_set()` cannot change). Call before
595/// [`Php::boot`], once. A key or value with a quote, a newline or a NUL is refused.
596pub 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
613/// Marks request startup as over, as `php_execute_script()` does before it runs a script. The runtime runs code
614/// without it, and while `PG(during_request_startup)` is set PHP names every diagnostic "PHP Request Startup" instead
615/// of the function that raised it.
616///
617/// # Safety
618///
619/// On the booting thread, right after a successful `php_request_startup()`.
620unsafe fn request_started() {
621    // SAFETY: the caller is on the booting thread; core_globals is the non-ZTS build's PG().
622    unsafe { ext_php_rs::ffi::core_globals.during_request_startup = false };
623}
624
625/// What serving one web request came to.
626#[derive(Debug)]
627pub struct Served {
628    /// The script's outcome; `exit()` is a normal end.
629    pub result: Result<(), PhpError>,
630    /// The engine's peak memory during the request, in bytes.
631    pub peak_memory: u64,
632    /// Whether a fatal error left the engine degraded (the worker should be replaced).
633    pub poisoned: bool,
634    pub headers_sent: bool,
635}
636
637/// `SG(server_context)` while a web request runs: PHP only reads the body and cookies when it is set.
638static mut SERVER_CONTEXT: [u64; 4] = [0; 4];
639
640unsafe extern "C" {
641    fn zend_memory_peak_usage(real_usage: bool) -> usize;
642}
643
644/// `$GLOBALS[$name]`, through references; `None` when it is not set or no request is open. Runs no PHP code.
645pub fn global(name: &str) -> Option<Value> {
646    if !crate::boundary::alive() {
647        return None;
648    }
649    // SAFETY: a request is open, so the symbol table is live; `to_value` neither runs PHP code nor allocates PHP
650    // memory.
651    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
665/// `$GLOBALS[$name] = $value`: a variable referencing the global sees the new value too.
666pub 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        // SAFETY: `fresh` is zval storage owned by this frame.
674        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        // SAFETY: a request is open; the slot found is live; the new value's ownership moves into the table or
688        // the slot, and the old value is handed back to be released.
689        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
719/// The global `name`'s value slot (indirect slots and references followed), if it is set.
720///
721/// # Safety
722///
723/// A request is open, on the engine's thread.
724pub(crate) unsafe fn global_slot(name: &str) -> Option<*mut zval> {
725    // SAFETY: the symbol table is live while a request is open; indirect and reference slots point to live zvals.
726    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
742/// `SEPARATE_ARRAY`: makes the array in `zv` one only `zv` holds, so changing it changes no copy.
743///
744/// # Safety
745///
746/// `zv` holds an array; inside a guard (duplicating allocates).
747unsafe fn separate_array(zv: *mut zval) {
748    // SAFETY: forwarded from the caller; an array's `arr` is its live table.
749    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            // Others still hold it: dropping our share frees nothing.
758            (*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
765/// `$GLOBALS[$name][] = $value`, in place, as WordPress pushes `$wp_current_filter`: one entry into PHP. False
766/// (nothing done) when the global is not an array.
767pub 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        // SAFETY: a request is open; `fresh` is zval storage owned by the enclosing frame, whose ownership moves into
775        // the array.
776        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                // No next index (PHP warns "Cannot add element"): the value stays ours to release.
788                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
802/// `array_pop($GLOBALS[$name])`, in place, as WordPress pops `$wp_current_filter`: one entry into PHP. False
803/// (nothing done) when the global is not an array.
804pub 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        // SAFETY: a request is open; the array's slots are read as `convert::array_values` does, and the last one is
810        // deleted through the hash API (which releases it, inside this guard).
811        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
835/// `spl_object_id($value)` for a PHP object held as a `Value::Opaque`.
836pub fn object_id(value: &Value) -> Option<u64> {
837    let object = convert::handle_of(value)?.object()?;
838    // SAFETY: the handle holds a reference to the object, so it is live.
839    Some(u64::from(unsafe { (*object).handle }))
840}
841
842impl Php {
843    /// Creates a PHP object: `new $class(...$args)`. An unknown class or a
844    /// constructor that throws is the exception PHP raised.
845    pub fn construct(&self, class: &str, args: &[Value]) -> Result<Value, PhpError> {
846        // Built in PHP rather than through the object API, so the constructor
847        // runs exactly as it would for a plugin's own `new`.
848        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    /// The class of a PHP object (`Value::Opaque` from PHP); `None` for
862    /// anything else.
863    pub fn class_of(&self, value: &Value) -> Option<String> {
864        let obj = convert::handle_of(value)?.object()?;
865        // SAFETY: the handle keeps the object, and so its class, alive.
866        Some(unsafe { class_name(obj) })
867    }
868
869    /// The public properties of a PHP object, in declaration then insertion
870    /// order; `None` for anything that is not a PHP object, or if one of the
871    /// properties cannot be converted.
872    pub fn properties_of(&self, value: &Value) -> Option<Vec<(String, Value)>> {
873        let obj = convert::handle_of(value)?.object()?;
874        settle_stray();
875        // Fetching the table can run PHP code (a lazy object initialises).
876        let table = guard(|| {
877            // SAFETY: the handle keeps `obj` alive; every object has handlers
878            // with a get_properties entry.
879            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        // SAFETY: the object owns `table` and is kept alive by the handle;
892        // reading it runs no PHP code.
893        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                // Protected and private names are mangled as "\0*\0name" and
900                // "\0Class\0name".
901                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    /// True once PHP has bailed out (a fatal error, memory exhaustion, or a
910    /// Rust panic carried through PHP) at least once; never cleared.
911    ///
912    /// The engine keeps working after a bailout, but degraded for the rest of
913    /// its single request: PHP turns the cycle collector off (`gc_protect`),
914    /// so reference cycles are no longer freed; a fatal error during
915    /// compilation leaves the file it was compiling open and its compiler
916    /// state behind; a fatal error part-way through an engine operation can
917    /// leave engine structures half-updated; and destructors of every object
918    /// that existed at the time of a fatal error never run. `exit()` does not
919    /// poison: in PHP 8 it unwinds as an exception, not a bailout. Memory
920    /// exhaustion does: PHP unwinds with the same object as `exit()`, but
921    /// reports a fatal error (a bailout of its own) on the way, and it is
922    /// returned as [`PhpError::Fatal`]. The caller decides whether to keep
923    /// going.
924    pub fn poisoned(&self) -> bool {
925        ENGINE.with(|e| e.poisoned.get())
926    }
927
928    /// Names the plugin that later `Hook::add` calls are registered for, until
929    /// changed. Hook errors from a failing callback name its owner.
930    pub fn set_owner(&self, owner: Option<&str>) {
931        hook_class::set_owner(owner);
932    }
933
934    /// Sends PHP's output to stdout (the default) or stderr.
935    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    /// Compiles `code` as `label` and runs it at the current scope.
941    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        // Owned here, outside every guard; the guards only see pointers.
951        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        // SAFETY: plain reads of the compiler globals on the engine's thread.
956        let saved_options = unsafe { (*ext_php_rs_compiler_globals()).compiler_options };
957
958        let ran = guard(|| {
959            // SAFETY: the sequence of zend_eval_stringl, keeping the op array
960            // so its top-level `return` reaches `retval`. All pointers are
961            // owned by the enclosing frame.
962            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; // ZEND_COMPILE_DEFAULT_FOR_EVAL
970                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; // A parse error is pending in EG(exception).
975                }
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        // SAFETY: restoring what the guard set, in case it bailed out early.
991        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            // A bailout during execution: free the op array as
999            // zend_eval_stringl does. Refused if a re-raise is pending, in
1000            // which case it stays with the request until shutdown.
1001            let _ = guard(|| {
1002                // SAFETY: `op` was compiled above and not yet destroyed.
1003                unsafe {
1004                    destroy_op_array(op);
1005                    efree(op.cast());
1006                }
1007            });
1008        }
1009        let src = source.get();
1010        if !src.is_null() {
1011            // SAFETY: the reference created above; freeing a string runs no
1012            // PHP code.
1013            unsafe { ext_php_rs_zend_string_release(src) };
1014        }
1015
1016        // SAFETY: `retval` is either still null or what the code returned.
1017        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/// Builds the SAPI and starts the engine and its first request: the documented SAPI start sequence, which needs
1032/// ext-php-rs's `embed` feature.
1033#[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    // PHP copies the struct, but cleanup_sapi_allocations needs the
1049    // original after shutdown, so it lives on the heap until Drop. If
1050    // startup fails it is leaked: a half-started engine cannot be shut
1051    // down safely, and the process is about to report the error and exit.
1052    let sapi = Box::into_raw(Box::new(sapi));
1053
1054    // SAFETY: the documented SAPI start sequence, run once per process
1055    // (guarded by BOOTED) on this thread. `sapi_startup` clears
1056    // `ini_entries`, so it is set between the two startup calls, as
1057    // php-src's own SAPIs do. INI_ENTRIES is 'static.
1058    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        // As the CLI does; request startup has just reset it.
1070        (*ext_php_rs_compiler_globals()).skip_shebang = true;
1071        request_started();
1072    }
1073    Ok(sapi)
1074}
1075
1076/// Without the `embed` feature there is no engine to start.
1077#[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        // Release everything Rust has let go of while PHP code may still run,
1087        // and clear an exception a destructor left, which shutdown must not
1088        // find pending.
1089        settle_stray();
1090        // SAFETY: ends the request on the booting thread, if one is open (after `serve` none is). Native functions
1091        // still work during it (shutdown functions and destructors may fire hooks); PHP catches bailouts in each
1092        // shutdown step itself.
1093        if crate::boundary::alive() {
1094            unsafe { php_request_shutdown(ptr::null_mut()) };
1095        }
1096
1097        // The request freed every PHP value. Any reference Rust still holds
1098        // or has queued points into freed memory and must never be touched.
1099        // Per-context records of fibers that were never unwound (PHP only
1100        // abandons a suspended fiber without unwinding it when its destructor
1101        // is skipped, after a fatal error) are forgotten too: `alive` is false,
1102        // so dropping them releases nothing.
1103        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); // ManuallyDrop: nothing is released.
1107            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        // SAFETY: reverse of the start sequence in `boot`, on the same thread.
1117        // The SAPI module is reclaimed only after PHP no longer uses it.
1118        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        // A Rust panic inside a native function called during shutdown.
1127        if let Some(payload) = parked_panic
1128            && !std::thread::panicking()
1129        {
1130            resume_unwind(payload);
1131        }
1132    }
1133}
1134
1135/// `s` as a single-quoted PHP string literal.
1136fn 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
1149/// Compiles and runs `code` in the open request; for [`Php`]'s methods and the free [`eval`].
1150fn execute(label: &str, code: &[u8], position: zend_compile_position) -> Result<Value, PhpError> {
1151    Php::execute_in(label, code, position)
1152}
1153
1154/// Runs PHP statements (no `<?php` tag) from anywhere on the thread that booted PHP while a request is open, as
1155/// [`Php::eval`] does (a native area holds no `Php` handle). Fails without touching PHP when no request is open.
1156pub 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}