1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use libc::{pid_t, c_void, c_int};
13 use std::c_str::CString;
18 use std::rt::rtio::{ProcessConfig, IoResult, IoError};
24 #[cfg(windows)] use std::string::String;
25 #[cfg(unix)] use super::c;
26 #[cfg(unix)] use super::retry;
27 #[cfg(unix)] use io::helper_thread::Helper;
30 helper_init!(static mut HELPER: Helper<Req>)
33 * A value representing a child process.
35 * The lifetime of this value is linked to the lifetime of the actual
36 * process - the Process destructor calls self.finish() which waits
37 * for the process to terminate.
40 /// The unique id of the process (this should never be negative).
43 /// A handle to the process - on unix this will always be NULL, but on
44 /// windows it will be a HANDLE to the process, which will prevent the
45 /// pid being re-used until the handle is closed.
48 /// None until finish() is called.
49 exit_code: Option<rtio::ProcessExit>,
51 /// Manually delivered signal
52 exit_signal: Option<int>,
54 /// Deadline after which wait() will return
60 NewChild(libc::pid_t, Sender<rtio::ProcessExit>, u64),
64 /// Creates a new process using native process-spawning abilities provided
65 /// by the OS. Operations on this process will be blocking instead of using
66 /// the runtime for sleeping just this current task.
67 pub fn spawn(cfg: ProcessConfig)
68 -> IoResult<(Process, Vec<Option<file::FileDesc>>)>
70 // right now we only handle stdin/stdout/stderr.
71 if cfg.extra_io.len() > 0 {
72 return Err(super::unimpl());
75 fn get_io(io: rtio::StdioContainer,
76 ret: &mut Vec<Option<file::FileDesc>>)
77 -> IoResult<Option<file::FileDesc>>
80 rtio::Ignored => { ret.push(None); Ok(None) }
81 rtio::InheritFd(fd) => {
83 Ok(Some(file::FileDesc::new(fd, true)))
85 rtio::CreatePipe(readable, _writable) => {
86 let (reader, writer) = try!(pipe());
87 let (theirs, ours) = if readable {
98 let mut ret_io = Vec::new();
99 let res = spawn_process_os(cfg,
100 try!(get_io(cfg.stdin, &mut ret_io)),
101 try!(get_io(cfg.stdout, &mut ret_io)),
102 try!(get_io(cfg.stderr, &mut ret_io)));
119 pub fn kill(pid: libc::pid_t, signum: int) -> IoResult<()> {
120 unsafe { killpid(pid, signum) }
124 impl rtio::RtioProcess for Process {
125 fn id(&self) -> pid_t { self.pid }
127 fn set_timeout(&mut self, timeout: Option<u64>) {
128 self.deadline = timeout.map(|i| i + ::io::timer::now()).unwrap_or(0);
131 fn wait(&mut self) -> IoResult<rtio::ProcessExit> {
132 match self.exit_code {
133 Some(code) => Ok(code),
135 let code = try!(waitpid(self.pid, self.deadline));
136 // On windows, waitpid will never return a signal. If a signal
137 // was successfully delivered to the process, however, we can
138 // consider it as having died via a signal.
139 let code = match self.exit_signal {
141 Some(signal) if cfg!(windows) => rtio::ExitSignal(signal),
144 self.exit_code = Some(code);
150 fn kill(&mut self, signum: int) -> IoResult<()> {
151 #[cfg(unix)] use ERROR = libc::EINVAL;
152 #[cfg(windows)] use ERROR = libc::ERROR_NOTHING_TO_TERMINATE;
154 // On linux (and possibly other unices), a process that has exited will
155 // continue to accept signals because it is "defunct". The delivery of
156 // signals will only fail once the child has been reaped. For this
157 // reason, if the process hasn't exited yet, then we attempt to collect
158 // their status with WNOHANG.
159 if self.exit_code.is_none() {
160 match waitpid_nowait(self.pid) {
161 Some(code) => { self.exit_code = Some(code); }
166 // if the process has finished, and therefore had waitpid called,
167 // and we kill it, then on unix we might ending up killing a
168 // newer process that happens to have the same (re-used) id
169 match self.exit_code {
170 Some(..) => return Err(IoError {
173 detail: Some("can't kill an exited process".to_string()),
178 // A successfully delivered signal that isn't 0 (just a poll for being
179 // alive) is recorded for windows (see wait())
180 match unsafe { killpid(self.pid, signum) } {
181 Ok(()) if signum == 0 => Ok(()),
182 Ok(()) => { self.exit_signal = Some(signum); Ok(()) }
188 impl Drop for Process {
190 free_handle(self.handle);
194 fn pipe() -> IoResult<(file::FileDesc, file::FileDesc)> {
195 #[cfg(unix)] use ERROR = libc::EMFILE;
196 #[cfg(windows)] use ERROR = libc::WSAEMFILE;
197 struct Closer { fd: libc::c_int }
199 let os::Pipe { reader, writer } = match unsafe { os::pipe() } {
201 Err(io::IoError { detail, .. }) => return Err(IoError {
207 let mut reader = Closer { fd: reader };
208 let mut writer = Closer { fd: writer };
210 let native_reader = file::FileDesc::new(reader.fd, true);
212 let native_writer = file::FileDesc::new(writer.fd, true);
214 return Ok((native_reader, native_writer));
216 impl Drop for Closer {
219 let _ = unsafe { libc::close(self.fd) };
226 unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
227 let handle = libc::OpenProcess(libc::PROCESS_TERMINATE |
228 libc::PROCESS_QUERY_INFORMATION,
229 libc::FALSE, pid as libc::DWORD);
230 if handle.is_null() {
231 return Err(super::last_error())
233 let ret = match signal {
234 // test for existence on signal 0
237 let ret = libc::GetExitCodeProcess(handle, &mut status);
239 Err(super::last_error())
240 } else if status != libc::STILL_ACTIVE {
242 code: libc::ERROR_NOTHING_TO_TERMINATE as uint,
250 15 | 9 => { // sigterm or sigkill
251 let ret = libc::TerminateProcess(handle, 1);
252 super::mkerr_winbool(ret)
255 code: libc::ERROR_CALL_NOT_IMPLEMENTED as uint,
257 detail: Some("unsupported signal on windows".to_string()),
260 let _ = libc::CloseHandle(handle);
265 unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> {
266 let r = libc::funcs::posix88::signal::kill(pid, signal as c_int);
270 struct SpawnProcessResult {
276 fn spawn_process_os(cfg: ProcessConfig,
277 in_fd: Option<file::FileDesc>,
278 out_fd: Option<file::FileDesc>,
279 err_fd: Option<file::FileDesc>)
280 -> IoResult<SpawnProcessResult> {
281 use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO};
282 use libc::consts::os::extra::{
284 STARTF_USESTDHANDLES,
285 INVALID_HANDLE_VALUE,
286 DUPLICATE_SAME_ACCESS
288 use libc::funcs::extra::kernel32::{
294 use libc::funcs::extra::msvcrt::get_osfhandle;
297 use std::iter::Iterator;
298 use std::str::StrSlice;
300 if cfg.gid.is_some() || cfg.uid.is_some() {
302 code: libc::ERROR_CALL_NOT_IMPLEMENTED as uint,
304 detail: Some("unsupported gid/uid requested on windows".to_string()),
309 let mut si = zeroed_startupinfo();
310 si.cb = mem::size_of::<STARTUPINFO>() as DWORD;
311 si.dwFlags = STARTF_USESTDHANDLES;
313 let cur_proc = GetCurrentProcess();
315 // Similarly to unix, we don't actually leave holes for the stdio file
316 // descriptors, but rather open up /dev/null equivalents. These
317 // equivalents are drawn from libuv's windows process spawning.
318 let set_fd = |fd: &Option<file::FileDesc>, slot: &mut HANDLE,
322 let access = if is_stdin {
323 libc::FILE_GENERIC_READ
325 libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES
327 let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>();
328 let mut sa = libc::SECURITY_ATTRIBUTES {
329 nLength: size as libc::DWORD,
330 lpSecurityDescriptor: ptr::mut_null(),
333 let filename: Vec<u16> = "NUL".utf16_units().collect();
334 let filename = filename.append_one(0);
335 *slot = libc::CreateFileW(filename.as_ptr(),
337 libc::FILE_SHARE_READ |
338 libc::FILE_SHARE_WRITE,
343 if *slot == INVALID_HANDLE_VALUE as libc::HANDLE {
344 return Err(super::last_error())
348 let orig = get_osfhandle(fd.fd()) as HANDLE;
349 if orig == INVALID_HANDLE_VALUE as HANDLE {
350 return Err(super::last_error())
352 if DuplicateHandle(cur_proc, orig, cur_proc, slot,
353 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE {
354 return Err(super::last_error())
361 try!(set_fd(&in_fd, &mut si.hStdInput, true));
362 try!(set_fd(&out_fd, &mut si.hStdOutput, false));
363 try!(set_fd(&err_fd, &mut si.hStdError, false));
365 let cmd_str = make_command_line(cfg.program, cfg.args);
366 let mut pi = zeroed_process_information();
367 let mut create_err = None;
369 // stolen from the libuv code.
370 let mut flags = libc::CREATE_UNICODE_ENVIRONMENT;
372 flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP;
375 with_envp(cfg.env, |envp| {
376 with_dirp(cfg.cwd, |dirp| {
377 let mut cmd_str: Vec<u16> = cmd_str.as_slice().utf16_units().collect();
378 cmd_str = cmd_str.append_one(0);
379 let created = CreateProcessW(ptr::null(),
380 cmd_str.as_mut_ptr(),
386 if created == FALSE {
387 create_err = Some(super::last_error());
392 assert!(CloseHandle(si.hStdInput) != 0);
393 assert!(CloseHandle(si.hStdOutput) != 0);
394 assert!(CloseHandle(si.hStdError) != 0);
397 Some(err) => return Err(err),
401 // We close the thread handle because we don't care about keeping the
402 // thread id valid, and we aren't keeping the thread handle around to be
403 // able to close it later. We don't close the process handle however
404 // because std::we want the process id to stay valid at least until the
405 // calling code closes the process handle.
406 assert!(CloseHandle(pi.hThread) != 0);
408 Ok(SpawnProcessResult {
409 pid: pi.dwProcessId as pid_t,
410 handle: pi.hProcess as *mut ()
416 fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO {
417 libc::types::os::arch::extra::STARTUPINFO {
419 lpReserved: ptr::mut_null(),
420 lpDesktop: ptr::mut_null(),
421 lpTitle: ptr::mut_null(),
432 lpReserved2: ptr::mut_null(),
433 hStdInput: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
434 hStdOutput: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
435 hStdError: libc::INVALID_HANDLE_VALUE as libc::HANDLE,
440 fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION {
441 libc::types::os::arch::extra::PROCESS_INFORMATION {
442 hProcess: ptr::mut_null(),
443 hThread: ptr::mut_null(),
450 fn make_command_line(prog: &CString, args: &[CString]) -> String {
451 let mut cmd = String::new();
452 append_arg(&mut cmd, prog.as_str()
453 .expect("expected program name to be utf-8 encoded"));
454 for arg in args.iter() {
456 append_arg(&mut cmd, arg.as_str()
457 .expect("expected argument to be utf-8 encoded"));
461 fn append_arg(cmd: &mut String, arg: &str) {
462 let quote = arg.chars().any(|c| c == ' ' || c == '\t');
466 let argvec: Vec<char> = arg.chars().collect();
467 for i in range(0u, argvec.len()) {
468 append_char_at(cmd, &argvec, i);
475 fn append_char_at(cmd: &mut String, arg: &Vec<char>, i: uint) {
479 cmd.push_str("\\\"");
482 if backslash_run_ends_in_quote(arg, i) {
483 // Double all backslashes that are in runs before quotes.
484 cmd.push_str("\\\\");
486 // Pass other backslashes through unescaped.
496 fn backslash_run_ends_in_quote(s: &Vec<char>, mut i: uint) -> bool {
497 while i < s.len() && *s.get(i) == '\\' {
500 return i < s.len() && *s.get(i) == '"';
505 fn spawn_process_os(cfg: ProcessConfig,
506 in_fd: Option<file::FileDesc>,
507 out_fd: Option<file::FileDesc>,
508 err_fd: Option<file::FileDesc>)
509 -> IoResult<SpawnProcessResult>
511 use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
512 use libc::funcs::bsd44::getdtablesize;
517 pub fn rust_unset_sigprocmask();
521 #[cfg(target_os = "macos")]
522 unsafe fn set_environ(envp: *const c_void) {
523 extern { fn _NSGetEnviron() -> *mut *const c_void; }
525 *_NSGetEnviron() = envp;
527 #[cfg(not(target_os = "macos"))]
528 unsafe fn set_environ(envp: *const c_void) {
529 extern { static mut environ: *const c_void; }
533 unsafe fn set_cloexec(fd: c_int) {
534 let ret = c::ioctl(fd, c::FIOCLEX);
538 let dirp = cfg.cwd.map(|c| c.as_ptr()).unwrap_or(ptr::null());
541 mem::transmute::<ProcessConfig,ProcessConfig<'static>>(cfg)
544 with_envp(cfg.env, proc(envp) {
545 with_argv(cfg.program, cfg.args, proc(argv) unsafe {
546 let (mut input, mut output) = try!(pipe());
548 // We may use this in the child, so perform allocations before the
550 let devnull = "/dev/null".to_c_str();
552 set_cloexec(output.fd());
556 return Err(super::last_error())
559 let mut bytes = [0, ..4];
560 return match input.inner_read(bytes) {
562 let errno = (bytes[0] << 24) as i32 |
563 (bytes[1] << 16) as i32 |
564 (bytes[2] << 8) as i32 |
565 (bytes[3] << 0) as i32;
573 Ok(SpawnProcessResult {
575 handle: ptr::mut_null()
578 Ok(..) => fail!("short read on the cloexec pipe"),
581 // And at this point we've reached a special time in the life of the
582 // child. The child must now be considered hamstrung and unable to
583 // do anything other than syscalls really. Consider the following
586 // 1. Thread A of process 1 grabs the malloc() mutex
587 // 2. Thread B of process 1 forks(), creating thread C
588 // 3. Thread C of process 2 then attempts to malloc()
589 // 4. The memory of process 2 is the same as the memory of
590 // process 1, so the mutex is locked.
592 // This situation looks a lot like deadlock, right? It turns out
593 // that this is what pthread_atfork() takes care of, which is
594 // presumably implemented across platforms. The first thing that
595 // threads to *before* forking is to do things like grab the malloc
596 // mutex, and then after the fork they unlock it.
598 // Despite this information, libnative's spawn has been witnessed to
599 // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but
600 // all collected backtraces point at malloc/free traffic in the
601 // child spawned process.
603 // For this reason, the block of code below should contain 0
604 // invocations of either malloc of free (or their related friends).
606 // As an example of not having malloc/free traffic, we don't close
607 // this file descriptor by dropping the FileDesc (which contains an
608 // allocation). Instead we just close it manually. This will never
609 // have the drop glue anyway because this code never returns (the
610 // child will either exec() or invoke libc::exit)
611 let _ = libc::close(input.fd());
613 fn fail(output: &mut file::FileDesc) -> ! {
614 let errno = os::errno();
621 assert!(output.inner_write(bytes).is_ok());
622 unsafe { libc::_exit(1) }
625 rustrt::rust_unset_sigprocmask();
627 // If a stdio file descriptor is set to be ignored (via a -1 file
628 // descriptor), then we don't actually close it, but rather open
629 // up /dev/null into that file descriptor. Otherwise, the first file
630 // descriptor opened up in the child would be numbered as one of the
631 // stdio file descriptors, which is likely to wreak havoc.
632 let setup = |src: Option<file::FileDesc>, dst: c_int| {
633 let src = match src {
635 let flags = if dst == libc::STDIN_FILENO {
640 libc::open(devnull.as_ptr(), flags, 0)
644 // Leak the memory and the file descriptor. We're in the
645 // child now an all our resources are going to be
646 // cleaned up very soon
651 src != -1 && retry(|| dup2(src, dst)) != -1
654 if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) }
655 if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) }
656 if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) }
658 // close all other fds
659 for fd in range(3, getdtablesize()).rev() {
660 if fd != output.fd() {
661 let _ = close(fd as c_int);
667 if libc::setgid(u as libc::gid_t) != 0 {
675 // When dropping privileges from root, the `setgroups` call
676 // will remove any extraneous groups. If we don't call this,
677 // then even though our uid has dropped, we may still have
678 // groups that enable us to do super-user things. This will
679 // fail if we aren't root, so don't bother checking the
680 // return value, this is just done as an optimistic
681 // privilege dropping function.
683 fn setgroups(ngroups: libc::c_int,
684 ptr: *const libc::c_void) -> libc::c_int;
686 let _ = setgroups(0, 0 as *const libc::c_void);
688 if libc::setuid(u as libc::uid_t) != 0 {
695 // Don't check the error of setsid because it fails if we're the
696 // process leader already. We just forked so it shouldn't return
697 // error, but ignore it anyway.
698 let _ = libc::setsid();
700 if !dirp.is_null() && chdir(dirp) == -1 {
706 let _ = execvp(*argv, argv as *mut _);
713 fn with_argv<T>(prog: &CString, args: &[CString],
714 cb: proc(*const *const libc::c_char) -> T) -> T {
715 let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1);
717 // Convert the CStrings into an array of pointers. Note: the
718 // lifetime of the various CStrings involved is guaranteed to be
719 // larger than the lifetime of our invocation of cb, but this is
720 // technically unsafe as the callback could leak these pointers
722 ptrs.push(prog.as_ptr());
723 ptrs.extend(args.iter().map(|tmp| tmp.as_ptr()));
725 // Add a terminating null pointer (required by libc).
726 ptrs.push(ptr::null());
732 fn with_envp<T>(env: Option<&[(CString, CString)]>,
733 cb: proc(*const c_void) -> T) -> T {
734 // On posixy systems we can pass a char** for envp, which is a
735 // null-terminated array of "k=v\0" strings. Since we must create
736 // these strings locally, yet expose a raw pointer to them, we
737 // create a temporary vector to own the CStrings that outlives the
741 let mut tmps = Vec::with_capacity(env.len());
743 for pair in env.iter() {
744 let mut kv = Vec::new();
745 kv.push_all(pair.ref0().as_bytes_no_nul());
747 kv.push_all(pair.ref1().as_bytes()); // includes terminal \0
751 // As with `with_argv`, this is unsafe, since cb could leak the pointers.
752 let mut ptrs: Vec<*const libc::c_char> =
754 .map(|tmp| tmp.as_ptr() as *const libc::c_char)
756 ptrs.push(ptr::null());
758 cb(ptrs.as_ptr() as *const c_void)
765 fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: |*mut c_void| -> T) -> T {
766 // On win32 we pass an "environment block" which is not a char**, but
767 // rather a concatenation of null-terminated k=v\0 sequences, with a final
771 let mut blk = Vec::new();
773 for pair in env.iter() {
774 let kv = format!("{}={}",
775 pair.ref0().as_str().unwrap(),
776 pair.ref1().as_str().unwrap());
777 blk.extend(kv.as_slice().utf16_units());
783 cb(blk.as_mut_ptr() as *mut c_void)
785 _ => cb(ptr::mut_null())
790 fn with_dirp<T>(d: Option<&CString>, cb: |*const u16| -> T) -> T {
793 let dir_str = dir.as_str()
794 .expect("expected workingdirectory to be utf-8 encoded");
795 let dir_str: Vec<u16> = dir_str.utf16_units().collect();
796 let dir_str = dir_str.append_one(0);
800 None => cb(ptr::null())
805 fn free_handle(handle: *mut ()) {
807 libc::CloseHandle(mem::transmute(handle)) != 0
812 fn free_handle(_handle: *mut ()) {
813 // unix has no process handle object, just a pid
817 fn translate_status(status: c_int) -> rtio::ProcessExit {
818 #![allow(non_snake_case_functions)]
819 #[cfg(target_os = "linux")]
820 #[cfg(target_os = "android")]
822 pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 }
823 pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff }
824 pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f }
827 #[cfg(target_os = "macos")]
828 #[cfg(target_os = "ios")]
829 #[cfg(target_os = "freebsd")]
831 pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 }
832 pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 }
833 pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 }
836 if imp::WIFEXITED(status) {
837 rtio::ExitStatus(imp::WEXITSTATUS(status) as int)
839 rtio::ExitSignal(imp::WTERMSIG(status) as int)
844 * Waits for a process to exit and returns the exit code, failing
845 * if there is no process with the specified id.
847 * Note that this is private to avoid race conditions on unix where if
848 * a user calls waitpid(some_process.get_id()) then some_process.finish()
849 * and some_process.destroy() and some_process.finalize() will then either
850 * operate on a none-existent process or, even worse, on a newer process
854 fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
855 use libc::types::os::arch::extra::DWORD;
856 use libc::consts::os::extra::{
858 PROCESS_QUERY_INFORMATION,
865 use libc::funcs::extra::kernel32::{
873 let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
876 if process.is_null() {
877 return Err(super::last_error())
882 if GetExitCodeProcess(process, &mut status) == FALSE {
883 let err = Err(super::last_error());
884 assert!(CloseHandle(process) != 0);
887 if status != STILL_ACTIVE {
888 assert!(CloseHandle(process) != 0);
889 return Ok(rtio::ExitStatus(status as int));
891 let interval = if deadline == 0 {
894 let now = ::io::timer::now();
895 if deadline < now {0} else {(deadline - now) as u32}
897 match WaitForSingleObject(process, interval) {
900 assert!(CloseHandle(process) != 0);
901 return Err(util::timeout("process wait timed out"))
904 let err = Err(super::last_error());
905 assert!(CloseHandle(process) != 0);
914 fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
918 static mut WRITE_FD: libc::c_int = 0;
920 let mut status = 0 as c_int;
922 return match retry(|| unsafe { c::waitpid(pid, &mut status, 0) }) {
923 -1 => fail!("unknown waitpid error: {}", super::last_error().code),
924 _ => Ok(translate_status(status)),
928 // On unix, wait() and its friends have no timeout parameters, so there is
929 // no way to time out a thread in wait(). From some googling and some
930 // thinking, it appears that there are a few ways to handle timeouts in
931 // wait(), but the only real reasonable one for a multi-threaded program is
932 // to listen for SIGCHLD.
934 // With this in mind, the waiting mechanism with a timeout barely uses
935 // waitpid() at all. There are a few times that waitpid() is invoked with
936 // WNOHANG, but otherwise all the necessary blocking is done by waiting for
937 // a SIGCHLD to arrive (and that blocking has a timeout). Note, however,
938 // that waitpid() is still used to actually reap the child.
940 // Signal handling is super tricky in general, and this is no exception. Due
941 // to the async nature of SIGCHLD, we use the self-pipe trick to transmit
942 // data out of the signal handler to the rest of the application. The first
943 // idea would be to have each thread waiting with a timeout to read this
944 // output file descriptor, but a write() is akin to a signal(), not a
945 // broadcast(), so it would only wake up one thread, and possibly the wrong
946 // thread. Hence a helper thread is used.
948 // The helper thread here is responsible for farming requests for a
949 // waitpid() with a timeout, and then processing all of the wait requests.
950 // By guaranteeing that only this helper thread is reading half of the
951 // self-pipe, we're sure that we'll never lose a SIGCHLD. This helper thread
952 // is also responsible for select() to wait for incoming messages or
953 // incoming SIGCHLD messages, along with passing an appropriate timeout to
954 // select() to wake things up as necessary.
956 // The ordering of the following statements is also very purposeful. First,
957 // we must be guaranteed that the helper thread is booted and available to
958 // receive SIGCHLD signals, and then we must also ensure that we do a
959 // nonblocking waitpid() at least once before we go ask the sigchld helper.
960 // This prevents the race where the child exits, we boot the helper, and
961 // then we ask for the child's exit status (never seeing a sigchld).
963 // The actual communication between the helper thread and this thread is
964 // quite simple, just a channel moving data around.
966 unsafe { HELPER.boot(register_sigchld, waitpid_helper) }
968 match waitpid_nowait(pid) {
969 Some(ret) => return Ok(ret),
973 let (tx, rx) = channel();
974 unsafe { HELPER.send(NewChild(pid, tx, deadline)); }
975 return match rx.recv_opt() {
977 Err(()) => Err(util::timeout("wait timed out")),
980 // Register a new SIGCHLD handler, returning the reading half of the
981 // self-pipe plus the old handler registered (return value of sigaction).
983 // Be sure to set up the self-pipe first because as soon as we register a
984 // handler we're going to start receiving signals.
985 fn register_sigchld() -> (libc::c_int, c::sigaction) {
987 let mut pipes = [0, ..2];
988 assert_eq!(libc::pipe(pipes.as_mut_ptr()), 0);
989 util::set_nonblocking(pipes[0], true).ok().unwrap();
990 util::set_nonblocking(pipes[1], true).ok().unwrap();
993 let mut old: c::sigaction = mem::zeroed();
994 let mut new: c::sigaction = mem::zeroed();
995 new.sa_handler = sigchld_handler;
996 new.sa_flags = c::SA_NOCLDSTOP;
997 assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0);
1002 // Helper thread for processing SIGCHLD messages
1003 fn waitpid_helper(input: libc::c_int,
1004 messages: Receiver<Req>,
1005 (read_fd, old): (libc::c_int, c::sigaction)) {
1006 util::set_nonblocking(input, true).ok().unwrap();
1007 let mut set: c::fd_set = unsafe { mem::zeroed() };
1008 let mut tv: libc::timeval;
1009 let mut active = Vec::<(libc::pid_t, Sender<rtio::ProcessExit>, u64)>::new();
1010 let max = cmp::max(input, read_fd) + 1;
1013 // Figure out the timeout of our syscall-to-happen. If we're waiting
1014 // for some processes, then they'll have a timeout, otherwise we
1015 // wait indefinitely for a message to arrive.
1017 // FIXME: sure would be nice to not have to scan the entire array
1018 let min = active.iter().map(|a| *a.ref2()).enumerate().min_by(|p| {
1021 let (p, idx) = match min {
1022 Some((idx, deadline)) => {
1023 let now = ::io::timer::now();
1024 let ms = if now < deadline {deadline - now} else {0};
1025 tv = util::ms_to_timeval(ms);
1026 (&mut tv as *mut _, idx)
1028 None => (ptr::mut_null(), -1),
1031 // Wait for something to happen
1032 c::fd_set(&mut set, input);
1033 c::fd_set(&mut set, read_fd);
1034 match unsafe { c::select(max, &mut set, ptr::mut_null(),
1035 ptr::mut_null(), p) } {
1036 // interrupted, retry
1037 -1 if os::errno() == libc::EINTR as int => continue,
1039 // We read something, break out and process
1042 // Timeout, the pending request is removed
1044 drop(active.remove(idx));
1048 n => fail!("error in select {} ({})", os::errno(), n),
1051 // Process any pending messages
1054 match messages.try_recv() {
1055 Ok(NewChild(pid, tx, deadline)) => {
1056 active.push((pid, tx, deadline));
1058 Err(comm::Disconnected) => {
1059 assert!(active.len() == 0);
1062 Err(comm::Empty) => break,
1067 // If a child exited (somehow received SIGCHLD), then poll all
1068 // children to see if any of them exited.
1070 // We also attempt to be responsible netizens when dealing with
1071 // SIGCHLD by invoking any previous SIGCHLD handler instead of just
1072 // ignoring any previous SIGCHLD handler. Note that we don't provide
1073 // a 1:1 mapping of our handler invocations to the previous handler
1074 // invocations because we drain the `read_fd` entirely. This is
1075 // probably OK because the kernel is already allowed to coalesce
1076 // simultaneous signals, we're just doing some extra coalescing.
1078 // Another point of note is that this likely runs the signal handler
1079 // on a different thread than the one that received the signal. I
1080 // *think* this is ok at this time.
1082 // The main reason for doing this is to allow stdtest to run native
1083 // tests as well. Both libgreen and libnative are running around
1084 // with process timeouts, but libgreen should get there first
1085 // (currently libuv doesn't handle old signal handlers).
1087 let i: uint = unsafe { mem::transmute(old.sa_handler) };
1089 assert!(old.sa_flags & c::SA_SIGINFO == 0);
1090 (old.sa_handler)(c::SIGCHLD);
1093 // FIXME: sure would be nice to not have to scan the entire
1095 active.retain(|&(pid, ref tx, _)| {
1096 match waitpid_nowait(pid) {
1097 Some(msg) => { tx.send(msg); false }
1104 // Once this helper thread is done, we re-register the old sigchld
1105 // handler and close our intermediate file descriptors.
1107 assert_eq!(c::sigaction(c::SIGCHLD, &old, ptr::mut_null()), 0);
1108 let _ = libc::close(read_fd);
1109 let _ = libc::close(WRITE_FD);
1114 // Drain all pending data from the file descriptor, returning if any data
1115 // could be drained. This requires that the file descriptor is in
1116 // nonblocking mode.
1117 fn drain(fd: libc::c_int) -> bool {
1118 let mut ret = false;
1120 let mut buf = [0u8, ..1];
1122 libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void,
1123 buf.len() as libc::size_t)
1125 n if n > 0 => { ret = true; }
1127 -1 if util::wouldblock() => return ret,
1128 n => fail!("bad read {} ({})", os::last_os_error(), n),
1133 // Signal handler for SIGCHLD signals, must be async-signal-safe!
1135 // This function will write to the writing half of the "self pipe" to wake
1136 // up the helper thread if it's waiting. Note that this write must be
1137 // nonblocking because if it blocks and the reader is the thread we
1138 // interrupted, then we'll deadlock.
1140 // When writing, if the write returns EWOULDBLOCK then we choose to ignore
1141 // it. At that point we're guaranteed that there's something in the pipe
1142 // which will wake up the other end at some point, so we just allow this
1143 // signal to be coalesced with the pending signals on the pipe.
1144 extern fn sigchld_handler(_signum: libc::c_int) {
1147 libc::write(WRITE_FD, &msg as *const _ as *const libc::c_void, 1)
1150 -1 if util::wouldblock() => {} // see above comments
1151 n => fail!("bad error on write fd: {} {}", n, os::errno()),
1156 fn waitpid_nowait(pid: pid_t) -> Option<rtio::ProcessExit> {
1157 return waitpid_os(pid);
1159 // This code path isn't necessary on windows
1161 fn waitpid_os(_pid: pid_t) -> Option<rtio::ProcessExit> { None }
1164 fn waitpid_os(pid: pid_t) -> Option<rtio::ProcessExit> {
1165 let mut status = 0 as c_int;
1166 match retry(|| unsafe {
1167 c::waitpid(pid, &mut status, c::WNOHANG)
1169 n if n == pid => Some(translate_status(status)),
1171 n => fail!("unknown waitpid error `{}`: {}", n,
1172 super::last_error().code),
1180 #[test] #[cfg(windows)]
1181 fn test_make_command_line() {
1183 use std::c_str::CString;
1184 use super::make_command_line;
1186 fn test_wrapper(prog: &str, args: &[&str]) -> String {
1187 make_command_line(&prog.to_c_str(),
1189 .map(|a| a.to_c_str())
1190 .collect::<Vec<CString>>()
1195 test_wrapper("prog", ["aaa", "bbb", "ccc"]),
1196 "prog aaa bbb ccc".to_string()
1200 test_wrapper("C:\\Program Files\\blah\\blah.exe", ["aaa"]),
1201 "\"C:\\Program Files\\blah\\blah.exe\" aaa".to_string()
1204 test_wrapper("C:\\Program Files\\test", ["aa\"bb"]),
1205 "\"C:\\Program Files\\test\" aa\\\"bb".to_string()
1208 test_wrapper("echo", ["a b c"]),
1209 "echo \"a b c\"".to_string()
1212 test_wrapper("\u03c0\u042f\u97f3\u00e6\u221e", []),
1213 "\u03c0\u042f\u97f3\u00e6\u221e".to_string()