Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,32 @@ jobs:
# ShutdownTest starts PHP processes of its own with the extension.
PHP_TOKIO_TEST_EXTENSION="$extension" php -d "extension=$extension" vendor/bin/phpunit

restart:
# PHP started again in the same process (as FrankenPHP restarts it), with the module still
# loaded: tests/embed/restart.sh, on the embed SAPI of Ubuntu's PHP.
name: PHP restarted in one process, ubuntu-24.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Install PHP 8.3 with the embed SAPI
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends php8.3-cli php8.3-dev php8.3-xml php8.3-mbstring libphp8.3-embed composer
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: restart
- name: Build the test extension
env:
PHP: /usr/bin/php8.3
PHP_CONFIG: /usr/bin/php-config8.3
run: cargo build --release -p php-tokio-test-extension
- name: Install the test suite's dependencies
working-directory: tests
run: /usr/bin/php8.3 "$(command -v composer)" install --no-interaction --no-progress
- name: Start PHP 3 times in one process
run: tests/embed/restart.sh target/release/libphp_tokio_test_extension.so /usr/bin/php-config8.3

coverage:
# Every line and function of php-tokio's Rust code covered: tests/coverage.sh fails otherwise.
name: coverage, ${{ matrix.os }}
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ php-tokio-derive = { version = "=0.3.0", path = "./crates/macros" }

[target.'cfg(windows)'.dependencies]
socket2 = "0.6"
windows-sys = { version = "0.61", features = ["Win32_Networking_WinSock", "Win32_System_IO"] }
windows-sys = { version = "0.61", features = ["Win32_Networking_WinSock", "Win32_System_IO", "Win32_System_LibraryLoader"] }

[workspace]
members = [
Expand Down
14 changes: 13 additions & 1 deletion crates/test-extension/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use php_tokio::{borrow_unchecked::borrow_unchecked, php_async_impl, EventLoop};
use std::{
io,
sync::atomic::{AtomicUsize, Ordering},
time::Duration,
time::{Duration, Instant},
};

/// The name of the threads of the runtime from `initWith()`.
Expand Down Expand Up @@ -97,6 +97,18 @@ impl Native {
})
}

/// Like `trySleep()`, but the future keeps a thread of the runtime busy for `ms` milliseconds:
/// it yields without ever parking it.
pub fn try_spin(ms: u64) -> PhpResult<Option<u64>> {
EventLoop::try_suspend_on(async move {
let deadline = Instant::now() + Duration::from_millis(ms);
while Instant::now() < deadline {
tokio::task::yield_now().await;
}
ms
})
}

/// The name of the thread the futures run on.
pub async fn thread_name() -> String {
std::thread::current().name().unwrap_or_default().to_owned()
Expand Down
70 changes: 60 additions & 10 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ use lazy_static::lazy_static;
use std::{
cell::RefCell,
collections::HashMap,
ffi::{c_char, c_int, c_void},
ffi::{c_char, c_int, c_void, CStr},
future::Future,
io, ptr,
sync::{
atomic::{AtomicU64, Ordering},
mpsc, Arc, Condvar, Mutex, OnceLock,
mpsc, Arc, Condvar, Mutex,
},
time::{Duration, Instant},
};
Expand All @@ -43,8 +43,11 @@ lazy_static! {
pub static ref RUNTIME: Runtime = Runtime::new().expect("Could not allocate runtime");
}

/// The type of the resources that shut the event loop down at the end of the request.
static REQUEST_END: OnceLock<c_int> = OnceLock::new();
/// The name of the type of the resources that shut the event loop down at the end of the request.
const REQUEST_END: &CStr = c"php-tokio";

/// Held while the type is looked up and registered: under ZTS, by one thread at a time.
static REQUEST_END_TYPE: Mutex<()> = Mutex::new(());

/// The destructor of a resource of type `REQUEST_END`. At the end of the request, PHP destroys the
/// resources once the extensions' RSHUTDOWN ran, and only then frees the objects, fibers
Expand All @@ -61,6 +64,7 @@ extern "C" {
module_number: c_int,
) -> c_int;
fn zend_register_resource(rsrc_pointer: *mut c_void, rsrc_type: c_int) -> *mut zend_resource;
fn zend_fetch_list_dtor_id(type_name: *const c_char) -> c_int;
}

