aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-php-shim
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-06-24 03:09:17 +0900
committernsfisis <nsfisis@gmail.com>2026-06-24 03:09:17 +0900
commitc5fc34a106a706ac12925c4df273a926811d260b (patch)
tree24e798c4a00b32aa1a1f155b705d02fba9895875 /crates/shirabe-php-shim
parentb2b321a26f6a628ee8e6757eb8577613e2024e70 (diff)
downloadphp-shirabe-c5fc34a106a706ac12925c4df273a926811d260b.tar.gz
php-shirabe-c5fc34a106a706ac12925c4df273a926811d260b.tar.zst
php-shirabe-c5fc34a106a706ac12925c4df273a926811d260b.zip
feat(process): redesign proc_* on PhpResource process handles
proc_open/proc_close/proc_get_status/proc_terminate represented the process handle as a PhpMixed, which cannot hold a live child process or its pipes, so they were stubs or todo!(). Model the handle as a new PhpResource::Process variant and child pipes as a StreamBacking::Pipe, with a native Descriptor enum for descriptorspec; proc_open now returns io::Result and fills pipes as IndexMap<i64, PhpResource>. Rewire the Symfony Process pipes and the Console terminal/cursor onto the new types, removing the "PhpMixed cannot carry a PhpResource" todo!()s. The remaining todo!()s are genuine syscall leaves (proc_terminate signal delivery, stream_select, stream_set_blocking, posix_kill, pty, fd>=3) left unimplemented since no syscall crate is introduced. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'crates/shirabe-php-shim')
-rw-r--r--crates/shirabe-php-shim/src/fs.rs37
-rw-r--r--crates/shirabe-php-shim/src/lib.rs48
-rw-r--r--crates/shirabe-php-shim/src/process.rs329
-rw-r--r--crates/shirabe-php-shim/src/stream.rs29
4 files changed, 403 insertions, 40 deletions
diff --git a/crates/shirabe-php-shim/src/fs.rs b/crates/shirabe-php-shim/src/fs.rs
index f12d7bf..e70d397 100644
--- a/crates/shirabe-php-shim/src/fs.rs
+++ b/crates/shirabe-php-shim/src/fs.rs
@@ -300,7 +300,7 @@ pub fn fwrite(stream: &PhpResource, data: &str, length: Option<i64>) -> Option<i
_ => bytes,
};
match stream {
- PhpResource::Stdin => None,
+ PhpResource::Stdin | PhpResource::Process(_) => None,
PhpResource::Stdout => std::io::stdout()
.write_all(bytes)
.ok()
@@ -333,7 +333,7 @@ pub fn fread(stream: &PhpResource, length: i64) -> Option<String> {
buf.truncate(n);
Some(String::from_utf8_lossy(&buf).into_owned())
}
- PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdout | PhpResource::Stderr | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.readable {
@@ -353,7 +353,10 @@ pub fn fread(stream: &PhpResource, length: i64) -> Option<String> {
/// PHP `feof()`: true only after a read has hit end-of-stream.
pub fn feof(stream: &PhpResource) -> bool {
match stream {
- PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => false,
+ PhpResource::Stdin
+ | PhpResource::Stdout
+ | PhpResource::Stderr
+ | PhpResource::Process(_) => false,
PhpResource::Stream(state) => state.borrow().eof,
}
}
@@ -362,6 +365,7 @@ pub fn feof(stream: &PhpResource) -> bool {
pub fn fclose(stream: &PhpResource) -> bool {
match stream {
PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => true,
+ PhpResource::Process(_) => false,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed {
@@ -393,7 +397,7 @@ pub fn fgets(stream: &PhpResource, length: Option<i64>) -> Option<String> {
}
Some(String::from_utf8_lossy(&line).into_owned())
}
- PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdout | PhpResource::Stderr | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.readable {
@@ -447,7 +451,7 @@ pub fn fgetc(stream: &PhpResource) -> Option<String> {
}
Some(String::from_utf8_lossy(&byte).into_owned())
}
- PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdout | PhpResource::Stderr | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.readable {
@@ -467,7 +471,10 @@ pub fn fgetc(stream: &PhpResource) -> Option<String> {
pub fn ftell(stream: &PhpResource) -> Option<i64> {
use std::io::Seek;
match stream {
- PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdin
+ | PhpResource::Stdout
+ | PhpResource::Stderr
+ | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed {
@@ -492,7 +499,10 @@ pub fn fseek(stream: &PhpResource, offset: i64, whence: i64) -> i64 {
_ => std::io::SeekFrom::Start(offset.max(0) as u64),
};
match stream {
- PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => -1,
+ PhpResource::Stdin
+ | PhpResource::Stdout
+ | PhpResource::Stderr
+ | PhpResource::Process(_) => -1,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed {
@@ -519,7 +529,10 @@ pub fn fstat(stream: &PhpResource) -> Option<IndexMap<String, PhpMixed>> {
match stream {
// TODO(phase-d): the stdio streams expose no fd to stat without a syscall crate; report
// failure rather than fabricate fields.
- PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdin
+ | PhpResource::Stdout
+ | PhpResource::Stderr
+ | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed {
@@ -531,6 +544,7 @@ pub fn fstat(stream: &PhpResource) -> Option<IndexMap<String, PhpMixed>> {
(m.len(), Some(m))
}
StreamBacking::Memory(c) => (c.get_ref().len() as u64, None),
+ StreamBacking::Pipe(_) => return None,
};
Some(build_stat_map(size, file_meta.as_ref()))
}
@@ -590,6 +604,7 @@ pub fn fflush(stream: &PhpResource) -> bool {
PhpResource::Stdin => true,
PhpResource::Stdout => std::io::stdout().flush().is_ok(),
PhpResource::Stderr => std::io::stderr().flush().is_ok(),
+ PhpResource::Process(_) => false,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed {
@@ -893,7 +908,10 @@ pub fn copy(_source: &str, _dest: &str) -> bool {
pub fn ftruncate(stream: &PhpResource, size: i64) -> bool {
match stream {
- PhpResource::Stdin | PhpResource::Stdout | PhpResource::Stderr => false,
+ PhpResource::Stdin
+ | PhpResource::Stdout
+ | PhpResource::Stderr
+ | PhpResource::Process(_) => false,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.writable {
@@ -908,6 +926,7 @@ pub fn ftruncate(stream: &PhpResource, size: i64) -> bool {
buf.resize(size as usize, 0);
true
}
+ StreamBacking::Pipe(_) => false,
}
}
}
diff --git a/crates/shirabe-php-shim/src/lib.rs b/crates/shirabe-php-shim/src/lib.rs
index 8eb8f2f..113c9d7 100644
--- a/crates/shirabe-php-shim/src/lib.rs
+++ b/crates/shirabe-php-shim/src/lib.rs
@@ -346,6 +346,7 @@ pub enum PhpResource {
Stdout,
Stderr,
Stream(std::rc::Rc<std::cell::RefCell<StreamState>>),
+ Process(std::rc::Rc<std::cell::RefCell<process::ProcessState>>),
}
/// Combined capability of every seekable byte stream backing. Both `std::fs::File`
@@ -361,6 +362,8 @@ pub enum StreamBacking {
/// TODO(phase-d): `php://temp/maxmemory:N` spills to a temp file past N bytes;
/// the threshold is ignored here and everything stays in memory.
Memory(std::io::Cursor<Vec<u8>>),
+ /// A child process pipe created by `proc_open`. Half-duplex and not seekable.
+ Pipe(ChildPipe),
}
impl StreamBacking {
@@ -368,10 +371,55 @@ impl StreamBacking {
match self {
StreamBacking::File(f) => f,
StreamBacking::Memory(c) => c,
+ StreamBacking::Pipe(p) => p,
}
}
}
+/// One end of a child process pipe. Each variant supports only the direction PHP
+/// allows for it; the unsupported operations return `ErrorKind::Unsupported` so the
+/// `ReadWriteSeek` contract is satisfied without pretending pipes are seekable.
+#[derive(Debug)]
+pub enum ChildPipe {
+ In(std::process::ChildStdin),
+ Out(std::process::ChildStdout),
+ Err(std::process::ChildStderr),
+}
+
+impl std::io::Read for ChildPipe {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ match self {
+ ChildPipe::Out(o) => o.read(buf),
+ ChildPipe::Err(e) => e.read(buf),
+ ChildPipe::In(_) => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
+ }
+ }
+}
+
+impl std::io::Write for ChildPipe {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ match self {
+ ChildPipe::In(i) => i.write(buf),
+ ChildPipe::Out(_) | ChildPipe::Err(_) => {
+ Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
+ }
+ }
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ match self {
+ ChildPipe::In(i) => i.flush(),
+ ChildPipe::Out(_) | ChildPipe::Err(_) => Ok(()),
+ }
+ }
+}
+
+impl std::io::Seek for ChildPipe {
+ fn seek(&mut self, _pos: std::io::SeekFrom) -> std::io::Result<u64> {
+ Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
+ }
+}
+
#[derive(Debug)]
pub struct StreamState {
pub(crate) backing: StreamBacking,
diff --git a/crates/shirabe-php-shim/src/process.rs b/crates/shirabe-php-shim/src/process.rs
index b47c579..402ad8b 100644
--- a/crates/shirabe-php-shim/src/process.rs
+++ b/crates/shirabe-php-shim/src/process.rs
@@ -1,4 +1,4 @@
-use crate::{PhpMixed, PhpResource};
+use crate::{ChildPipe, PhpMixed, PhpResource, StreamBacking, StreamState};
use indexmap::IndexMap;
pub const SIGINT: i64 = 2;
@@ -130,33 +130,215 @@ pub fn escapeshellarg(arg: &str) -> String {
out
}
-// TODO(phase-c): reports proc_open as unavailable (returns false), so callers fall back to
-// their defaults. A real implementation requires holding the child process and its pipes; defer
-// it to the broader process-subsystem work (ProcessExecutor).
+/// State held behind a `PhpResource::Process` handle returned by `proc_open`.
+#[derive(Debug)]
+pub struct ProcessState {
+ /// The spawned child. Taken by `proc_close`/`wait`; once taken the handle is closed.
+ child: Option<std::process::Child>,
+ /// The command line passed to `proc_open`, reported back by `proc_get_status`.
+ command: String,
+}
+
+/// One entry of the `descriptorspec` array passed to `proc_open`. Unlike PHP's array this is a
+/// native type so it can carry a live `PhpResource` (e.g. a `/dev/null` stream).
+#[derive(Debug)]
+pub enum Descriptor {
+ /// `['pipe', mode]` — `mode` is `"r"`/`"w"` from the child's point of view.
+ Pipe(String),
+ /// `['file', path, mode]`.
+ File(String, String),
+ /// `['pty']`.
+ Pty,
+ /// An already-opened stream resource used directly as the descriptor.
+ Resource(PhpResource),
+ /// A descriptor index left unspecified by a sparse PHP descriptorspec; the child inherits the
+ /// corresponding parent fd.
+ Inherit,
+}
+
+/// Extracts a `try_clone`d `std::fs::File` from a file-backed stream resource so it can be handed
+/// to `Stdio::from` as a `proc_open` descriptor.
+fn resource_to_file(resource: &PhpResource) -> std::io::Result<std::fs::File> {
+ match resource {
+ PhpResource::Stream(state) => {
+ let state = state.borrow();
+ match &state.backing {
+ StreamBacking::File(f) => f.try_clone(),
+ _ => Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "proc_open descriptor resource is not a file-backed stream",
+ )),
+ }
+ }
+ _ => Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "proc_open descriptor is not a stream resource",
+ )),
+ }
+}
+
+/// PHP `proc_open`. Returns the process resource on success; the PHP `false` return is modeled as
+/// `Err`. The `pipes` out-parameter is filled with the parent-side pipe streams keyed by fd index.
pub fn proc_open(
- _command: &str,
- _descriptorspec: &[PhpMixed],
- _pipes: &mut PhpMixed,
- _cwd: Option<&str>,
- _env: Option<&[String]>,
- _options: Option<&IndexMap<String, PhpMixed>>,
-) -> PhpMixed {
- PhpMixed::Bool(false)
+ command: &str,
+ descriptorspec: &[Descriptor],
+ pipes: &mut IndexMap<i64, PhpResource>,
+ cwd: Option<&str>,
+ env: Option<&[String]>,
+ options: Option<&IndexMap<String, PhpMixed>>,
+) -> std::io::Result<PhpResource> {
+ // Windows-oriented options (bypass_shell, create_process_group, ...) have no effect here.
+ let _ = options;
+
+ let mut cmd = std::process::Command::new("/bin/sh");
+ cmd.arg("-c").arg(command);
+
+ if let Some(cwd) = cwd {
+ cmd.current_dir(cwd);
+ }
+
+ if let Some(env) = env {
+ // A provided environment replaces the inherited one, matching proc_open.
+ cmd.env_clear();
+ for pair in env {
+ match pair.split_once('=') {
+ Some((k, v)) => cmd.env(k, v),
+ None => cmd.env(pair, ""),
+ };
+ }
+ }
+
+ // Remember which fds requested a pipe so their ends can be taken after spawn.
+ let mut pipe_modes: Vec<(i64, String)> = Vec::new();
+ for (index, descriptor) in descriptorspec.iter().enumerate() {
+ let fd = index as i64;
+ let stdio = match descriptor {
+ Descriptor::Pipe(mode) => {
+ pipe_modes.push((fd, mode.clone()));
+ std::process::Stdio::piped()
+ }
+ Descriptor::File(path, mode) => {
+ std::process::Stdio::from(resource_to_file(&crate::fs::fopen(path, mode)?)?)
+ }
+ Descriptor::Resource(resource) => {
+ std::process::Stdio::from(resource_to_file(resource)?)
+ }
+ Descriptor::Inherit => std::process::Stdio::inherit(),
+ Descriptor::Pty => {
+ // TODO(phase-d): pty descriptors need a pseudo-terminal (openpty/ioctl); a syscall
+ // crate is intentionally not introduced here.
+ todo!("proc_open: pty descriptors require a pseudo-terminal (syscall)")
+ }
+ };
+ match fd {
+ 0 => cmd.stdin(stdio),
+ 1 => cmd.stdout(stdio),
+ 2 => cmd.stderr(stdio),
+ _ => {
+ // TODO(phase-d): inheriting fds >= 3 (e.g. the --enable-sigchild pipe 3) requires
+ // dup2/pre_exec; a syscall crate is intentionally not introduced here.
+ todo!("proc_open: descriptors with fd >= 3 require fd inheritance (syscall)")
+ }
+ };
+ }
+
+ let mut child = cmd.spawn()?;
+
+ for (fd, mode) in pipe_modes {
+ // fd 0 is the child's stdin: the parent-side handle is writable. fds 1/2 are stdout/stderr:
+ // the parent reads them.
+ let (pipe, readable, writable) = match fd {
+ 0 => (ChildPipe::In(child.stdin.take().unwrap()), false, true),
+ 1 => (ChildPipe::Out(child.stdout.take().unwrap()), true, false),
+ 2 => (ChildPipe::Err(child.stderr.take().unwrap()), true, false),
+ _ => unreachable!(),
+ };
+ let resource = StreamState::new(
+ StreamBacking::Pipe(pipe),
+ readable,
+ writable,
+ mode,
+ format!("pipe:fd{}", fd),
+ );
+ pipes.insert(fd, resource);
+ }
+
+ Ok(PhpResource::Process(std::rc::Rc::new(
+ std::cell::RefCell::new(ProcessState {
+ child: Some(child),
+ command: command.to_string(),
+ }),
+ )))
}
-pub fn proc_close(_process: PhpMixed) -> i64 {
+/// PHP `proc_close`. Waits for the process to terminate and returns its exit code (-1 on failure).
+/// Pipes are expected to have been closed by the caller beforehand.
+pub fn proc_close(process: &PhpResource) -> i64 {
+ if let PhpResource::Process(state) = process {
+ let mut state = state.borrow_mut();
+ if let Some(mut child) = state.child.take() {
+ return match child.wait() {
+ Ok(status) => status.code().map(|c| c as i64).unwrap_or(-1),
+ Err(_) => -1,
+ };
+ }
+ }
-1
}
-pub fn proc_get_status(_process: &PhpMixed) -> IndexMap<String, PhpMixed> {
- // TODO(phase-d): depends on proc_open returning a real process handle, which is itself deferred
- // (see proc_open above). Without a live child there is no status to report.
- todo!()
+/// PHP `proc_get_status`. Reports the live status of the process behind the resource.
+pub fn proc_get_status(process: &PhpResource) -> IndexMap<String, PhpMixed> {
+ use std::os::unix::process::ExitStatusExt;
+
+ let mut status = IndexMap::new();
+ let PhpResource::Process(state) = process else {
+ return status;
+ };
+ let mut state = state.borrow_mut();
+
+ let pid = state.child.as_ref().map(|c| c.id() as i64).unwrap_or(-1);
+ let mut running = false;
+ let mut signaled = false;
+ let mut exitcode = -1i64;
+ let mut termsig = 0i64;
+
+ if let Some(child) = state.child.as_mut() {
+ match child.try_wait() {
+ Ok(None) => running = true,
+ Ok(Some(exit)) => {
+ if let Some(code) = exit.code() {
+ exitcode = code as i64;
+ }
+ if let Some(sig) = exit.signal() {
+ signaled = true;
+ termsig = sig as i64;
+ }
+ }
+ Err(_) => {}
+ }
+ }
+
+ status.insert(
+ "command".to_string(),
+ PhpMixed::String(state.command.clone()),
+ );
+ status.insert("pid".to_string(), PhpMixed::Int(pid));
+ status.insert("running".to_string(), PhpMixed::Bool(running));
+ status.insert("signaled".to_string(), PhpMixed::Bool(signaled));
+ status.insert("stopped".to_string(), PhpMixed::Bool(false));
+ status.insert("exitcode".to_string(), PhpMixed::Int(exitcode));
+ status.insert("termsig".to_string(), PhpMixed::Int(termsig));
+ status.insert("stopsig".to_string(), PhpMixed::Int(0));
+ status
}
-pub fn proc_terminate(_process: &PhpMixed, _signal: i64) -> bool {
- // TODO(phase-d): depends on proc_open returning a real process handle (see proc_open above).
- todo!()
+pub fn proc_terminate(process: &PhpResource, signal: i64) -> bool {
+ let _ = (process, signal);
+ // TODO(phase-d): sending an arbitrary signal requires kill(2); std's Child::kill only sends
+ // SIGKILL and a syscall crate is intentionally not introduced here.
+ todo!(
+ "proc_terminate: arbitrary signal delivery requires kill(2) (syscall crate not available)"
+ )
}
pub fn getmypid() -> i64 {
@@ -210,8 +392,8 @@ pub fn posix_isatty(stream: PhpResource) -> bool {
PhpResource::Stdin => std::io::stdin().is_terminal(),
PhpResource::Stdout => std::io::stdout().is_terminal(),
PhpResource::Stderr => std::io::stderr().is_terminal(),
- // A regular file or in-memory stream is never a tty.
- PhpResource::Stream(_) => false,
+ // A regular file, in-memory stream or process handle is never a tty.
+ PhpResource::Stream(_) | PhpResource::Process(_) => false,
}
}
@@ -225,3 +407,106 @@ pub fn get_current_user() -> String {
// getpwuid(3); neither is reachable without a libc/syscall crate.
todo!()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fs::{fclose, fwrite};
+ use crate::stream::stream_get_contents;
+
+ #[test]
+ fn proc_open_reads_stdout_and_reports_status() {
+ let mut pipes = IndexMap::new();
+ let process = proc_open(
+ "echo hi",
+ &[
+ Descriptor::Inherit,
+ Descriptor::Pipe("w".to_string()),
+ Descriptor::Inherit,
+ ],
+ &mut pipes,
+ None,
+ None,
+ None,
+ )
+ .unwrap();
+
+ let stdout = pipes.get(&1).unwrap();
+ assert_eq!(stream_get_contents(stdout).unwrap(), "hi\n");
+
+ // Reading to EOF means the child has finished; the status converges to "not running".
+ let status = loop {
+ let status = proc_get_status(&process);
+ if !crate::php_truthy(status.get("running").unwrap()) {
+ break status;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ };
+ assert_eq!(status.get("command").unwrap().as_string(), Some("echo hi"));
+ assert!(status.get("pid").unwrap().as_int().unwrap() > 0);
+ assert_eq!(status.get("exitcode").unwrap().as_int(), Some(0));
+ assert_eq!(status.get("signaled").unwrap().as_bool(), Some(false));
+
+ for (_, pipe) in &pipes {
+ fclose(pipe);
+ }
+ assert_eq!(proc_close(&process), 0);
+ }
+
+ #[test]
+ fn proc_open_writes_stdin_pipe() {
+ let mut pipes = IndexMap::new();
+ let process = proc_open(
+ "cat",
+ &[
+ Descriptor::Pipe("r".to_string()),
+ Descriptor::Pipe("w".to_string()),
+ Descriptor::Inherit,
+ ],
+ &mut pipes,
+ None,
+ None,
+ None,
+ )
+ .unwrap();
+
+ fwrite(pipes.get(&0).unwrap(), "ping\n", None);
+ fclose(pipes.get(&0).unwrap());
+ // Dropping the last handle closes the fd so `cat` sees end-of-input.
+ pipes.shift_remove(&0);
+
+ assert_eq!(
+ stream_get_contents(pipes.get(&1).unwrap()).unwrap(),
+ "ping\n"
+ );
+
+ assert_eq!(proc_close(&process), 0);
+ }
+
+ #[test]
+ fn proc_open_redirects_stdout_to_file() {
+ let path =
+ std::env::temp_dir().join(format!("shirabe_proc_open_{}.txt", std::process::id()));
+ let path_str = path.to_str().unwrap();
+
+ let mut pipes = IndexMap::new();
+ let process = proc_open(
+ "echo filetest",
+ &[
+ Descriptor::Inherit,
+ Descriptor::File(path_str.to_string(), "w".to_string()),
+ Descriptor::Inherit,
+ ],
+ &mut pipes,
+ None,
+ None,
+ None,
+ )
+ .unwrap();
+ assert!(pipes.is_empty());
+ assert_eq!(proc_close(&process), 0);
+
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "filetest\n");
+ std::fs::remove_file(&path).ok();
+ }
+}
diff --git a/crates/shirabe-php-shim/src/stream.rs b/crates/shirabe-php-shim/src/stream.rs
index 5e43316..2ecfc62 100644
--- a/crates/shirabe-php-shim/src/stream.rs
+++ b/crates/shirabe-php-shim/src/stream.rs
@@ -43,7 +43,7 @@ fn stream_read_remaining(stream: &PhpResource, max_length: Option<i64>) -> Optio
}
Some(String::from_utf8_lossy(&buf).into_owned())
}
- PhpResource::Stdout | PhpResource::Stderr => None,
+ PhpResource::Stdout | PhpResource::Stderr | PhpResource::Process(_) => None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.readable {
@@ -92,7 +92,7 @@ pub fn stream_copy_to_stream(source: &PhpResource, dest: &PhpResource) -> Option
PhpResource::Stdin => {
std::io::stdin().read_to_end(&mut buf).ok()?;
}
- PhpResource::Stdout | PhpResource::Stderr => return None,
+ PhpResource::Stdout | PhpResource::Stderr | PhpResource::Process(_) => return None,
PhpResource::Stream(state) => {
let mut state = state.borrow_mut();
if state.closed || !state.readable {
@@ -102,7 +102,7 @@ pub fn stream_copy_to_stream(source: &PhpResource, dest: &PhpResource) -> Option
}
}
match dest {
- PhpResource::Stdin => None,
+ PhpResource::Stdin | PhpResource::Process(_) => None,
PhpResource::Stdout => std::io::stdout()
.write_all(&buf)
.ok()
@@ -128,13 +128,14 @@ pub fn stream_isatty_resource(resource: &PhpResource) -> bool {
PhpResource::Stdin => std::io::stdin().is_terminal(),
PhpResource::Stdout => std::io::stdout().is_terminal(),
PhpResource::Stderr => std::io::stderr().is_terminal(),
- PhpResource::Stream(_) => false,
+ PhpResource::Stream(_) | PhpResource::Process(_) => false,
}
}
pub fn stream_get_meta_data(resource: &PhpResource) -> IndexMap<String, PhpMixed> {
// (timed_out, blocked, eof, wrapper_type, stream_type, mode, seekable, uri)
let (eof, wrapper_type, stream_type, mode, seekable, uri) = match resource {
+ PhpResource::Process(_) => (false, "PHP", "STDIO", String::new(), false, ""),
PhpResource::Stdin => (false, "PHP", "STDIO", "r".to_string(), false, "php://stdin"),
PhpResource::Stdout => (
false,
@@ -163,6 +164,7 @@ pub fn stream_get_meta_data(resource: &PhpResource) -> IndexMap<String, PhpMixed
}
}
StreamBacking::File(_) => ("plainfile", "STDIO"),
+ StreamBacking::Pipe(_) => ("PHP", "STDIO"),
};
return build_meta_data(
state.eof,
@@ -205,17 +207,23 @@ fn build_meta_data(
}
pub fn stream_set_blocking(_resource: &PhpResource, _enable: bool) -> bool {
- todo!()
+ // TODO(phase-d): toggling O_NONBLOCK requires fcntl(2); a syscall crate is intentionally not
+ // introduced here.
+ todo!("stream_set_blocking requires fcntl(2) (syscall crate not available)")
}
+/// PHP `stream_select`. Returns the number of changed streams, or `None` for the PHP `false`
+/// returned when the underlying `select` is interrupted/fails.
pub fn stream_select(
_read: &mut Vec<PhpResource>,
_write: &mut Vec<PhpResource>,
_except: &mut Vec<PhpResource>,
_seconds: i64,
_microseconds: Option<i64>,
-) -> i64 {
- todo!()
+) -> Option<i64> {
+ // TODO(phase-d): multiplexing readiness requires select(2)/poll(2); a syscall crate is
+ // intentionally not introduced here.
+ todo!("stream_select requires select(2)/poll(2) (syscall crate not available)")
}
/// PHP `stream_get_contents($stream, $maxlength, $offset)`. A non-negative `offset` seeks there
@@ -236,8 +244,11 @@ pub fn is_resource_value(_resource: &PhpResource) -> bool {
true
}
-pub fn get_resource_type(_resource: &PhpResource) -> String {
- "stream".to_string()
+pub fn get_resource_type(resource: &PhpResource) -> String {
+ match resource {
+ PhpResource::Process(_) => "process".to_string(),
+ _ => "stream".to_string(),
+ }
}
/// Convenience wrapper over `fopen` for callers that open never-failing `php://` stdio streams and