提交 046062d3 编写于 作者: A Aaron Turon

Process::new etc should support non-utf8 commands/args

The existing APIs for spawning processes took strings for the command
and arguments, but the underlying system may not impose utf8 encoding,
so this is overly limiting.

The assumption we actually want to make is just that the command and
arguments are viewable as [u8] slices with no interior NULLs, i.e., as
CStrings. The ToCStr trait is a handy bound for types that meet this
requirement (such as &str and Path).

However, since the commands and arguments are often a mixture of
strings and paths, it would be inconvenient to take a slice with a
single T: ToCStr bound. So this patch revamps the process creation API
to instead use a builder-style interface, called `Command`, allowing
arguments to be added one at a time with differing ToCStr
implementations for each.

The initial cut of the builder API has some drawbacks that can be
addressed once issue #13851 (libstd as a facade) is closed. These are
detailed as FIXMEs.

Closes #11650.

[breaking-change]
上级 8f9cbe08
......@@ -10,7 +10,7 @@
use std::os;
use std::str;
use std::io::process::{ProcessExit, Process, ProcessConfig, ProcessOutput};
use std::io::process::{ProcessExit, Command, Process, ProcessOutput};
#[cfg(target_os = "win32")]
fn target_env(lib_path: &str, prog: &str) -> Vec<(~str, ~str)> {
......@@ -68,14 +68,7 @@ pub fn run(lib_path: &str,
input: Option<~str>) -> Option<Result> {
let env = env.clone().append(target_env(lib_path, prog).as_slice());
let opt_process = Process::configure(ProcessConfig {
program: prog,
args: args,
env: Some(env.as_slice()),
.. ProcessConfig::new()
});
match opt_process {
match Command::new(prog).args(args).env(env.as_slice()).spawn() {
Ok(mut process) => {
for input in input.iter() {
process.stdin.get_mut_ref().write(input.as_bytes()).unwrap();
......@@ -100,14 +93,7 @@ pub fn run_background(lib_path: &str,
input: Option<~str>) -> Option<Process> {
let env = env.clone().append(target_env(lib_path, prog).as_slice());
let opt_process = Process::configure(ProcessConfig {
program: prog,
args: args,
env: Some(env.as_slice()),
.. ProcessConfig::new()
});
match opt_process {
match Command::new(prog).args(args).env(env.as_slice()).spawn() {
Ok(mut process) => {
for input in input.iter() {
process.stdin.get_mut_ref().write(input.as_bytes()).unwrap();
......
......@@ -420,7 +420,7 @@ fn debugger() -> ~str { "gdb".to_owned() }
}
fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) {
use std::io::process::{Process, ProcessConfig, ProcessOutput};
use std::io::process::{Command, ProcessOutput};
if config.lldb_python_dir.is_none() {
fatal("Can't run LLDB test because LLDB's python path is not set.".to_owned());
......@@ -483,25 +483,13 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
fn run_lldb(config: &Config, test_executable: &Path, debugger_script: &Path) -> ProcRes {
// Prepare the lldb_batchmode which executes the debugger script
let lldb_batchmode_script = "./src/etc/lldb_batchmode.py".to_owned();
let test_executable_str = test_executable.as_str().unwrap().to_owned();
let debugger_script_str = debugger_script.as_str().unwrap().to_owned();
let commandline = format!("python {} {} {}",
lldb_batchmode_script.as_slice(),
test_executable_str.as_slice(),
debugger_script_str.as_slice());
let args = &[lldb_batchmode_script, test_executable_str, debugger_script_str];
let env = &[("PYTHONPATH".to_owned(), config.lldb_python_dir.clone().unwrap())];
let opt_process = Process::configure(ProcessConfig {
program: "python",
args: args,
env: Some(env),
.. ProcessConfig::new()
});
let (status, out, err) = match opt_process {
let mut cmd = Command::new("python");
cmd.arg("./src/etc/lldb_batchmode.py")
.arg(test_executable)
.arg(debugger_script)
.env([("PYTHONPATH", config.lldb_python_dir.clone().unwrap().as_slice())]);
let (status, out, err) = match cmd.spawn() {
Ok(process) => {
let ProcessOutput { status, output, error } =
process.wait_with_output().unwrap();
......@@ -520,7 +508,7 @@ fn run_lldb(config: &Config, test_executable: &Path, debugger_script: &Path) ->
status: status,
stdout: out,
stderr: err,
cmdline: commandline
cmdline: format!("{}", cmd)
};
}
}
......
......@@ -27,13 +27,12 @@
use std::io;
use std::io::IoError;
use std::io::net::ip::SocketAddr;
use std::io::process::ProcessConfig;
use std::io::signal::Signum;
use std::os;
use std::rt::rtio;
use std::rt::rtio::{RtioTcpStream, RtioTcpListener, RtioUdpSocket};
use std::rt::rtio::{RtioUnixListener, RtioPipe, RtioFileStream, RtioProcess};
use std::rt::rtio::{RtioSignal, RtioTTY, CloseBehavior, RtioTimer};
use std::rt::rtio::{RtioSignal, RtioTTY, CloseBehavior, RtioTimer, ProcessConfig};
use ai = std::io::net::addrinfo;
// Local re-exports
......@@ -258,10 +257,10 @@ fn fs_utime(&mut self, src: &CString, atime: u64,
fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>> {
timer::Timer::new().map(|t| box t as Box<RtioTimer:Send>)
}
fn spawn(&mut self, config: ProcessConfig)
fn spawn(&mut self, cfg: ProcessConfig)
-> IoResult<(Box<RtioProcess:Send>,
Vec<Option<Box<RtioPipe:Send>>>)> {
process::Process::spawn(config).map(|(p, io)| {
process::Process::spawn(cfg).map(|(p, io)| {
(box p as Box<RtioProcess:Send>,
io.move_iter().map(|p| p.map(|p| {
box p as Box<RtioPipe:Send>
......
......@@ -15,9 +15,10 @@
use std::os;
use std::ptr;
use std::rt::rtio;
use std::rt::rtio::ProcessConfig;
use std::c_str::CString;
use p = std::io::process;
use super::IoResult;
use super::file;
use super::util;
......@@ -65,27 +66,11 @@ impl Process {
/// Creates a new process using native process-spawning abilities provided
/// by the OS. Operations on this process will be blocking instead of using
/// the runtime for sleeping just this current task.
///
/// # Arguments
///
/// * prog - the program to run
/// * args - the arguments to pass to the program, not including the program
/// itself
/// * env - an optional environment to specify for the child process. If
/// this value is `None`, then the child will inherit the parent's
/// environment
/// * cwd - an optionally specified current working directory of the child,
/// defaulting to the parent's current working directory
/// * stdin, stdout, stderr - These optionally specified file descriptors
/// dictate where the stdin/out/err of the child process will go. If
/// these are `None`, then this module will bind the input/output to an
/// os pipe instead. This process takes ownership of these file
/// descriptors, closing them upon destruction of the process.
pub fn spawn(config: p::ProcessConfig)
pub fn spawn(cfg: ProcessConfig)
-> Result<(Process, Vec<Option<file::FileDesc>>), io::IoError>
{
// right now we only handle stdin/stdout/stderr.
if config.extra_io.len() > 0 {
if cfg.extra_io.len() > 0 {
return Err(super::unimpl());
}
......@@ -109,14 +94,11 @@ fn get_io(io: p::StdioContainer, ret: &mut Vec<Option<file::FileDesc>>)
}
let mut ret_io = Vec::new();
let (in_pipe, in_fd) = get_io(config.stdin, &mut ret_io);
let (out_pipe, out_fd) = get_io(config.stdout, &mut ret_io);
let (err_pipe, err_fd) = get_io(config.stderr, &mut ret_io);
let (in_pipe, in_fd) = get_io(cfg.stdin, &mut ret_io);
let (out_pipe, out_fd) = get_io(cfg.stdout, &mut ret_io);
let (err_pipe, err_fd) = get_io(cfg.stderr, &mut ret_io);
let env = config.env.map(|a| a.to_owned());
let cwd = config.cwd.map(|a| Path::new(a));
let res = spawn_process_os(config, env, cwd.as_ref(), in_fd, out_fd,
err_fd);
let res = spawn_process_os(cfg, in_fd, out_fd, err_fd);
unsafe {
for pipe in in_pipe.iter() { let _ = libc::close(pipe.input); }
......@@ -262,11 +244,8 @@ struct SpawnProcessResult {
}
#[cfg(windows)]
fn spawn_process_os(config: p::ProcessConfig,
env: Option<~[(~str, ~str)]>,
dir: Option<&Path>,
in_fd: c_int, out_fd: c_int,
err_fd: c_int) -> IoResult<SpawnProcessResult> {
fn spawn_process_os(cfg: ProcessConfig, in_fd: c_int, out_fd: c_int, err_fd: c_int)
-> IoResult<SpawnProcessResult> {
use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
use libc::consts::os::extra::{
TRUE, FALSE,
......@@ -284,7 +263,7 @@ fn spawn_process_os(config: p::ProcessConfig,
use std::mem;
if config.gid.is_some() || config.uid.is_some() {
if cfg.gid.is_some() || cfg.uid.is_some() {
return Err(io::IoError {
kind: io::OtherIoError,
desc: "unsupported gid/uid requested on windows",
......@@ -293,7 +272,6 @@ fn spawn_process_os(config: p::ProcessConfig,
}
unsafe {
let mut si = zeroed_startupinfo();
si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
si.dwFlags = STARTF_USESTDHANDLES;
......@@ -333,23 +311,26 @@ fn spawn_process_os(config: p::ProcessConfig,
}
}
let cmd = make_command_line(config.program, config.args);
let cmd_str = make_command_line(cfg.program, cfg.args);
let mut pi = zeroed_process_information();
let mut create_err = None;
// stolen from the libuv code.
let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
if config.detach {
if cfg.detach {
flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
}
with_envp(env, |envp| {
with_dirp(dir, |dirp| {
os::win32::as_mut_utf16_p(cmd, |cmdp| {
let created = CreateProcessW(ptr::null(), cmdp,
ptr::mut_null(), ptr::mut_null(), TRUE,
flags, envp, dirp, &mut si,
&mut pi);
with_envp(cfg.env, |envp| {
with_dirp(cfg.cwd, |dirp| {
os::win32::as_mut_utf16_p(cmd_str, |cmdp| {
let created = CreateProcessW(ptr::null(),
cmdp,
ptr::mut_null(),
ptr::mut_null(),
TRUE,
flags, envp, dirp,
&mut si, &mut pi);
if created == FALSE {
create_err = Some(super::last_error());
}
......@@ -415,12 +396,14 @@ fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMA
}
#[cfg(windows)]
fn make_command_line(prog: &str, args: &[~str]) -> ~str {
fn make_command_line(prog: &CString, args: &[CString]) -> ~str {
let mut cmd = StrBuf::new();
append_arg(&mut cmd, prog);
append_arg(&mut cmd, prog.as_str()
.expect("expected program name to be utf-8 encoded"));
for arg in args.iter() {
cmd.push_char(' ');
append_arg(&mut cmd, *arg);
append_arg(&mut cmd, arg.as_str()
.expect("expected argument to be utf-8 encoded"));
}
return cmd.into_owned();
......@@ -468,11 +451,9 @@ fn backslash_run_ends_in_quote(s: &Vec<char>, mut i: uint) -> bool {
}
#[cfg(unix)]
fn spawn_process_os(config: p::ProcessConfig,
env: Option<~[(~str, ~str)]>,
dir: Option<&Path>,
in_fd: c_int, out_fd: c_int,
err_fd: c_int) -> IoResult<SpawnProcessResult> {
fn spawn_process_os(cfg: ProcessConfig, in_fd: c_int, out_fd: c_int, err_fd: c_int)
-> IoResult<SpawnProcessResult>
{
use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
use libc::funcs::bsd44::getdtablesize;
use io::c;
......@@ -500,11 +481,10 @@ unsafe fn set_cloexec(fd: c_int) {
assert_eq!(ret, 0);
}
let dirp = dir.map(|p| p.to_c_str());
let dirp = dirp.as_ref().map(|c| c.with_ref(|p| p)).unwrap_or(ptr::null());
let dirp = cfg.cwd.map(|c| c.with_ref(|p| p)).unwrap_or(ptr::null());
with_envp(env, proc(envp) {
with_argv(config.program, config.args, proc(argv) unsafe {
with_envp(cfg.env, proc(envp) {
with_argv(cfg.program, cfg.args, proc(argv) unsafe {
let pipe = os::pipe();
let mut input = file::FileDesc::new(pipe.input, true);
let mut output = file::FileDesc::new(pipe.out, true);
......@@ -605,7 +585,7 @@ fn fail(output: &mut file::FileDesc) -> ! {
}
}
match config.gid {
match cfg.gid {
Some(u) => {
if libc::setgid(u as libc::gid_t) != 0 {
fail(&mut output);
......@@ -613,7 +593,7 @@ fn fail(output: &mut file::FileDesc) -> ! {
}
None => {}
}
match config.uid {
match cfg.uid {
Some(u) => {
// When dropping privileges from root, the `setgroups` call will
// remove any extraneous groups. If we don't call this, then
......@@ -633,7 +613,7 @@ fn setgroups(ngroups: libc::c_int,
}
None => {}
}
if config.detach {
if cfg.detach {
// Don't check the error of setsid because it fails if we're the
// process leader already. We just forked so it shouldn't return
// error, but ignore it anyway.
......@@ -652,47 +632,47 @@ fn setgroups(ngroups: libc::c_int,
}
#[cfg(unix)]
fn with_argv<T>(prog: &str, args: &[~str], cb: proc(**libc::c_char) -> T) -> T {
// We can't directly convert `str`s into `*char`s, as someone needs to hold
// a reference to the intermediary byte buffers. So first build an array to
// hold all the ~[u8] byte strings.
let mut tmps = Vec::with_capacity(args.len() + 1);
tmps.push(prog.to_c_str());
for arg in args.iter() {
tmps.push(arg.to_c_str());
}
// Next, convert each of the byte strings into a pointer. This is
// technically unsafe as the caller could leak these pointers out of our
// scope.
let mut ptrs: Vec<_> = tmps.iter().map(|tmp| tmp.with_ref(|buf| buf)).collect();
// Finally, make sure we add a null pointer.
fn with_argv<T>(prog: &CString, args: &[CString], cb: proc(**libc::c_char) -> T) -> T {
let mut ptrs: Vec<*libc::c_char> = Vec::with_capacity(args.len()+1);
// Convert the CStrings into an array of pointers. Note: the
// lifetime of the various CStrings involved is guaranteed to be
// larger than the lifetime of our invocation of cb, but this is
// technically unsafe as the callback could leak these pointers
// out of our scope.
ptrs.push(prog.with_ref(|buf| buf));
ptrs.extend(args.iter().map(|tmp| tmp.with_ref(|buf| buf)));
// Add a terminating null pointer (required by libc).
ptrs.push(ptr::null());
cb(ptrs.as_ptr())
}
#[cfg(unix)]
fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: proc(*c_void) -> T) -> T {
fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: proc(*c_void) -> T) -> T {
// On posixy systems we can pass a char** for envp, which is a
// null-terminated array of "k=v\n" strings. Like `with_argv`, we have to
// have a temporary buffer to hold the intermediary `~[u8]` byte strings.
// null-terminated array of "k=v\0" strings. Since we must create
// these strings locally, yet expose a raw pointer to them, we
// create a temporary vector to own the CStrings that outlives the
// call to cb.
match env {
Some(env) => {
let mut tmps = Vec::with_capacity(env.len());
for pair in env.iter() {
let kv = format!("{}={}", *pair.ref0(), *pair.ref1());
tmps.push(kv.to_c_str());
let mut kv = Vec::new();
kv.push_all(pair.ref0().as_bytes_no_nul());
kv.push('=' as u8);
kv.push_all(pair.ref1().as_bytes()); // includes terminal \0
tmps.push(kv);
}
// Once again, this is unsafe.
let mut ptrs: Vec<*libc::c_char> = tmps.iter()
.map(|tmp| tmp.with_ref(|buf| buf))
.collect();
// As with `with_argv`, this is unsafe, since cb could leak the pointers.
let mut ptrs: Vec<*libc::c_char> =
tmps.iter()
.map(|tmp| tmp.as_ptr() as *libc::c_char)
.collect();
ptrs.push(ptr::null());
cb(ptrs.as_ptr() as *c_void)
......@@ -702,7 +682,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: proc(*c_void) -> T) -> T {
}
#[cfg(windows)]
fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: |*mut c_void| -> T) -> T {
// On win32 we pass an "environment block" which is not a char**, but
// rather a concatenation of null-terminated k=v\0 sequences, with a final
// \0 to terminate.
......@@ -711,7 +691,9 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
let mut blk = Vec::new();
for pair in env.iter() {
let kv = format!("{}={}", *pair.ref0(), *pair.ref1());
let kv = format!("{}={}",
pair.ref0().as_str().unwrap(),
pair.ref1().as_str().unwrap());
blk.push_all(kv.to_utf16().as_slice());
blk.push(0);
}
......@@ -725,11 +707,12 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
}
#[cfg(windows)]
fn with_dirp<T>(d: Option<&Path>, cb: |*u16| -> T) -> T {
fn with_dirp<T>(d: Option<&CString>, cb: |*u16| -> T) -> T {
match d {
Some(dir) => match dir.as_str() {
Some(dir_str) => os::win32::as_utf16_p(dir_str, cb),
None => cb(ptr::null())
Some(dir) => {
let dir_str = dir.as_str()
.expect("expected workingdirectory to be utf-8 encoded");
os::win32::as_utf16_p(dir_str, cb)
},
None => cb(ptr::null())
}
......@@ -1106,25 +1089,37 @@ mod tests {
#[test] #[cfg(windows)]
fn test_make_command_line() {
use std::str;
use std::c_str::CString;
use super::make_command_line;
fn test_wrapper(prog: &str, args: &[&str]) -> ~str {
make_command_line(&prog.to_c_str(),
args.iter()
.map(|a| a.to_c_str())
.collect::<Vec<CString>>()
.as_slice())
}
assert_eq!(
make_command_line("prog", ["aaa".to_owned(), "bbb".to_owned(), "ccc".to_owned()]),
test_wrapper("prog", ["aaa", "bbb", "ccc"]),
"prog aaa bbb ccc".to_owned()
);
assert_eq!(
make_command_line("C:\\Program Files\\blah\\blah.exe", ["aaa".to_owned()]),
test_wrapper("C:\\Program Files\\blah\\blah.exe", ["aaa"]),
"\"C:\\Program Files\\blah\\blah.exe\" aaa".to_owned()
);
assert_eq!(
make_command_line("C:\\Program Files\\test", ["aa\"bb".to_owned()]),
test_wrapper("C:\\Program Files\\test", ["aa\"bb"]),
"\"C:\\Program Files\\test\" aa\\\"bb".to_owned()
);
assert_eq!(
make_command_line("echo", ["a b c".to_owned()]),
test_wrapper("echo", ["a b c"]),
"echo \"a b c\"".to_owned()
);
assert_eq!(
make_command_line("\u03c0\u042f\u97f3\u00e6\u221e", []),
test_wrapper("\u03c0\u042f\u97f3\u00e6\u221e", []),
"\u03c0\u042f\u97f3\u00e6\u221e".to_owned()
);
}
......
......@@ -16,7 +16,7 @@
use lib::llvm::{ArchiveRef, llvm};
use libc;
use std::io::process::{ProcessConfig, Process, ProcessOutput};
use std::io::process::{Command, ProcessOutput};
use std::io::{fs, TempDir};
use std::io;
use std::mem;
......@@ -39,26 +39,24 @@ pub struct ArchiveRO {
fn run_ar(sess: &Session, args: &str, cwd: Option<&Path>,
paths: &[&Path]) -> ProcessOutput {
let ar = get_ar_prog(sess);
let mut cmd = Command::new(ar.as_slice());
cmd.arg(args).args(paths);
debug!("{}", cmd);
let mut args = vec!(args.to_owned());
let paths = paths.iter().map(|p| p.as_str().unwrap().to_owned());
args.extend(paths);
debug!("{} {}", ar, args.connect(" "));
match cwd {
Some(p) => { debug!("inside {}", p.display()); }
Some(p) => {
cmd.cwd(p);
debug!("inside {}", p.display());
}
None => {}
}
match Process::configure(ProcessConfig {
program: ar.as_slice(),
args: args.as_slice(),
cwd: cwd.map(|a| &*a),
.. ProcessConfig::new()
}) {
match cmd.spawn() {
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if !o.status.success() {
sess.err(format!("{} {} failed with: {}", ar, args.connect(" "),
o.status));
sess.err(format!("{} failed with: {}", cmd, o.status));
sess.note(format!("stdout ---\n{}",
str::from_utf8(o.output.as_slice()).unwrap()));
sess.note(format!("stderr ---\n{}",
......@@ -68,7 +66,7 @@ fn run_ar(sess: &Session, args: &str, cwd: Option<&Path>,
o
},
Err(e) => {
sess.err(format!("could not exec `{}`: {}", ar, e));
sess.err(format!("could not exec `{}`: {}", ar.as_slice(), e));
sess.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
......
此差异已折叠。
......@@ -11,7 +11,7 @@
use std::cell::RefCell;
use std::char;
use std::io;
use std::io::{Process, TempDir};
use std::io::{Command, TempDir};
use std::os;
use std::str;
use std::strbuf::StrBuf;
......@@ -155,9 +155,7 @@ fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
if no_run { return }
// Run the code!
let exe = outdir.path().join("rust_out");
let out = Process::output(exe.as_str().unwrap(), []);
match out {
match Command::new(outdir.path().join("rust_out")).output() {
Err(e) => fail!("couldn't run the test: {}{}", e,
if e.kind == io::PermissionDenied {
" - maybe your tempdir is mounted with noexec?"
......
......@@ -13,7 +13,8 @@
use std::io::IoError;
use std::io::process;
use std::ptr;
use std::rt::rtio::RtioProcess;
use std::c_str::CString;
use std::rt::rtio::{ProcessConfig, RtioProcess};
use std::rt::task::BlockedTask;
use homing::{HomingIO, HomeHandle};
......@@ -50,12 +51,10 @@ impl Process {
///
/// Returns either the corresponding process object or an error which
/// occurred.
pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
-> Result<(Box<Process>, Vec<Option<PipeWatcher>>), UvError>
{
let cwd = config.cwd.map(|s| s.to_c_str());
let mut io = vec![config.stdin, config.stdout, config.stderr];
for slot in config.extra_io.iter() {
pub fn spawn(io_loop: &mut UvIoFactory, cfg: ProcessConfig)
-> Result<(Box<Process>, Vec<Option<PipeWatcher>>), UvError> {
let mut io = vec![cfg.stdin, cfg.stdout, cfg.stderr];
for slot in cfg.extra_io.iter() {
io.push(*slot);
}
let mut stdio = Vec::<uvll::uv_stdio_container_t>::with_capacity(io.len());
......@@ -69,16 +68,16 @@ pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
}
}
let ret = with_argv(config.program, config.args, |argv| {
with_env(config.env, |envp| {
let ret = with_argv(cfg.program, cfg.args, |argv| {
with_env(cfg.env, |envp| {
let mut flags = 0;
if config.uid.is_some() {
if cfg.uid.is_some() {
flags |= uvll::PROCESS_SETUID;
}
if config.gid.is_some() {
if cfg.gid.is_some() {
flags |= uvll::PROCESS_SETGID;
}
if config.detach {
if cfg.detach {
flags |= uvll::PROCESS_DETACHED;
}
let options = uvll::uv_process_options_t {
......@@ -86,15 +85,15 @@ pub fn spawn(io_loop: &mut UvIoFactory, config: process::ProcessConfig)
file: unsafe { *argv },
args: argv,
env: envp,
cwd: match cwd {
Some(ref cwd) => cwd.with_ref(|p| p),
cwd: match cfg.cwd {
Some(cwd) => cwd.with_ref(|p| p),
None => ptr::null(),
},
flags: flags as libc::c_uint,
stdio_count: stdio.len() as libc::c_int,
stdio: stdio.as_ptr(),
uid: config.uid.unwrap_or(0) as uvll::uv_uid_t,
gid: config.gid.unwrap_or(0) as uvll::uv_gid_t,
uid: cfg.uid.unwrap_or(0) as uvll::uv_uid_t,
gid: cfg.gid.unwrap_or(0) as uvll::uv_gid_t,
};
let handle = UvHandle::alloc(None::<Process>, uvll::UV_PROCESS);
......@@ -175,42 +174,53 @@ unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t,
}
}
/// Converts the program and arguments to the argv array expected by libuv
fn with_argv<T>(prog: &str, args: &[~str], f: |**libc::c_char| -> T) -> T {
// First, allocation space to put all the C-strings (we need to have
// ownership of them somewhere
let mut c_strs = Vec::with_capacity(args.len() + 1);
c_strs.push(prog.to_c_str());
for arg in args.iter() {
c_strs.push(arg.to_c_str());
}
/// Converts the program and arguments to the argv array expected by libuv.
fn with_argv<T>(prog: &CString, args: &[CString], cb: |**libc::c_char| -> T) -> T {
let mut ptrs: Vec<*libc::c_char> = Vec::with_capacity(args.len()+1);
// Next, create the char** array
let mut c_args = Vec::with_capacity(c_strs.len() + 1);
for s in c_strs.iter() {
c_args.push(s.with_ref(|p| p));
}
c_args.push(ptr::null());
f(c_args.as_ptr())
// Convert the CStrings into an array of pointers. Note: the
// lifetime of the various CStrings involved is guaranteed to be
// larger than the lifetime of our invocation of cb, but this is
// technically unsafe as the callback could leak these pointers
// out of our scope.
ptrs.push(prog.with_ref(|buf| buf));
ptrs.extend(args.iter().map(|tmp| tmp.with_ref(|buf| buf)));
// Add a terminating null pointer (required by libc).
ptrs.push(ptr::null());
cb(ptrs.as_ptr())
}
/// Converts the environment to the env array expected by libuv
fn with_env<T>(env: Option<&[(~str, ~str)]>, f: |**libc::c_char| -> T) -> T {
let env = match env {
Some(s) => s,
None => { return f(ptr::null()); }
};
// As with argv, create some temporary storage and then the actual array
let mut envp = Vec::with_capacity(env.len());
for &(ref key, ref value) in env.iter() {
envp.push(format!("{}={}", *key, *value).to_c_str());
}
let mut c_envp = Vec::with_capacity(envp.len() + 1);
for s in envp.iter() {
c_envp.push(s.with_ref(|p| p));
fn with_env<T>(env: Option<&[(CString, CString)]>, cb: |**libc::c_char| -> T) -> T {
// We can pass a char** for envp, which is a null-terminated array
// of "k=v\0" strings. Since we must create these strings locally,
// yet expose a raw pointer to them, we create a temporary vector
// to own the CStrings that outlives the call to cb.
match env {
Some(env) => {
let mut tmps = Vec::with_capacity(env.len());
for pair in env.iter() {
let mut kv = Vec::new();
kv.push_all(pair.ref0().as_bytes_no_nul());
kv.push('=' as u8);
kv.push_all(pair.ref1().as_bytes()); // includes terminal \0
tmps.push(kv);
}
// As with `with_argv`, this is unsafe, since cb could leak the pointers.
let mut ptrs: Vec<*libc::c_char> =
tmps.iter()
.map(|tmp| tmp.as_ptr() as *libc::c_char)
.collect();
ptrs.push(ptr::null());
cb(ptrs.as_ptr())
}
_ => cb(ptr::null())
}
c_envp.push(ptr::null());
f(c_envp.as_ptr())
}
impl HomingIO for Process {
......
......@@ -13,7 +13,6 @@
use std::c_str::CString;
use std::io::IoError;
use std::io::net::ip::SocketAddr;
use std::io::process::ProcessConfig;
use std::io::signal::Signum;
use std::io::{FileMode, FileAccess, Open, Append, Truncate, Read, Write,
ReadWrite, FileStat};
......@@ -25,7 +24,7 @@
use libc;
use std::path::Path;
use std::rt::rtio;
use std::rt::rtio::{IoFactory, EventLoop};
use std::rt::rtio::{ProcessConfig, IoFactory, EventLoop};
use ai = std::io::net::addrinfo;
#[cfg(test)] use std::unstable::run_in_bare_thread;
......@@ -270,12 +269,12 @@ fn fs_utime(&mut self, path: &CString, atime: u64, mtime: u64)
r.map_err(uv_error_to_io_error)
}
fn spawn(&mut self, config: ProcessConfig)
fn spawn(&mut self, cfg: ProcessConfig)
-> Result<(Box<rtio::RtioProcess:Send>,
Vec<Option<Box<rtio::RtioPipe:Send>>>),
IoError>
{
match Process::spawn(self, config) {
match Process::spawn(self, cfg) {
Ok((p, io)) => {
Ok((p as Box<rtio::RtioProcess:Send>,
io.move_iter().map(|i| i.map(|p| {
......
......@@ -245,7 +245,7 @@ fn file_product(p: &Path) -> IoResult<u32> {
pub use self::net::tcp::TcpStream;
pub use self::net::udp::UdpStream;
pub use self::pipe::PipeStream;
pub use self::process::{Process, ProcessConfig};
pub use self::process::{Process, Command};
pub use self::tempfile::TempDir;
pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
......
此差异已折叠。
......@@ -29,7 +29,7 @@
use io;
use io::IoResult;
use io::net::ip::{IpAddr, SocketAddr};
use io::process::{ProcessConfig, ProcessExit};
use io::process::{StdioContainer, ProcessExit};
use io::signal::Signum;
use io::{FileMode, FileAccess, FileStat, FilePermission};
use io::{SeekStyle};
......@@ -87,6 +87,61 @@ pub enum CloseBehavior {
CloseAsynchronously,
}
/// Data needed to spawn a process. Serializes the `std::io::process::Command`
/// builder.
pub struct ProcessConfig<'a> {
/// Path to the program to run.
pub program: &'a CString,
/// Arguments to pass to the program (doesn't include the program itself).
pub args: &'a [CString],
/// Optional environment to specify for the program. If this is None, then
/// it will inherit the current process's environment.
pub env: Option<&'a [(CString, CString)]>,
/// Optional working directory for the new process. If this is None, then
/// the current directory of the running process is inherited.
pub cwd: Option<&'a CString>,
/// Configuration for the child process's stdin handle (file descriptor 0).
/// This field defaults to `CreatePipe(true, false)` so the input can be
/// written to.
pub stdin: StdioContainer,
/// Configuration for the child process's stdout handle (file descriptor 1).
/// This field defaults to `CreatePipe(false, true)` so the output can be
/// collected.
pub stdout: StdioContainer,
/// Configuration for the child process's stdout handle (file descriptor 2).
/// This field defaults to `CreatePipe(false, true)` so the output can be
/// collected.
pub stderr: StdioContainer,
/// Any number of streams/file descriptors/pipes may be attached to this
/// process. This list enumerates the file descriptors and such for the
/// process to be spawned, and the file descriptors inherited will start at
/// 3 and go to the length of this array. The first three file descriptors
/// (stdin/stdout/stderr) are configured with the `stdin`, `stdout`, and
/// `stderr` fields.
pub extra_io: &'a [StdioContainer],
/// Sets the child process's user id. This translates to a `setuid` call in
/// the child process. Setting this value on windows will cause the spawn to
/// fail. Failure in the `setuid` call on unix will also cause the spawn to
/// fail.
pub uid: Option<uint>,
/// Similar to `uid`, but sets the group id of the child process. This has
/// the same semantics as the `uid` field.
pub gid: Option<uint>,
/// If true, the child process is spawned in a detached state. On unix, this
/// means that the child is the leader of a new process group.
pub detach: bool,
}
pub struct LocalIo<'a> {
factory: &'a mut IoFactory,
}
......@@ -189,7 +244,7 @@ fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) ->
// misc
fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>>;
fn spawn(&mut self, config: ProcessConfig)
fn spawn(&mut self, cfg: ProcessConfig)
-> IoResult<(Box<RtioProcess:Send>,
Vec<Option<Box<RtioPipe:Send>>>)>;
fn kill(&mut self, pid: libc::pid_t, signal: int) -> IoResult<()>;
......
......@@ -221,8 +221,6 @@ pub enum RTLD {
pub mod dl {
use libc;
use os;
use path::GenericPath;
use path;
use ptr;
use result::{Ok, Err, Result};
......
......@@ -488,7 +488,7 @@ pub fn unwrap(self) -> T {
#[cfg(not(target_os="android"))] // FIXME(#10455)
fn test() {
use std::os;
use std::io::{fs, Process};
use std::io::{fs, Command};
use std::str::from_utf8;
// Create a path to a new file 'filename' in the directory in which
......@@ -522,10 +522,7 @@ fn make_path(filename: StrBuf) -> Path {
prep.exec(proc(_exe) {
let out = make_path("foo.o".to_strbuf());
let compiler = if cfg!(windows) {"gcc"} else {"cc"};
// FIXME (#9639): This needs to handle non-utf8 paths
Process::status(compiler, [pth.as_str().unwrap().to_owned(),
"-o".to_owned(),
out.as_str().unwrap().to_owned()]).unwrap();
Command::new(compiler).arg(pth).arg("-o").arg(out.clone()).status().unwrap();
let _proof_of_concept = subcx.prep("subfn");
// Could run sub-rules inside here.
......
......@@ -27,7 +27,8 @@ fn bar() { }
fn baz() { }
pub fn test() {
let lib = DynamicLibrary::open(None).unwrap();
let none: Option<Path> = None; // appease the typechecker
let lib = DynamicLibrary::open(none).unwrap();
unsafe {
assert!(lib.symbol::<int>("foo").is_ok());
assert!(lib.symbol::<int>("baz").is_err());
......
......@@ -12,7 +12,7 @@
use rand::{task_rng, Rng};
use std::{char, os, str};
use std::io::{File, Process};
use std::io::{File, Command};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an indentifier
......@@ -40,7 +40,6 @@ fn main() {
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.write_str("mod unicode_input_multiple_files_chars;");
......@@ -57,7 +56,9 @@ fn main() {
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let result = Command::new("sh")
.arg("-c").arg(rustc + " " + main_file.as_str().unwrap())
.output().unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the
......
......@@ -12,7 +12,7 @@
use rand::{task_rng, Rng};
use std::{char, os, str};
use std::io::{File, Process};
use std::io::{File, Command};
// creates a file with `fn main() { <random ident> }` and checks the
// compiler emits a span of the appropriate length (for the
......@@ -37,9 +37,7 @@ fn main() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("span_main.rs");
let main_file_str = main_file.as_str().unwrap();
for _ in range(0, 100) {
let n = task_rng().gen_range(3u, 20);
......@@ -53,7 +51,9 @@ fn main() {
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let result = Command::new("sh")
.arg("-c").arg(rustc + " " + main_file.as_str().unwrap())
.output().unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
......
......@@ -14,7 +14,7 @@
extern crate native;
use std::os;
use std::io::process::{Process, ProcessConfig};
use std::io::process::Command;
use std::unstable::finally::Finally;
use std::str;
......@@ -48,15 +48,7 @@ fn runtest(me: &str) {
env.push(("RUST_BACKTRACE".to_strbuf(), "1".to_strbuf()));
// Make sure that the stack trace is printed
let env = env.iter()
.map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
.collect::<Vec<_>>();
let mut p = Process::configure(ProcessConfig {
program: me,
args: ["fail".to_owned()],
env: Some(env.as_slice()),
.. ProcessConfig::new()
}).unwrap();
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -64,11 +56,7 @@ fn runtest(me: &str) {
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Process::configure(ProcessConfig {
program: me,
args: ["fail".to_owned()],
.. ProcessConfig::new()
}).unwrap();
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -76,11 +64,7 @@ fn runtest(me: &str) {
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Process::configure(ProcessConfig {
program: me,
args: ["double-fail".to_owned()],
.. ProcessConfig::new()
}).unwrap();
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......@@ -88,12 +72,7 @@ fn runtest(me: &str) {
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Process::configure(ProcessConfig {
program: me,
args: ["double-fail".to_owned()],
env: Some(env.as_slice()),
.. ProcessConfig::new()
}).unwrap();
let mut p = Command::new(me).arg("double-fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
......
......@@ -22,7 +22,7 @@
extern crate green;
extern crate rustuv;
use std::io::Process;
use std::io::{Process, Command};
macro_rules! succeed( ($e:expr) => (
match $e { Ok(..) => {}, Err(e) => fail!("failure: {}", e) }
......@@ -36,7 +36,7 @@ mod $name {
use std::io::timer;
use libc;
use std::str;
use std::io::process::{Process, ProcessOutput};
use std::io::process::Command;
use native;
use super::*;
......@@ -68,14 +68,14 @@ fn start(argc: int, argv: **u8) -> int {
#[cfg(unix)]
pub fn sleeper() -> Process {
Process::new("sleep", ["1000".to_owned()]).unwrap()
Command::new("sleep").arg("1000").spawn().unwrap()
}
#[cfg(windows)]
pub fn sleeper() -> Process {
// There's a `timeout` command on windows, but it doesn't like having
// its output piped, so instead just ping ourselves a few times with
// gaps inbetweeen so we're sure this process is alive for awhile
Process::new("ping", ["127.0.0.1".to_owned(), "-n".to_owned(), "1000".to_owned()]).unwrap()
Command::new("ping").arg("127.0.0.1").arg("-n").arg("1000").spawn().unwrap()
}
iotest!(fn test_destroy_twice() {
......@@ -85,7 +85,7 @@ pub fn sleeper() -> Process {
})
pub fn test_destroy_actually_kills(force: bool) {
use std::io::process::{Process, ProcessOutput, ExitStatus, ExitSignal};
use std::io::process::{Command, ProcessOutput, ExitStatus, ExitSignal};
use std::io::timer;
use libc;
use std::str;
......@@ -100,7 +100,7 @@ pub fn test_destroy_actually_kills(force: bool) {
static BLOCK_COMMAND: &'static str = "cmd";
// this process will stay alive indefinitely trying to read from stdin
let mut p = Process::new(BLOCK_COMMAND, []).unwrap();
let mut p = Command::new(BLOCK_COMMAND).spawn().unwrap();
assert!(p.signal(0).is_ok());
......
......@@ -18,7 +18,7 @@
pub fn main () {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1] == "child".to_owned() {
if args.len() > 1 && args[1].as_slice() == "child" {
for _ in range(0, 1000) {
println!("hello?");
}
......@@ -28,14 +28,7 @@ pub fn main () {
return;
}
let config = process::ProcessConfig {
program : args[0].as_slice(),
args : &["child".to_owned()],
stdout: process::Ignored,
stderr: process::Ignored,
.. process::ProcessConfig::new()
};
let mut p = process::Process::configure(config).unwrap();
println!("{}", p.wait());
let mut p = process::Command::new(args[0].as_slice());
p.arg("child").stdout(process::Ignored).stderr(process::Ignored);
println!("{}", p.spawn().unwrap().wait());
}
......@@ -50,10 +50,8 @@ fn main() {
fn parent(flavor: StrBuf) {
let args = os::args();
let args = args.as_slice();
let mut p = io::Process::new(args[0].as_slice(), [
"child".to_owned(),
flavor.to_owned()
]).unwrap();
let mut p = io::process::Command::new(args[0].as_slice())
.arg("child").arg(flavor).spawn().unwrap();
p.stdin.get_mut_ref().write_str("test1\ntest2\ntest3").unwrap();
let out = p.wait_with_output().unwrap();
assert!(out.status.success());
......
......@@ -16,7 +16,7 @@
#[phase(syntax, link)]
extern crate log;
use std::io::{Process, ProcessConfig};
use std::io::Command;
use std::os;
use std::str;
......@@ -30,16 +30,11 @@ fn main() {
}
let env = [("RUST_LOG".to_owned(), "debug".to_owned())];
let config = ProcessConfig {
program: args[0].as_slice(),
args: &["child".to_owned()],
env: Some(env.as_slice()),
..ProcessConfig::new()
};
let p = Process::configure(config).unwrap().wait_with_output().unwrap();
let p = Command::new(args[0].as_slice())
.arg("child").env(env.as_slice())
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(lines.next().unwrap().contains("bar"));
}
......@@ -10,7 +10,7 @@
#![feature(asm)]
use std::io::Process;
use std::io::process::Command;
use std::os;
use std::str;
......@@ -40,12 +40,12 @@ fn main() {
} else if args.len() > 1 && args[1].as_slice() == "loud" {
loud_recurse();
} else {
let silent = Process::output(args[0], ["silent".to_owned()]).unwrap();
let silent = Command::new(args[0].as_slice()).arg("silent").output().unwrap();
assert!(!silent.status.success());
let error = str::from_utf8_lossy(silent.error.as_slice());
assert!(error.as_slice().contains("has overflowed its stack"));
let loud = Process::output(args[0], ["loud".to_owned()]).unwrap();
let loud = Command::new(args[0].as_slice()).arg("loud").output().unwrap();
assert!(!loud.status.success());
let error = str::from_utf8_lossy(silent.error.as_slice());
assert!(error.as_slice().contains("has overflowed its stack"));
......
......@@ -24,6 +24,7 @@
extern crate libc;
use std::io::process;
use std::io::process::Command;
use std::io::signal::{Listener, Interrupt};
#[start]
......@@ -34,19 +35,12 @@ fn start(argc: int, argv: **u8) -> int {
fn main() {
unsafe { libc::setsid(); }
let config = process::ProcessConfig {
program : "/bin/sh",
args: &["-c".to_owned(), "read a".to_owned()],
detach: true,
.. process::ProcessConfig::new()
};
// we shouldn't die because of an interrupt
let mut l = Listener::new();
l.register(Interrupt).unwrap();
// spawn the child
let mut p = process::Process::configure(config).unwrap();
let mut p = Command::new("/bin/sh").arg("-c").arg("read a").detached().spawn().unwrap();
// send an interrupt to everyone in our process group
unsafe { libc::funcs::posix88::signal::kill(0, libc::SIGINT); }
......@@ -59,4 +53,3 @@ fn main() {
process::ExitSignal(..) => fail!()
}
}
......@@ -20,8 +20,7 @@
use std::io;
use std::io::fs;
use std::io::process::Process;
use std::io::process::ProcessConfig;
use std::io::Command;
use std::os;
use std::path::Path;
......@@ -56,13 +55,11 @@ fn main() {
assert!(fs::copy(&my_path, &child_path).is_ok());
// run child
let p = Process::configure(ProcessConfig {
program: child_path.as_str().unwrap(),
args: [arg.to_owned()],
cwd: Some(&cwd),
env: Some(my_env.append_one(env).as_slice()),
.. ProcessConfig::new()
}).unwrap().wait_with_output().unwrap();
let p = Command::new(&child_path)
.arg(arg)
.cwd(&cwd)
.env(my_env.append_one(env).as_slice())
.spawn().unwrap().wait_with_output().unwrap();
// display the output
assert!(io::stdout().write(p.output.as_slice()).is_ok());
......
......@@ -21,7 +21,7 @@
// ignore-win32
use std::os;
use std::io::process::{Process, ExitSignal, ExitStatus};
use std::io::process::{Command, ExitSignal, ExitStatus};
pub fn main() {
let args = os::args();
......@@ -30,7 +30,7 @@ pub fn main() {
// Raise a segfault.
unsafe { *(0 as *mut int) = 0; }
} else {
let status = Process::status(args[0], ["signal".to_owned()]).unwrap();
let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap();
// Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status {
ExitSignal(_) if cfg!(unix) => {},
......@@ -39,4 +39,3 @@ pub fn main() {
}
}
}
......@@ -12,7 +12,8 @@
// doesn't die in a ball of fire, but rather it's gracefully handled.
use std::os;
use std::io::{PipeStream, Process};
use std::io::PipeStream;
use std::io::Command;
fn test() {
let os::Pipe { input, out } = os::pipe();
......@@ -30,6 +31,7 @@ fn main() {
return test();
}
let mut p = Process::new(args[0], ["test".to_owned()]).unwrap();
let mut p = Command::new(args[0].as_slice())
.arg("test").spawn().unwrap();
assert!(p.wait().unwrap().success());
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册