/// The ID of the next caller, unique in the process: a caller of an event loop that was shut down
Expand Down Expand Up @@ -226,6 +230,8 @@ impl Drop for Task {
}

const SOCKET_ERROR: &str = "Could not create the notification socket";
#[cfg(windows)]
const PIN_ERROR: &str = "Could not keep the extension loaded";

pub struct EventLoop {
/// The suspensions of the callers waiting for a future, by ID. PHP values never leave the
Expand Down Expand Up @@ -289,6 +295,8 @@ impl EventLoop {
EVENTLOOP.with_borrow_mut(|e| {
let event_loop = match e {
None => {
// Before any thread of the runtime starts.
keep_loaded()?;
let runtime = runtime()
.map_err(|err| format!("Could not build the Tokio runtime: {}", err))?;
e.insert(Self::new(runtime)?)
Expand Down Expand Up @@ -509,12 +517,25 @@ impl EventLoop {
}

// Shuts the event loop down at the end of the request (see shutdown()), with a resource of
// the request, which PHP destroys then. Its type is registered by the first event loop of
// the process: under ZTS, other threads may meanwhile look types up in the table, which
// this doesn't reallocate (PHP 8 registers few resource types, in a table of 64).
let request_end = *REQUEST_END.get_or_init(|| unsafe {
zend_register_list_destructors_ex(Some(request_end), None, c"php-tokio".as_ptr(), 0)
});
// the request, which PHP destroys then. Its type is registered by the first event loop
// since PHP started, looked up by name afterwards: the module outlives PHP (see
// keep_loaded()), which may start again in the same process, with a new table of types.
// Under ZTS, other threads may meanwhile look types up in the table, which this doesn't
// reallocate (PHP 8 registers few resource types, in a table of 64).
let request_end = {
let _registering = REQUEST_END_TYPE.lock().unwrap();
match unsafe { zend_fetch_list_dtor_id(REQUEST_END.as_ptr()) } {
0 => unsafe {
zend_register_list_destructors_ex(
Some(request_end),
None,
REQUEST_END.as_ptr(),
0,
)
},
id => id,
}
};
unsafe { zend_register_resource(ptr::null_mut(), request_end) };

Ok(Self {
Expand All @@ -538,6 +559,35 @@ impl EventLoop {
}
}

/// Keeps the module php-tokio is linked into loaded until the process exits.
///
/// PHP unloads the extensions at the end of the process (`zend_destroy_modules()`), while the
/// threads of the runtimes may still run their code: those of `RUNTIME`, never shut down, and
/// those of a runtime from `init_with()` that is released in the background, both running the
/// futures of `try_suspend_on()` that PHP stopped waiting for. Linux and macOS never unload a
/// module whose threads registered thread-local destructors (Tokio's do), but on Windows,
/// `FreeLibrary()` would unmap the code under them: pin it.
#[cfg(windows)]
fn keep_loaded() -> PhpResult<()> {
use windows_sys::Win32::System::LibraryLoader::{
GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN,
};
// The module that contains this function; pinning it again does nothing.
let address = keep_loaded as *const () as *const u16;
let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN;
let mut module = ptr::null_mut();
let pinned = unsafe { GetModuleHandleExW(flags, address, &mut module) } != 0;
// Formatted either way, for the coverage: the module of one of its own functions is always
// found.
let error = format!("{PIN_ERROR}: {}", io::Error::last_os_error());
pinned.then_some(()).ok_or(error.into())
}

#[cfg(not(windows))]
fn keep_loaded() -> PhpResult<()> {
Ok(())
}

/// How a caller's suspension ended.
enum Suspended {
/// By wakeup() or drain(), once its future completed.
Expand Down
26 changes: 26 additions & 0 deletions tests/embed/restart.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Starts PHP (the embed SAPI) <runs> times in this process, running <script> each time: as
// FrankenPHP restarts PHP, the extensions are started again while their modules stay loaded.
//
// Usage: restart <script> <runs>

// PHP's headers use memrchr().
#define _GNU_SOURCE
#include <stdlib.h>
#include <sapi/embed/php_embed.h>

int main(int argc, char **argv)
{
if (argc != 3) {
return 2;
}
int runs = atoi(argv[2]);
for (int i = 0; i < runs; i++) {
PHP_EMBED_START_BLOCK(argc, argv)
zend_file_handle script;
zend_stream_init_filename(&script, argv[1]);
php_execute_script(&script);
zend_destroy_file_handle(&script);
PHP_EMBED_END_BLOCK()
}
return 0;
}
19 changes: 19 additions & 0 deletions tests/embed/restart.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

// Run by restart.c once per start of PHP: a suspended caller resumed, then the event loop shut
// down at the end of the request by its resource, whose type is registered again since PHP
// started again.

use PhpTokio\Test\Native;
use Revolt\EventLoop;

use function Amp\async;

require __DIR__.'/../vendor/autoload.php';

$stream = Native::init();
stream_set_blocking($stream, false);
EventLoop::onReadable($stream, static fn () => Native::wakeup());
echo async(static fn () => Native::sleep(1))->await(), "\n";
29 changes: 29 additions & 0 deletions tests/embed/restart.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# Starts PHP 3 times in one process (the embed SAPI, as FrankenPHP restarts it), with the test
# extension, running restart.php each time: php-tokio's module outlives PHP (it stays loaded), so
# nothing it keeps may refer to a PHP that ended, such as the type of its resources.
#
# Needs the embed SAPI's library and the headers of the same PHP.
# Usage: tests/embed/restart.sh <test extension> [php-config]
set -euo pipefail
dir=$(cd "$(dirname "$0")" && pwd)
extension=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
php_config=${2:-php-config}

prefix=$("$php_config" --prefix)
library=$(ls "$prefix"/lib/libphp*.so | head -1)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
# shellcheck disable=SC2046
cc -o "$tmp/restart" "$dir/restart.c" $("$php_config" --includes) "$library" -Wl,-rpath,"$(dirname "$library")"
printf 'extension=%s\nerror_reporting=E_ALL\ndisplay_errors=stderr\n' "$extension" > "$tmp/php.ini"

PHPRC=$tmp/php.ini PHP_INI_SCAN_DIR= "$tmp/restart" "$dir/restart.php" 3 > "$tmp/out" 2> "$tmp/err" || status=$?
if [ "${status:-0}" != 0 ] || [ "$(cat "$tmp/out")" != $'1\n1\n1' ] || [ -s "$tmp/err" ]; then
echo "Exit status ${status:-0}, expected 0; output (expected 1 per run):"
cat "$tmp/out"
echo "Standard error (expected empty):"
cat "$tmp/err"
exit 1
fi
echo "PHP started 3 times in one process: OK"
13 changes: 13 additions & 0 deletions tests/src/ShutdownTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,19 @@ public function testTheRequestEndsWithoutWaitingForTheFuturesOfTrySuspendOn(stri
self::assertLessThan(4.0, $elapsed, 'try_suspend_on() did not wait for the future');
}

#[DataProvider('initializers')]
public function testTheProcessExitsWhileAFutureOfTrySuspendOnRuns(string $init): void
{
// The future still runs on a thread of the runtime when PHP unloads the extension, at the
// end of the process: on Windows, unloading it would unmap the code the thread runs.
$elapsed = self::assertRuns("exiting\n", <<<'PHP'
async(static fn () => Native::trySpin(5_000));
delay(0.05);
echo "exiting\n";
PHP, $init);
self::assertLessThan(4.0, $elapsed, 'try_suspend_on() did not wait for the future');
}

public function testExitInterruptsTrySuspendOn(): void
{
// exit() in a fiber unwinds it with an unwind exit, which stays pending too.
Expand Down
Loading