diff options
| author | nsfisis <nsfisis@gmail.com> | 2026-06-24 03:09:17 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2026-06-24 03:09:17 +0900 |
| commit | c5fc34a106a706ac12925c4df273a926811d260b (patch) | |
| tree | 24e798c4a00b32aa1a1f155b705d02fba9895875 | |
| parent | b2b321a26f6a628ee8e6757eb8577613e2024e70 (diff) | |
| download | php-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>
12 files changed, 649 insertions, 193 deletions
diff --git a/crates/shirabe-external-packages/src/symfony/console/cursor.rs b/crates/shirabe-external-packages/src/symfony/console/cursor.rs index 811553f..c36f9b5 100644 --- a/crates/shirabe-external-packages/src/symfony/console/cursor.rs +++ b/crates/shirabe-external-packages/src/symfony/console/cursor.rs @@ -181,31 +181,20 @@ impl Cursor { let is_tty_supported = if shirabe_php_shim::function_exists("proc_open") { *IS_TTY_SUPPORTED.get_or_init(|| { - let mut pipes = shirabe_php_shim::PhpMixed::Null; - shirabe_php_shim::php_truthy(&shirabe_php_shim::proc_open( + let mut pipes = indexmap::IndexMap::new(); + shirabe_php_shim::proc_open( "echo 1 >/dev/null", - &vec![ - shirabe_php_shim::PhpMixed::List(vec![ - shirabe_php_shim::PhpMixed::String("file".to_string()), - shirabe_php_shim::PhpMixed::String("/dev/tty".to_string()), - shirabe_php_shim::PhpMixed::String("r".to_string()), - ]), - shirabe_php_shim::PhpMixed::List(vec![ - shirabe_php_shim::PhpMixed::String("file".to_string()), - shirabe_php_shim::PhpMixed::String("/dev/tty".to_string()), - shirabe_php_shim::PhpMixed::String("w".to_string()), - ]), - shirabe_php_shim::PhpMixed::List(vec![ - shirabe_php_shim::PhpMixed::String("file".to_string()), - shirabe_php_shim::PhpMixed::String("/dev/tty".to_string()), - shirabe_php_shim::PhpMixed::String("w".to_string()), - ]), + &[ + shirabe_php_shim::Descriptor::File("/dev/tty".to_string(), "r".to_string()), + shirabe_php_shim::Descriptor::File("/dev/tty".to_string(), "w".to_string()), + shirabe_php_shim::Descriptor::File("/dev/tty".to_string(), "w".to_string()), ], &mut pipes, None, None, None, - )) + ) + .is_ok() }) } else { false diff --git a/crates/shirabe-external-packages/src/symfony/console/helper/question_helper.rs b/crates/shirabe-external-packages/src/symfony/console/helper/question_helper.rs index 1fc90bd..2bdd929 100644 --- a/crates/shirabe-external-packages/src/symfony/console/helper/question_helper.rs +++ b/crates/shirabe-external-packages/src/symfony/console/helper/question_helper.rs @@ -377,13 +377,14 @@ impl QuestionHelper { // Read a keypress while !shirabe_php_shim::feof(input_stream) { while is_stdin - && 0 == shirabe_php_shim::stream_select( - &mut r, - &mut w.clone(), - &mut w.clone(), - 0, - Some(100), - ) + && Some(0) + == shirabe_php_shim::stream_select( + &mut r, + &mut w.clone(), + &mut w.clone(), + 0, + Some(100), + ) { // Give signal handlers a chance to run r = vec![input_stream.clone()]; diff --git a/crates/shirabe-external-packages/src/symfony/console/terminal.rs b/crates/shirabe-external-packages/src/symfony/console/terminal.rs index ac4009e..c02b87f 100644 --- a/crates/shirabe-external-packages/src/symfony/console/terminal.rs +++ b/crates/shirabe-external-packages/src/symfony/console/terminal.rs @@ -208,49 +208,48 @@ impl Terminal { return None; } - let descriptorspec: Vec<PhpMixed> = vec![ - PhpMixed::List(vec![ - PhpMixed::String("pipe".to_string()), - PhpMixed::String("w".to_string()), - ]), - PhpMixed::List(vec![ - PhpMixed::String("pipe".to_string()), - PhpMixed::String("w".to_string()), - ]), + // Sparse PHP descriptorspec `[1 => ['pipe', 'w'], 2 => ['pipe', 'w']]`: fd 0 is inherited. + let descriptorspec = [ + shirabe_php_shim::Descriptor::Inherit, + shirabe_php_shim::Descriptor::Pipe("w".to_string()), + shirabe_php_shim::Descriptor::Pipe("w".to_string()), ]; - let _cp = if shirabe_php_shim::function_exists("sapi_windows_cp_set") { + let cp = if shirabe_php_shim::function_exists("sapi_windows_cp_set") { shirabe_php_shim::sapi_windows_cp_get(None) } else { 0 }; - let mut pipes = PhpMixed::Null; - let process = - shirabe_php_shim::proc_open(command, &descriptorspec, &mut pipes, None, None, None); - if !shirabe_php_shim::php_truthy(&process) { - return None; + let mut pipes: indexmap::IndexMap<i64, shirabe_php_shim::PhpResource> = + indexmap::IndexMap::new(); + let process = match shirabe_php_shim::proc_open( + command, + &descriptorspec, + &mut pipes, + None, + None, + None, + ) { + Ok(process) => process, + Err(_) => return None, + }; + + let info = pipes + .get(&1) + .and_then(shirabe_php_shim::stream_get_contents); + if let Some(pipe) = pipes.get(&1) { + shirabe_php_shim::fclose(pipe); } + if let Some(pipe) = pipes.get(&2) { + shirabe_php_shim::fclose(pipe); + } + shirabe_php_shim::proc_close(&process); - // $pipes[1] and $pipes[2] from proc_open's output array. - let _pipe1 = php_pipe(&pipes, 1); - let _pipe2 = php_pipe(&pipes, 2); - // TODO(phase-d): the pipe contents are read via stream_get_contents() and the pipes are - // fclose()d, but they are PHP stream resources the PhpMixed pipe list cannot hold. - todo!( - "Terminal: reading proc_open pipes needs PhpResource handles the PhpMixed pipe list cannot carry" - ); - } -} + if cp != 0 { + shirabe_php_shim::sapi_windows_cp_set(cp); + } -/// Indexes into the `$pipes` array populated by proc_open. -fn php_pipe(pipes: &PhpMixed, index: i64) -> PhpMixed { - match pipes { - PhpMixed::List(list) => list.get(index as usize).cloned().unwrap_or(PhpMixed::Null), - PhpMixed::Array(array) => array - .get(&index.to_string()) - .map(|v| v.clone()) - .unwrap_or(PhpMixed::Null), - _ => PhpMixed::Null, + info } } diff --git a/crates/shirabe-external-packages/src/symfony/process/pipes/abstract_pipes.rs b/crates/shirabe-external-packages/src/symfony/process/pipes/abstract_pipes.rs index d8ced43..5b85813 100644 --- a/crates/shirabe-external-packages/src/symfony/process/pipes/abstract_pipes.rs +++ b/crates/shirabe-external-packages/src/symfony/process/pipes/abstract_pipes.rs @@ -1,11 +1,11 @@ //! ref: composer/vendor/symfony/process/Pipes/AbstractPipes.php use indexmap::IndexMap; -use shirabe_php_shim::{self as php, PhpMixed}; +use shirabe_php_shim::{self as php, PhpMixed, PhpResource}; #[derive(Debug)] pub struct AbstractPipes { - pub pipes: PhpMixed, + pub pipes: IndexMap<i64, PhpResource>, input_buffer: String, input: PhpMixed, @@ -17,6 +17,8 @@ impl AbstractPipes { pub fn new(input: PhpMixed) -> Self { let mut input_buffer = String::new(); let stored_input; + // TODO(plugin): `$input instanceof \Iterator` is not modeled. `is_resource` on a PhpMixed is + // always false, so the resource branch never stores input here. if php::is_resource(&input) { stored_input = input; } else if let PhpMixed::String(s) = &input { @@ -28,7 +30,7 @@ impl AbstractPipes { } Self { - pipes: PhpMixed::List(Vec::new()), + pipes: IndexMap::new(), input_buffer, input: stored_input, blocked: true, @@ -37,9 +39,10 @@ impl AbstractPipes { } pub fn close(&mut self) { - // TODO(phase-d): each pipe is a PHP stream resource that should be fclose()d, but the pipe - // list is a PhpMixed that cannot hold a PhpResource; the handles are dropped instead. - self.pipes = PhpMixed::List(Vec::new()); + for (_, pipe) in &self.pipes { + php::fclose(pipe); + } + self.pipes = IndexMap::new(); } /// Returns true if a system call has been interrupted. @@ -54,14 +57,52 @@ impl AbstractPipes { /// Unblocks streams. pub(crate) fn unblock(&mut self) { - let _ = &self.input_buffer; - let _ = &self.blocked; - todo!() + if !self.blocked { + return; + } + + for (_, pipe) in &self.pipes { + php::stream_set_blocking(pipe, false); + } + // The `is_resource($this->input)` branch does not apply: `input` is never a resource in this + // port (is_resource on a PhpMixed is always false). + + self.blocked = false; } /// Writes input to stdin. - pub(crate) fn write(&mut self) -> Option<IndexMap<i64, PhpMixed>> { - todo!() + pub(crate) fn write(&mut self) -> Option<Vec<PhpResource>> { + let stdin = self.pipes.get(&0)?.clone(); + + // TODO(plugin): the `$input instanceof \Iterator` branch is not modeled. `input` is never a + // resource here, so the fread($input)/stream_set_blocking($input) paths do not apply and + // only the input buffer is written to stdin. + + let mut r: Vec<PhpResource> = Vec::new(); + let mut e: Vec<PhpResource> = Vec::new(); + let mut w: Vec<PhpResource> = vec![stdin.clone()]; + + // let's have a look if something changed in streams + if php::stream_select(&mut r, &mut w, &mut e, 0, Some(0)).is_none() { + return None; + } + + if !self.input_buffer.is_empty() { + let written = php::fwrite(&stdin, &self.input_buffer, None).unwrap_or(0) as usize; + self.input_buffer = self.input_buffer.get(written..).unwrap_or("").to_string(); + if !self.input_buffer.is_empty() { + return Some(vec![stdin]); + } + } + + // no input to read on resource, buffer is empty + if self.input_buffer.is_empty() && !php::php_truthy(&self.input) { + self.input = PhpMixed::Null; + php::fclose(&stdin); + self.pipes.shift_remove(&0); + } + + None } pub fn handle_error(&mut self, _type: i64, msg: String) { diff --git a/crates/shirabe-external-packages/src/symfony/process/pipes/pipes_interface.rs b/crates/shirabe-external-packages/src/symfony/process/pipes/pipes_interface.rs index e10b3b3..92d584d 100644 --- a/crates/shirabe-external-packages/src/symfony/process/pipes/pipes_interface.rs +++ b/crates/shirabe-external-packages/src/symfony/process/pipes/pipes_interface.rs @@ -1,14 +1,14 @@ //! ref: composer/vendor/symfony/process/Pipes/PipesInterface.php use indexmap::IndexMap; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{Descriptor, PhpResource}; pub const CHUNK_SIZE: i64 = 16384; /// PipesInterface manages descriptors and pipes for the use of proc_open. pub trait PipesInterface: std::fmt::Debug { /// Returns an array of descriptors for the use of proc_open. - fn get_descriptors(&mut self) -> Vec<PhpMixed>; + fn get_descriptors(&mut self) -> Vec<Descriptor>; /// Returns an array of filenames indexed by their related stream in case these pipes use temporary files. fn get_files(&self) -> IndexMap<i64, String>; @@ -25,7 +25,7 @@ pub trait PipesInterface: std::fmt::Debug { /// Closes file handles and pipes. fn close(&mut self); - /// Accessor for the `pipes` property populated by proc_open. - fn pipes(&self) -> &PhpMixed; - fn pipes_mut(&mut self) -> &mut PhpMixed; + /// Accessor for the `pipes` property populated by proc_open, keyed by fd index. + fn pipes(&self) -> &IndexMap<i64, PhpResource>; + fn pipes_mut(&mut self) -> &mut IndexMap<i64, PhpResource>; } diff --git a/crates/shirabe-external-packages/src/symfony/process/pipes/unix_pipes.rs b/crates/shirabe-external-packages/src/symfony/process/pipes/unix_pipes.rs index 983ed07..795bb64 100644 --- a/crates/shirabe-external-packages/src/symfony/process/pipes/unix_pipes.rs +++ b/crates/shirabe-external-packages/src/symfony/process/pipes/unix_pipes.rs @@ -1,10 +1,10 @@ //! ref: composer/vendor/symfony/process/Pipes/UnixPipes.php use indexmap::IndexMap; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{self as php, Descriptor, PhpMixed, PhpResource}; use crate::symfony::process::pipes::abstract_pipes::AbstractPipes; -use crate::symfony::process::pipes::pipes_interface::PipesInterface; +use crate::symfony::process::pipes::pipes_interface::{CHUNK_SIZE, PipesInterface}; use crate::symfony::process::process::Process; /// UnixPipes implementation uses unix pipes as handles. @@ -32,24 +32,24 @@ impl UnixPipes { } } -fn descriptor(items: &[&str]) -> PhpMixed { - PhpMixed::List( - items - .iter() - .map(|s| PhpMixed::String(s.to_string())) - .collect(), - ) +fn descriptor(items: &[&str]) -> Descriptor { + match items { + ["pipe", mode] => Descriptor::Pipe(mode.to_string()), + ["file", path, mode] => Descriptor::File(path.to_string(), mode.to_string()), + ["pty"] => Descriptor::Pty, + _ => panic!("unsupported descriptor spec: {:?}", items), + } } impl PipesInterface for UnixPipes { - fn get_descriptors(&mut self) -> Vec<PhpMixed> { + fn get_descriptors(&mut self) -> Vec<Descriptor> { if !self.have_read_support { - // TODO(phase-d): /dev/null is opened as a stream resource and placed directly into the - // proc_open descriptor spec, but the descriptor list is a Vec<PhpMixed> that cannot - // carry a PhpResource. - todo!( - "UnixPipes::get_descriptors: the /dev/null resource cannot be represented in a PhpMixed descriptor list" - ); + let nullstream = php::fopen("/dev/null", "c").expect("fopen('/dev/null') failed"); + return vec![ + descriptor(&["pipe", "r"]), + Descriptor::Resource(nullstream.clone()), + Descriptor::Resource(nullstream), + ]; } if self.tty_mode == Some(true) { @@ -79,8 +79,71 @@ impl PipesInterface for UnixPipes { IndexMap::new() } - fn read_and_write(&mut self, _blocking: bool, _close: bool) -> IndexMap<i64, String> { - todo!() + fn read_and_write(&mut self, blocking: bool, close: bool) -> IndexMap<i64, String> { + self.inner.unblock(); + let w = self.inner.write(); + + let mut read: IndexMap<i64, String> = IndexMap::new(); + // $r = $this->pipes; unset($r[0]); + let r: Vec<(i64, PhpResource)> = self + .inner + .pipes + .iter() + .filter(|(fd, _)| **fd != 0) + .map(|(fd, pipe)| (*fd, pipe.clone())) + .collect(); + + // TODO(plugin): set_error_handler/restore_error_handler around stream_select is not modeled. + let mut r_sel: Vec<PhpResource> = r.iter().map(|(_, p)| p.clone()).collect(); + let mut w_sel: Vec<PhpResource> = w.clone().unwrap_or_default(); + let mut e_sel: Vec<PhpResource> = Vec::new(); + + // let's have a look if something changed in streams + if (!r_sel.is_empty() || w.is_some()) + && php::stream_select( + &mut r_sel, + &mut w_sel, + &mut e_sel, + 0, + Some(if blocking { + (Process::TIMEOUT_PRECISION * 1e6) as i64 + } else { + 0 + }), + ) + .is_none() + { + // if a system call has been interrupted, forget about it, let's try again + // otherwise, an error occurred, let's reset pipes + if !self.inner.has_system_call_been_interrupted() { + self.inner.pipes = IndexMap::new(); + } + + return read; + } + + for (fd, pipe) in &r { + let mut data = String::new(); + loop { + let chunk = php::fread(pipe, CHUNK_SIZE).unwrap_or_default(); + let len = chunk.len() as i64; + data.push_str(&chunk); + if !(len > 0 && (close || len >= CHUNK_SIZE)) { + break; + } + } + + if !data.is_empty() { + read.insert(*fd, data); + } + + if close && php::feof(pipe) { + php::fclose(pipe); + self.inner.pipes.shift_remove(fd); + } + } + + read } fn have_read_support(&self) -> bool { @@ -88,18 +151,18 @@ impl PipesInterface for UnixPipes { } fn are_open(&self) -> bool { - shirabe_php_shim::php_truthy(&self.inner.pipes) + !self.inner.pipes.is_empty() } fn close(&mut self) { self.inner.close(); } - fn pipes(&self) -> &PhpMixed { + fn pipes(&self) -> &IndexMap<i64, PhpResource> { &self.inner.pipes } - fn pipes_mut(&mut self) -> &mut PhpMixed { + fn pipes_mut(&mut self) -> &mut IndexMap<i64, PhpResource> { &mut self.inner.pipes } } diff --git a/crates/shirabe-external-packages/src/symfony/process/pipes/windows_pipes.rs b/crates/shirabe-external-packages/src/symfony/process/pipes/windows_pipes.rs index 7602e7d..a31f184 100644 --- a/crates/shirabe-external-packages/src/symfony/process/pipes/windows_pipes.rs +++ b/crates/shirabe-external-packages/src/symfony/process/pipes/windows_pipes.rs @@ -1,7 +1,7 @@ //! ref: composer/vendor/symfony/process/Pipes/WindowsPipes.php use indexmap::IndexMap; -use shirabe_php_shim::PhpMixed; +use shirabe_php_shim::{Descriptor, PhpMixed, PhpResource}; use crate::symfony::process::pipes::abstract_pipes::AbstractPipes; use crate::symfony::process::pipes::pipes_interface::PipesInterface; @@ -11,8 +11,8 @@ use crate::symfony::process::pipes::pipes_interface::PipesInterface; pub struct WindowsPipes { inner: AbstractPipes, files: IndexMap<i64, String>, - file_handles: IndexMap<i64, PhpMixed>, - lock_handles: IndexMap<i64, PhpMixed>, + file_handles: IndexMap<i64, PhpResource>, + lock_handles: IndexMap<i64, PhpResource>, read_bytes: IndexMap<i64, i64>, have_read_support: bool, } @@ -25,7 +25,7 @@ impl WindowsPipes { } impl PipesInterface for WindowsPipes { - fn get_descriptors(&mut self) -> Vec<PhpMixed> { + fn get_descriptors(&mut self) -> Vec<Descriptor> { let _ = ( &self.files, &self.file_handles, @@ -48,7 +48,7 @@ impl PipesInterface for WindowsPipes { } fn are_open(&self) -> bool { - shirabe_php_shim::php_truthy(&self.inner.pipes) && !self.file_handles.is_empty() + !self.inner.pipes.is_empty() && !self.file_handles.is_empty() } fn close(&mut self) { @@ -56,11 +56,11 @@ impl PipesInterface for WindowsPipes { todo!() } - fn pipes(&self) -> &PhpMixed { + fn pipes(&self) -> &IndexMap<i64, PhpResource> { &self.inner.pipes } - fn pipes_mut(&mut self) -> &mut PhpMixed { + fn pipes_mut(&mut self) -> &mut IndexMap<i64, PhpResource> { &mut self.inner.pipes } } diff --git a/crates/shirabe-external-packages/src/symfony/process/process.rs b/crates/shirabe-external-packages/src/symfony/process/process.rs index d0d104e..caf8aa1 100644 --- a/crates/shirabe-external-packages/src/symfony/process/process.rs +++ b/crates/shirabe-external-packages/src/symfony/process/process.rs @@ -3,7 +3,7 @@ use std::sync::OnceLock; use indexmap::IndexMap; -use shirabe_php_shim::{self as php, PhpMixed, PhpResource}; +use shirabe_php_shim::{self as php, Descriptor, PhpMixed, PhpResource}; use crate::symfony::process::exception::invalid_argument_exception::InvalidArgumentException; use crate::symfony::process::exception::logic_exception::LogicException; @@ -50,7 +50,7 @@ pub struct Process { output_disabled: bool, stdout: Option<PhpResource>, stderr: Option<PhpResource>, - process: PhpMixed, + process: Option<PhpResource>, status: String, incremental_output_offset: i64, incremental_error_output_offset: i64, @@ -74,24 +74,12 @@ impl std::fmt::Debug for Process { } } -fn descriptor(items: &[&str]) -> PhpMixed { - PhpMixed::List( - items - .iter() - .map(|s| PhpMixed::String(s.to_string())) - .collect(), - ) -} - -/// Index into the `$pipes` array (a PhpMixed list/array) populated by proc_open. -fn php_pipe(pipes: &PhpMixed, index: i64) -> PhpMixed { - match pipes { - PhpMixed::List(list) => list.get(index as usize).cloned().unwrap_or(PhpMixed::Null), - PhpMixed::Array(array) => array - .get(&index.to_string()) - .cloned() - .unwrap_or(PhpMixed::Null), - _ => PhpMixed::Null, +fn descriptor(items: &[&str]) -> Descriptor { + match items { + ["pipe", mode] => Descriptor::Pipe(mode.to_string()), + ["file", path, mode] => Descriptor::File(path.to_string(), mode.to_string()), + ["pty"] => Descriptor::Pty, + _ => panic!("unsupported descriptor spec: {:?}", items), } } @@ -201,7 +189,7 @@ impl Process { output_disabled: false, stdout: None, stderr: None, - process: PhpMixed::Null, + process: None, status: Self::STATUS_READY.to_string(), incremental_output_offset: 0, incremental_error_output_offset: 0, @@ -397,9 +385,9 @@ impl Process { Some(&options), ) }; - self.process = process; + self.process = process.ok(); - if !php::php_truthy(&self.process) { + if self.process.is_none() { return Err( RuntimeException::new("Unable to launch a new process.".to_string()).into(), ); @@ -407,12 +395,19 @@ impl Process { self.status = Self::STATUS_STARTED.to_string(); if descriptors.len() > 3 { - let _pipe3 = php_pipe(self.process_pipes.as_ref().unwrap().pipes(), 3); - // TODO(phase-d): the pid is read with fgets() from pipe 3, a PHP stream resource. The - // pipe list is a PhpMixed and cannot hold a PhpResource, so this cannot be expressed. - todo!( - "Process::start: reading the pid from pipe 3 needs a PhpResource the PhpMixed pipe list cannot carry" - ); + let pipe3 = self + .process_pipes + .as_ref() + .unwrap() + .pipes() + .get(&3) + .cloned(); + let pid = pipe3 + .and_then(|p| php::fgets(&p, None)) + .map(|s| s.trim().parse::<i64>().unwrap_or(0)) + .unwrap_or(0); + self.fallback_status + .insert("pid".to_string(), PhpMixed::Int(pid)); } if self.tty { @@ -1121,8 +1116,8 @@ impl Process { static IS_TTY_SUPPORTED: OnceLock<bool> = OnceLock::new(); *IS_TTY_SUPPORTED.get_or_init(|| { - let mut pipes = PhpMixed::Null; - php::php_truthy(&php::proc_open( + let mut pipes = IndexMap::new(); + php::proc_open( "echo 1 >/dev/null", &[ descriptor(&["file", "/dev/tty", "r"]), @@ -1133,7 +1128,8 @@ impl Process { None, None, None, - )) + ) + .is_ok() }) } @@ -1146,8 +1142,8 @@ impl Process { return false; } - let mut pipes = PhpMixed::Null; - php::php_truthy(&php::proc_open( + let mut pipes = IndexMap::new(); + php::proc_open( "echo 1 >/dev/null", &[ descriptor(&["pty"]), @@ -1158,12 +1154,13 @@ impl Process { None, None, None, - )) + ) + .is_ok() }) } /// Creates the descriptors needed by the proc_open. - fn get_descriptors(&mut self) -> Vec<PhpMixed> { + fn get_descriptors(&mut self) -> Vec<Descriptor> { // TODO(plugin): $this->input instanceof \Iterator -> rewind() is not modeled. if php::DIRECTORY_SEPARATOR == "\\" { self.process_pipes = Some(Box::new(WindowsPipes::new( @@ -1220,7 +1217,7 @@ impl Process { return; } - self.process_information = Some(php::proc_get_status(&self.process)); + self.process_information = Some(php::proc_get_status(self.process.as_ref().unwrap())); let running = self .process_information .as_ref() @@ -1358,9 +1355,9 @@ impl Process { if let Some(p) = self.process_pipes.as_mut() { p.close(); } - if php::php_truthy(&self.process) { - php::proc_close(self.process.clone()); - self.process = PhpMixed::Null; + if self.process.is_some() { + php::proc_close(self.process.as_ref().unwrap()); + self.process = None; } self.exitcode = self .process_information @@ -1411,7 +1408,7 @@ impl Process { Some(php::fopen(&format!("php://temp/maxmemory:{}", 1024 * 1024), "w+").unwrap()); self.stderr = Some(php::fopen(&format!("php://temp/maxmemory:{}", 1024 * 1024), "w+").unwrap()); - self.process = PhpMixed::Null; + self.process = None; self.latest_signal = None; self.status = Self::STATUS_READY.to_string(); self.incremental_output_offset = 0; @@ -1456,24 +1453,27 @@ impl Process { } else { let ok; if !self.is_sigchild_enabled() { - ok = php::proc_terminate(&self.process, signal); + ok = php::proc_terminate(self.process.as_ref().unwrap(), signal); } else if php::function_exists("posix_kill") { ok = php::posix_kill(pid, signal); } else { - let mut pipes = PhpMixed::Null; + let mut pipes = IndexMap::new(); let opened = php::proc_open( &format!("kill -{} {}", signal, pid), - &[PhpMixed::Null, PhpMixed::Null, descriptor(&["pipe", "w"])], + &[ + Descriptor::Inherit, + Descriptor::Inherit, + descriptor(&["pipe", "w"]), + ], &mut pipes, None, None, None, ); - let _pipe2 = php_pipe(&pipes, 2); - // TODO(phase-d): the original also requires `fgets($pipes[2]) === false`, reading - // from a PHP stream resource the PhpMixed pipe list cannot hold; that read is - // dropped here. - ok = php::php_truthy(&opened); + ok = match opened { + Ok(_) => pipes.get(&2).and_then(|p| php::fgets(p, None)).is_none(), + Err(_) => false, + }; } if !ok { if throw_exception { 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 |
