The Zend surface (upstream's ext-src/) is Rust. Swoole\Atomic
(crates/phplocks) is the smallest complete family to read.
crates/zend-sys: bindgen at build time againstphp-config --includes($PHP_CONFIG;build_ext.pysets it from--php-config), so struct layouts follow that PHP's version and ZTS mode. bindgen's layout assertions fail the build on a mismatch.src/shim*.care the macros and inline functions bindgen can't see that have to stay C (What stays C); anything else is Rust over the bindgen'd layouts (zend::value::set,empty_string,module_loaded, aphp_stream's bitfields). Theextern "C"declarations the crates write by hand over wrapper types aren't bindgen's:tools/externs.py(PR tier) checks each one's arity and argument widths against the PHP, shim, OpenSSL and glibc header that declares it.crates/zend: the safe layer.Call(argument count,$this,long/doubleparsed asZ_PARAM_LONG/Z_PARAM_DOUBLE,set_long/set_bool),Object<T>(struct { T data; zend_object std; }:create,data,install,dtor; Objects makes it safe),Class(registration from a method table),unset_property_deny,throw_exception/throw_error, and values:&Value(a borrowed zval, fromCall::valueorValue::from_ptr:as_long,as_double,str,array,object,class,pointerread a type without converting it,long,double,string,truthyconvert as Zend does,dereferencedfollows a reference),&Array(get,find,entries,for_each,count,is_list),&ZStr(a borrowed string:bytes,c_str,parse_quantity),ZStringandOwned/OwnedArray(push_*,insert_*), released inDropor handed to the return slot withCall::set_owned.Call's parsers have borrowed forms too (zstr,zstr_or_null,array_ref,bool_or_null). A family crate reads values through these with nounsafeof its own (crates/phpredis/src/format.rs,crates/phpswoole/src/options.rs); a raw pointer becomes a&Value,&Arrayor&ZStronce, at the boundary. A family's MINIT is afn(&Minit) -> Result<(), Bailout>that registers constants, classes and function aliases safely, whichcrates/phpswooleruns throughFamilies; a callable that a C owner such as a timer holds runs throughCallable::callbacks::<impl Holder>().crates/phptimeruses nounsafeat all. Add wrappers as callers need them. A sharedValueexposes no content edits; useOwned::array_mutfor an owned array's exclusive borrow. Property reads (Value::property,Props::slot,Declared::get) andCall::retreturn owned snapshots, including the current referent of a PHP reference, so writes through another handle cannot invalidate their contents. Property writers lend the slot out while editing and separate arrays before native parser writes; return-slot writers stay behindCall. By-reference argument edits require a mutableCall, which excludes simultaneous argument borrows.- One
crates/php<family>crate per family (crates/phplocks). It calls the mechanism crate directly (Rust calls Rust).
All three sit behind a php feature and are empty without it, so the
workspace builds without PHP. crates/ffi's php feature turns on each
family crate's php. crates/ext builds swoole.so with php on (fat LTO under the benchmarks'
--profile release-lto); tools/build_ext.py --native also builds the Zend-free
libswoole_rs_ffi.a without it, which the native gates link into executables.
handlers! {
zim_swoole_atomic_add => word::add::<Atomic>; // Zend name => body
}
fn fetch<H: Holder>(call: &Call, op: fn(&H::Word, i64) -> i64) {
match call.arity(0, 1).and_then(|()| call.long(1, 1)) {
Ok(value) => call.set_long(word::<H>(call).map_or(0, |word| op(word, value))),
Err(_) => failed(call), // ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE)
}
}Speed: a method crosses crates (zend, the mechanism crate) and rustc inlines
non-generic functions across crates only when they are #[inline]. Keep the
zend call-frame accessors #[inline], and give the mechanism a plain
#[inline] pub Rust function beside its swr_v1_* export, where it has
one; calling the export
costs Atomic::add about 40 instructions.
A class whose objects carry Rust state (Swoole's SW_SET_CLASS_CUSTOM_OBJECT)
implements zend::Custom for that state and registers with
Minit::register_object::<T>, which installs generated create and free
handlers: Custom::new makes each object's data, and the data drops with the
object. Call::custom::<T>() borrows $this's data and Value::custom::<T>()
any value's, both None for an object of another class; new_object(data)
makes one without running its constructor. The data is shared while a method
runs PHP code, so mutable state sits in Cells and OnceCells.
static LOCK: CustomClass<Held> = CustomClass::new();
struct Held(OnceCell<Lock>); // unset until __construct
impl Custom for Held {
fn class() -> &'static CustomClass<Self> { &LOCK }
fn new() -> Self { Self(OnceCell::new()) }
}A CustomClass<T> serves one data type, so a handler can't read another
class's objects as T. A type that sets Custom::DESTRUCTS also gets a
dtor_obj handler, which runs __destruct and then Custom::destruct (the
channel frees its queued values there). crates/phplocks and
crates/phpcollections use no unsafe at all.
Custom::free receives FreeProperties, an opaque view of the dying object's
properties. It can release uploaded files from a declared property, preserving
PHP's replacement of that array, but cannot expose the object as a Value or run
methods through it. General PHP callbacks belong in the earlier destruct step.
Mirror upstream's ZPP block exactly: the same min/max, defaults and failure
return value. Errors are Zend's own (zend_wrong_parameters_count_error,
zend_wrong_parameter_error), so messages match.
crates/phpstubs is every upstream stub's arginfo as Rust statics, one module
per ext-src/stubs/*.stub.php, named as gen_stub names them
(phpstubs::atomic::arginfo_class_Swoole_Atomic_add). tools/arginfo.py
generates it from the pin's stubs; --check (the PR tier's ext job) fails
if it is stale or if the same model, rendered as gen_stub's C, differs by a
byte from the pin's *_arginfo.h. The builders in zend::arginfo are one
const fn per Zend macro over the headers' own type bits, so the arrays are
the macros' on every PHP version.
A family's table is upstream's PHP_ME rows, in upstream's order (reflection
lists methods in table order, which is not always the stub's):
method_table! {
static METHODS = [
c"__construct" => zim_swoole_lock___construct, &lock::arginfo_class_Swoole_Lock___construct, ZEND_ACC_PUBLIC;
c"lock" => zim_swoole_lock_lock, &lock::arginfo_class_Swoole_Lock_lock, ZEND_ACC_PUBLIC;
];
}exit() and fatal errors leave PHP code by zend_bailout(), a longjmp to the
nearest zend_try. A longjmp must never cross a Rust frame, so Rust never
calls PHP code directly where it could bail out:
zend::bailout::call(fci, fcc)runszend_call_functioninside azend_trythat lives in the C shim, and returnsErr(Bailout)if it bailed. It (andcall_method) calls nothing once a bailout is pending: upstream never ran a callback past the first bailout.zend::contain_with(body)traps a native callback's bailout and reports a deferred Rust bailout after the closure returns. The closure may capture borrows and plain values; captures requiring Drop are rejected. Safe Rust helpers return or defer outcomes so their local owners are cleaned up normally.Bailoutis#[must_use]. A safe callback defers it and returns to its owner; the reactor, timer, process or server stops before invoking another callback. The owner propagates the pending outcome to the surrounding native boundary.zend::handlers!andzend::exports!generate unsafe native entry points around ordinary safe Rust bodies. The body consumes its arguments and returns aCopyresult before the entry point resumes the native bailout. Rust cannot invoke that entry point without acknowledging its native bailout scope and the absence of intervening Rust owners. Destructor entry points preserve an already-pending bailout for its original boundary.- A C/C++ trampoline can instead receive the outcome with
relay_to_cand resume it after Rust returns. The nativefree_objhandler drops its Rust data before calling Zend's standard property destructor. Both property destruction and the final bailout run under the native caller's scope.
zend::bailout::parse_func is Z_PARAM_FUNC (Zend's own callback errors).
A warning or notice runs the user error handler (set_error_handler), which
is PHP code: a fatal error in it, or exit() with no PHP frame below (a
reactor or timer callback), bails out. So every error Rust raises goes through
shim_errors.c, which runs it inside zend_try:
zend::php_error(level, message):php_error_docref.zend::host's calls:sw_callable_warning, for a callable that cannot be called.Call's ZPP slow paths (null-to-scalar and float-to-int deprecations) andValue::long/double/string(zval_get_*: an object or array warns,__toStringruns PHP).PropsandArrayMutwrites (zend_update_property: a subclass's__setor property hook runs PHP), skipped once a bailout is pending; and the release of an object, array or reference (Owned's drop,Call::assign,ArrayMut'sinsert*andupdateover a key already there:__destruct, or the cycle collector a possible root starts).
Each returns (or, for the converters, defers) a Bailout. Invalid-instance
errors also defer and return an absent binding, so callers stop before using it.
bailout::defer records the pending outcome; generated native boundaries resume
it after Rust cleanup. Never call php_error_docref, zend_error or a C++
reporter directly from safe Rust.
tests/modules/zend/run.py (error_handler_bailout.php) checks this per family against
upstream: an error handler that exit()s, and one that raises a fatal error,
on a Rust-raised warning.
python3 tools/zend_imports.py runs in pre-commit and the required PR tooling
job. Every hand-written PHP/Zend foreign function or static outside
crates/zend* needs an exact path:symbol entry in tools/zend_imports.json.
The reason names the enclosing C trap or Rust contain_with call, or explains
why this use cannot execute PHP. Allocation-only entries rely on the supported
PHP allocator contract below. Moving or removing a declaration requires updating
its entry; empty and stale entries fail too.
The inventory scans every cfg branch and foreign ABI (including the default), using
link_name rather than a Rust alias (all alternatives for cfg_attr). It recognizes
PHP/Zend namespaces, the unprefixed entry points listed in the tool, and legacy
swr_* shims found in zend-sys C sources/headers. Add an unprefixed PHP API to
PHP_NAMES when introducing one. This is a review gate for declarations, not a
proof that callers still use the documented trap; call-site changes need review.
Zend's request allocator (emalloc, zend_string_alloc, array_init, a
growing hash) doesn't bail out at memory_limit. Since PHP's delayed
out-of-memory errors (8.2.35, 8.3.36, 8.4.27 and 8.5.12; Ubuntu's
8.3.6-0ubuntu0.24.04.13, which CI uses, backports them), an allocation past the
limit returns its memory and queues the "Allowed memory size" fatal error. Zend
raises it at the VM's next interrupt check or in zend_call_function, which
Rust reaches only through bailout::call. Past the hard limit (twice
memory_limit, or 1 GiB above it) the allocator ends the process with
_exit(137), and a persistent allocation that fails exits too. So ZString,
ZBuf, OwnedArray, ArrayMut, Callable, new objects and MINIT's
persistent tables allocate with no setjmp. An older PHP bails out of the
allocator, over the Rust frames that called it, so zend-sys refuses to build
against one.
tests/modules/zend/memory_limit.php reaches the limit inside a ZBuf and
compares the outcome with upstream's.
Rust-owned request allocations use Emalloc with Box::new_in or
Vec::with_capacity_in. The zero-sized allocator is neither Send nor Sync and
rejects alignment above Zend's eight-byte guarantee. Empty layouts need no Zend
allocation. Its owners must drop or transfer their storage before request shutdown.
Callable records and argument slices transfer to their native callback owner;
custom PHP objects still use zend_object_alloc, including their variable property
tail, and Zend frees them after the Rust data destructor.
native/corebase/swoole_rs_zend_guard.h defines native scope outcomes: normal
return (0), ordinary Zend bailout (1) and pending whole-thread exit (2). Rust
relays the outcome after dropping its owners. Only Swoole\Thread, which needs
ZTS, raises a whole-thread exit, so only ZTS builds keep a record per scope;
on NTS a scope is a plain zend_try. Callbacks invoked below Rust must
catch C++ exceptions inside the native body, return a typed fault, and rethrow
only after Rust returns.
The C compiled from crates/ into swoole.so (outside crates/oracle) is
what Rust can't express, or can't express without more unsafe. Each file's
header names its reasons from this list:
- bailout: the call can run PHP code (a destructor,
__get, an autoloader, an error handler) that bails out, andzend_try'ssetjmpmust sit in a C frame (Calling PHP). - globals: it reads or writes
EG,CG,PG,SG,BG,FG,OGorSIGG. Under ZTS these are TSRM slots reached through a thread-local cache and offsets only the macros know. - allocator: it allocates or frees through Zend's allocator (
emalloc,pemalloc,zend_string_*,array_init,OBJ_RELEASE,smart_str), whose entry points take the caller's file and line in debug builds (ZEND_FILE_LINE_DC). - version: the macro, field or signature differs between the PHP versions
CI builds (
PHP_VERSION_ID, a feature#ifdef), or the member sits in an anonymous union whose bindgen name changes (ce->create_object,ce->parent); the same holds for library versions (ARES_VERSION). - variadic: a C variadic or
va_listfunction, which stable Rust can't define (crates/corebase/src/format.c,crates/corebase/src/fatal.c,shim_errors.c,shim_host.c). - private: the layout is private to a source file or library release:
zend_closurebehindZEND_CLOSURE_OBJECT,zend_execute.c's static helpers (crates/phpstdext/src/stdext.c, overnative/hooks/zend_execute_private.h), ext/sockets'php_socket. - budget: a
static inlineover public fields (Z_TRY_ADDREF_P,ZVAL_COPY,ZVAL_STR,GC_ADDREF,Z_OBJPROP_P,ZEND_HASH_FOREACH) whose callers hold raw pointers: a Rust port addsunsafeand removes none, whichtools/budget.pyrefuses. One moves once its callers hold aValueorOwned, where it can be a safe method.
A shim that fits none of these is a port waiting to happen: write it in
crates/zend against the bindgen'd layout, as zend::module_loaded replaced
swr_zend_module_loaded. tools/budget.py counts these lines,
and a PR that adds some names the reasons in a Stays C: <reason> line of its body.
The stdext feature of crates/ffi (phpstdext/active) tracks native
SW_STDEXT; tools/build_ext.py --stdext turns it on.
Feature-enabled Rust checks use --features php,active.
cargo clippy --workspace --all-targets --all-featuresandcargo test --workspace --all-features(therustjob installs PHP headers and libclang).- The Cargo build and the family's PHPTs on Linux:
python3 tools/dev.py docker -- tools/build_ext.pyandcorpus/upstream/run.py --case ...against both engines. - A callgrind A/B of a tight method loop against upstream, in the PR.
- Alpine (musl) builds build scripts with
-C target-feature=-crt-static(merge tier); a static build script cannotdlopenlibclang.
Raw bindgen zval bits are not validated values. Zvals::of is private to the
Zend crate, and Value::of there borrows a value made by value (Value::naming
for a borrowed object), not raw bits. Local results use Owned; call helpers accept
Zvals::owned, Zvals::one, or Zvals::with, whose temporary stack copies
cannot escape the closure. ObjectRef::with_value lends a live object's value
within its borrow, and persistent non-owning holders use Weak<T> to acquire a
live object before reading its state.