diff options
Diffstat (limited to 'src/libstd/sys')
| -rw-r--r-- | src/libstd/sys/common/mod.rs | 91 | ||||
| -rw-r--r-- | src/libstd/sys/unix/ext.rs | 81 | ||||
| -rw-r--r-- | src/libstd/sys/unix/fs.rs | 409 | ||||
| -rw-r--r-- | src/libstd/sys/unix/mod.rs | 111 | ||||
| -rw-r--r-- | src/libstd/sys/unix/os.rs | 12 | ||||
| -rw-r--r-- | src/libstd/sys/unix/pipe.rs | 328 | ||||
| -rw-r--r-- | src/libstd/sys/unix/process.rs | 627 | ||||
| -rw-r--r-- | src/libstd/sys/unix/process2.rs | 4 | ||||
| -rw-r--r-- | src/libstd/sys/unix/tcp.rs | 164 | ||||
| -rw-r--r-- | src/libstd/sys/unix/timer.rs | 294 | ||||
| -rw-r--r-- | src/libstd/sys/unix/tty.rs | 81 | ||||
| -rw-r--r-- | src/libstd/sys/unix/udp.rs | 11 | ||||
| -rw-r--r-- | src/libstd/sys/windows/ext.rs | 75 | ||||
| -rw-r--r-- | src/libstd/sys/windows/fs.rs | 452 | ||||
| -rw-r--r-- | src/libstd/sys/windows/helper_signal.rs | 38 | ||||
| -rw-r--r-- | src/libstd/sys/windows/mod.rs | 176 | ||||
| -rw-r--r-- | src/libstd/sys/windows/os.rs | 32 | ||||
| -rw-r--r-- | src/libstd/sys/windows/pipe.rs | 775 | ||||
| -rw-r--r-- | src/libstd/sys/windows/process.rs | 518 | ||||
| -rw-r--r-- | src/libstd/sys/windows/tcp.rs | 230 | ||||
| -rw-r--r-- | src/libstd/sys/windows/timer.rs | 214 | ||||
| -rw-r--r-- | src/libstd/sys/windows/tty.rs | 169 | ||||
| -rw-r--r-- | src/libstd/sys/windows/udp.rs | 11 |
23 files changed, 13 insertions, 4890 deletions
diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs index 8a01eace889..95294b813ea 100644 --- a/src/libstd/sys/common/mod.rs +++ b/src/libstd/sys/common/mod.rs @@ -10,24 +10,11 @@ #![allow(missing_docs)] -use old_io::{self, IoError, IoResult}; use prelude::v1::*; -use sys::{last_error, retry}; -use ffi::CString; -#[allow(deprecated)] // Int -use num::Int; - -#[allow(deprecated)] -use old_path::BytesContainer; - -use collections; - -#[macro_use] pub mod helper_thread; pub mod backtrace; pub mod condvar; pub mod mutex; -pub mod net; pub mod net2; pub mod poison; pub mod remutex; @@ -40,72 +27,6 @@ pub mod wtf8; // common error constructors -#[allow(deprecated)] -pub fn eof() -> IoError { - IoError { - kind: old_io::EndOfFile, - desc: "end of file", - detail: None, - } -} - -#[allow(deprecated)] -pub fn timeout(desc: &'static str) -> IoError { - IoError { - kind: old_io::TimedOut, - desc: desc, - detail: None, - } -} - -#[allow(deprecated)] -pub fn short_write(n: usize, desc: &'static str) -> IoError { - IoError { - kind: if n == 0 { old_io::TimedOut } else { old_io::ShortWrite(n) }, - desc: desc, - detail: None, - } -} - -#[allow(deprecated)] -pub fn unimpl() -> IoError { - IoError { - kind: old_io::IoUnavailable, - desc: "operations not yet supported", - detail: None, - } -} - -// unix has nonzero values as errors -#[allow(deprecated)] -pub fn mkerr_libc<T: Int>(ret: T) -> IoResult<()> { - if ret != Int::zero() { - Err(last_error()) - } else { - Ok(()) - } -} - -pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where - F: FnMut(*const u8, usize) -> i64, -{ - let origamt = data.len(); - let mut data = data.as_ptr(); - let mut amt = origamt; - while amt > 0 { - let ret = retry(|| f(data, amt)); - if ret == 0 { - break - } else if ret != -1 { - amt -= ret as usize; - data = unsafe { data.offset(ret as isize) }; - } else { - return ret; - } - } - return (origamt - amt) as i64; -} - /// A trait for viewing representations from std types #[doc(hidden)] pub trait AsInner<Inner: ?Sized> { @@ -129,15 +50,3 @@ pub trait IntoInner<Inner> { pub trait FromInner<Inner> { fn from_inner(inner: Inner) -> Self; } - -#[doc(hidden)] -#[allow(deprecated)] -pub trait ProcessConfig<K: BytesContainer, V: BytesContainer> { - fn program(&self) -> &CString; - fn args(&self) -> &[CString]; - fn env(&self) -> Option<&collections::HashMap<K, V>>; - fn cwd(&self) -> Option<&CString>; - fn uid(&self) -> Option<usize>; - fn gid(&self) -> Option<usize>; - fn detach(&self) -> bool; -} diff --git a/src/libstd/sys/unix/ext.rs b/src/libstd/sys/unix/ext.rs index fa0f14b4807..0fbcf3aee61 100644 --- a/src/libstd/sys/unix/ext.rs +++ b/src/libstd/sys/unix/ext.rs @@ -15,14 +15,12 @@ //! //! # Example //! -//! ```rust,ignore -//! #![feature(globs)] -//! -//! use std::old_io::fs::File; +//! ```no_run +//! use std::fs::File; //! use std::os::unix::prelude::*; //! //! fn main() { -//! let f = File::create(&Path::new("foo.txt")).unwrap(); +//! let f = File::create("foo.txt").unwrap(); //! let fd = f.as_raw_fd(); //! //! // use fd with native unix bindings @@ -34,7 +32,6 @@ /// Unix-specific extensions to general I/O primitives #[stable(feature = "rust1", since = "1.0.0")] pub mod io { - #[allow(deprecated)] use old_io; use fs; use libc; use net; @@ -82,14 +79,6 @@ pub mod io { unsafe fn from_raw_fd(fd: RawFd) -> Self; } - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::fs::File { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for fs::File { fn as_raw_fd(&self) -> RawFd { @@ -103,70 +92,6 @@ pub mod io { } } - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::pipe::PipeStream { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::net::pipe::UnixStream { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::net::pipe::UnixListener { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::net::pipe::UnixAcceptor { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[stable(feature = "rust1", since = "1.0.0")] - #[allow(deprecated)] - impl AsRawFd for old_io::net::tcp::TcpStream { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[stable(feature = "rust1", since = "1.0.0")] - #[allow(deprecated)] - impl AsRawFd for old_io::net::tcp::TcpListener { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[stable(feature = "rust1", since = "1.0.0")] - #[allow(deprecated)] - impl AsRawFd for old_io::net::tcp::TcpAcceptor { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawFd for old_io::net::udp::UdpSocket { - fn as_raw_fd(&self) -> RawFd { - self.as_inner().fd() - } - } - #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::TcpStream { fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs deleted file mode 100644 index 6121105f10b..00000000000 --- a/src/libstd/sys/unix/fs.rs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Blocking posix-based file I/O -#![allow(deprecated)] - -#![allow(deprecated)] // this module itself is essentially deprecated - -use prelude::v1::*; - -use ffi::{CString, CStr}; -use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; -use old_io::{IoResult, FileStat, SeekStyle}; -use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; -use old_io; -use old_path::{Path, GenericPath}; -use libc::{self, c_int, c_void}; -use mem; -use ptr; -use sys::retry; -use sys_common::{keep_going, eof, mkerr_libc}; - -pub type fd_t = libc::c_int; - -pub struct FileDesc { - /// The underlying C file descriptor. - fd: fd_t, - - /// Whether to close the file descriptor on drop. - close_on_drop: bool, -} - -impl FileDesc { - pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc { - FileDesc { fd: fd, close_on_drop: close_on_drop } - } - - pub fn read(&self, buf: &mut [u8]) -> IoResult<usize> { - let ret = retry(|| unsafe { - libc::read(self.fd(), - buf.as_mut_ptr() as *mut libc::c_void, - buf.len() as libc::size_t) - }); - if ret == 0 { - Err(eof()) - } else if ret < 0 { - Err(super::last_error()) - } else { - Ok(ret as usize) - } - } - pub fn write(&self, buf: &[u8]) -> IoResult<()> { - let ret = keep_going(buf, |buf, len| { - unsafe { - libc::write(self.fd(), buf as *const libc::c_void, - len as libc::size_t) as i64 - } - }); - if ret < 0 { - Err(super::last_error()) - } else { - Ok(()) - } - } - - pub fn fd(&self) -> fd_t { self.fd } - - pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> { - let whence = match whence { - SeekSet => libc::SEEK_SET, - SeekEnd => libc::SEEK_END, - SeekCur => libc::SEEK_CUR, - }; - let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) }; - if n < 0 { - Err(super::last_error()) - } else { - Ok(n as u64) - } - } - - pub fn tell(&self) -> IoResult<u64> { - let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) }; - if n < 0 { - Err(super::last_error()) - } else { - Ok(n as u64) - } - } - - pub fn fsync(&self) -> IoResult<()> { - mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) })) - } - - pub fn datasync(&self) -> IoResult<()> { - return mkerr_libc(os_datasync(self.fd())); - - #[cfg(any(target_os = "macos", target_os = "ios"))] - fn os_datasync(fd: c_int) -> c_int { - unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) } - } - #[cfg(target_os = "linux")] - fn os_datasync(fd: c_int) -> c_int { - retry(|| unsafe { libc::fdatasync(fd) }) - } - #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] - fn os_datasync(fd: c_int) -> c_int { - retry(|| unsafe { libc::fsync(fd) }) - } - } - - pub fn truncate(&self, offset: i64) -> IoResult<()> { - mkerr_libc(retry(|| unsafe { - libc::ftruncate(self.fd(), offset as libc::off_t) - })) - } - - pub fn fstat(&self) -> IoResult<FileStat> { - let mut stat: libc::stat = unsafe { mem::zeroed() }; - match unsafe { libc::fstat(self.fd(), &mut stat) } { - 0 => Ok(mkstat(&stat)), - _ => Err(super::last_error()), - } - } - - /// Extract the actual filedescriptor without closing it. - pub fn unwrap(self) -> fd_t { - let fd = self.fd; - unsafe { mem::forget(self) }; - fd - } -} - -impl Drop for FileDesc { - fn drop(&mut self) { - // closing stdio file handles makes no sense, so never do it. Also, note - // that errors are ignored when closing a file descriptor. The reason - // for this is that if an error occurs we don't actually know if the - // file descriptor was closed or not, and if we retried (for something - // like EINTR), we might close another valid file descriptor (opened - // after we closed ours. - if self.close_on_drop && self.fd > libc::STDERR_FILENO { - let n = unsafe { libc::close(self.fd) }; - if n != 0 { - println!("error {} when closing file descriptor {}", n, self.fd); - } - } - } -} - -fn cstr(path: &Path) -> IoResult<CString> { - Ok(try!(CString::new(path.as_vec()))) -} - -pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> { - let flags = match fm { - Open => 0, - Append => libc::O_APPEND, - Truncate => libc::O_TRUNC, - }; - // Opening with a write permission must silently create the file. - let (flags, mode) = match fa { - Read => (flags | libc::O_RDONLY, 0), - Write => (flags | libc::O_WRONLY | libc::O_CREAT, - libc::S_IRUSR | libc::S_IWUSR), - ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT, - libc::S_IRUSR | libc::S_IWUSR), - }; - - let path = try!(cstr(path)); - match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) { - -1 => Err(super::last_error()), - fd => Ok(FileDesc::new(fd, true)), - } -} - -pub fn mkdir(p: &Path, mode: usize) -> IoResult<()> { - let p = try!(cstr(p)); - mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) }) -} - -pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { - use libc::{dirent_t}; - use libc::{opendir, readdir_r, closedir}; - - fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> { - let root = Path::new(root); - - dirs.into_iter().filter(|path| { - path.as_vec() != b"." && path.as_vec() != b".." - }).map(|path| root.join(path)).collect() - } - - extern { - fn rust_dirent_t_size() -> libc::c_int; - fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char; - } - - let size = unsafe { rust_dirent_t_size() }; - let mut buf = Vec::<u8>::with_capacity(size as usize); - let ptr = buf.as_mut_ptr() as *mut dirent_t; - - let p = try!(CString::new(p.as_vec())); - let dir_ptr = unsafe {opendir(p.as_ptr())}; - - if dir_ptr as usize != 0 { - let mut paths = vec!(); - let mut entry_ptr = ptr::null_mut(); - while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } { - if entry_ptr.is_null() { break } - paths.push(unsafe { - Path::new(CStr::from_ptr(rust_list_dir_val(entry_ptr)).to_bytes()) - }); - } - assert_eq!(unsafe { closedir(dir_ptr) }, 0); - Ok(prune(&p, paths)) - } else { - Err(super::last_error()) - } -} - -pub fn unlink(p: &Path) -> IoResult<()> { - let p = try!(cstr(p)); - mkerr_libc(unsafe { libc::unlink(p.as_ptr()) }) -} - -pub fn rename(old: &Path, new: &Path) -> IoResult<()> { - let old = try!(cstr(old)); - let new = try!(cstr(new)); - mkerr_libc(unsafe { - libc::rename(old.as_ptr(), new.as_ptr()) - }) -} - -pub fn chmod(p: &Path, mode: usize) -> IoResult<()> { - let p = try!(cstr(p)); - mkerr_libc(retry(|| unsafe { - libc::chmod(p.as_ptr(), mode as libc::mode_t) - })) -} - -pub fn rmdir(p: &Path) -> IoResult<()> { - let p = try!(cstr(p)); - mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) }) -} - -pub fn chown(p: &Path, uid: isize, gid: isize) -> IoResult<()> { - let p = try!(cstr(p)); - mkerr_libc(retry(|| unsafe { - libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) - })) -} - -pub fn readlink(p: &Path) -> IoResult<Path> { - let c_path = try!(cstr(p)); - let p = c_path.as_ptr(); - let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; - if len == -1 { - len = 1024; // FIXME: read PATH_MAX from C ffi? - } - let mut buf: Vec<u8> = Vec::with_capacity(len as usize); - match unsafe { - libc::readlink(p, buf.as_ptr() as *mut libc::c_char, - len as libc::size_t) as libc::c_int - } { - -1 => Err(super::last_error()), - n => { - assert!(n > 0); - unsafe { buf.set_len(n as usize); } - Ok(Path::new(buf)) - } - } -} - -pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { - let src = try!(cstr(src)); - let dst = try!(cstr(dst)); - mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }) -} - -pub fn link(src: &Path, dst: &Path) -> IoResult<()> { - let src = try!(cstr(src)); - let dst = try!(cstr(dst)); - mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }) -} - -fn mkstat(stat: &libc::stat) -> FileStat { - // FileStat times are in milliseconds - fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } - - fn ctime(stat: &libc::stat) -> u64 { - mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64) - } - - fn atime(stat: &libc::stat) -> u64 { - mktime(stat.st_atime as u64, stat.st_atime_nsec as u64) - } - - fn mtime(stat: &libc::stat) -> u64 { - mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64) - } - - #[cfg(not(any(target_os = "linux", target_os = "android")))] - fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 } - #[cfg(any(target_os = "linux", target_os = "android"))] - fn flags(_stat: &libc::stat) -> u64 { 0 } - - #[cfg(not(any(target_os = "linux", target_os = "android")))] - fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 } - #[cfg(any(target_os = "linux", target_os = "android"))] - fn gen(_stat: &libc::stat) -> u64 { 0 } - - FileStat { - size: stat.st_size as u64, - kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT { - libc::S_IFREG => old_io::FileType::RegularFile, - libc::S_IFDIR => old_io::FileType::Directory, - libc::S_IFIFO => old_io::FileType::NamedPipe, - libc::S_IFBLK => old_io::FileType::BlockSpecial, - libc::S_IFLNK => old_io::FileType::Symlink, - _ => old_io::FileType::Unknown, - }, - perm: FilePermission::from_bits_truncate(stat.st_mode as u32), - created: ctime(stat), - modified: mtime(stat), - accessed: atime(stat), - unstable: UnstableFileStat { - device: stat.st_dev as u64, - inode: stat.st_ino as u64, - rdev: stat.st_rdev as u64, - nlink: stat.st_nlink as u64, - uid: stat.st_uid as u64, - gid: stat.st_gid as u64, - blksize: stat.st_blksize as u64, - blocks: stat.st_blocks as u64, - flags: flags(stat), - gen: gen(stat), - }, - } -} - -pub fn stat(p: &Path) -> IoResult<FileStat> { - let p = try!(cstr(p)); - let mut stat: libc::stat = unsafe { mem::zeroed() }; - match unsafe { libc::stat(p.as_ptr(), &mut stat) } { - 0 => Ok(mkstat(&stat)), - _ => Err(super::last_error()), - } -} - -pub fn lstat(p: &Path) -> IoResult<FileStat> { - let p = try!(cstr(p)); - let mut stat: libc::stat = unsafe { mem::zeroed() }; - match unsafe { libc::lstat(p.as_ptr(), &mut stat) } { - 0 => Ok(mkstat(&stat)), - _ => Err(super::last_error()), - } -} - -pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> { - let p = try!(cstr(p)); - let buf = libc::utimbuf { - actime: (atime / 1000) as libc::time_t, - modtime: (mtime / 1000) as libc::time_t, - }; - mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) }) -} - -#[cfg(test)] -mod tests { - use super::FileDesc; - use libc; - use os; - use prelude::v1::*; - - #[cfg_attr(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "bitrig"), - ignore)] - // under some system, pipe(2) will return a bidrectionnal pipe - #[test] - fn test_file_desc() { - // Run this test with some pipes so we don't have to mess around with - // opening or closing files. - let (mut reader, mut writer) = unsafe { ::sys::os::pipe().unwrap() }; - - writer.write(b"test").unwrap(); - let mut buf = [0; 4]; - match reader.read(&mut buf) { - Ok(4) => { - assert_eq!(buf[0], 't' as u8); - assert_eq!(buf[1], 'e' as u8); - assert_eq!(buf[2], 's' as u8); - assert_eq!(buf[3], 't' as u8); - } - r => panic!("invalid read: {:?}", r), - } - - assert!(writer.read(&mut buf).is_err()); - assert!(reader.write(&buf).is_err()); - } -} diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index e8409bb4fd4..a8a6219f398 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -13,124 +13,30 @@ use prelude::v1::*; -use ffi::CStr; use io::{self, ErrorKind}; use libc; use num::{Int, SignedInt}; -use old_io::{self, IoError}; -use str; -use sys_common::mkerr_libc; pub mod backtrace; pub mod c; pub mod condvar; pub mod ext; pub mod fd; -pub mod fs; // support for std::old_io -pub mod fs2; // support for std::fs -pub mod helper_signal; +pub mod fs2; pub mod mutex; pub mod net; pub mod os; pub mod os_str; -pub mod pipe; pub mod pipe2; -pub mod process; pub mod process2; pub mod rwlock; pub mod stack_overflow; pub mod sync; -pub mod tcp; pub mod thread; pub mod thread_local; pub mod time; -pub mod timer; -pub mod tty; -pub mod udp; pub mod stdio; -pub mod addrinfo { - pub use sys_common::net::get_host_addresses; - pub use sys_common::net::get_address_name; -} - -// FIXME: move these to c module -pub type sock_t = self::fs::fd_t; -pub type wrlen = libc::size_t; -pub type msglen_t = libc::size_t; -pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); } - -#[allow(deprecated)] -pub fn last_error() -> IoError { - decode_error_detailed(os::errno() as i32) -} - -#[allow(deprecated)] -pub fn last_net_error() -> IoError { - last_error() -} - -extern "system" { - fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char; -} - -#[allow(deprecated)] -pub fn last_gai_error(s: libc::c_int) -> IoError { - - let mut err = decode_error(s); - err.detail = Some(unsafe { - let data = CStr::from_ptr(gai_strerror(s)); - str::from_utf8(data.to_bytes()).unwrap().to_string() - }); - err -} - -/// Convert an `errno` value into a high-level error variant and description. -#[allow(deprecated)] -pub fn decode_error(errno: i32) -> IoError { - // FIXME: this should probably be a bit more descriptive... - let (kind, desc) = match errno { - libc::EOF => (old_io::EndOfFile, "end of file"), - libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"), - libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"), - libc::EPERM | libc::EACCES => - (old_io::PermissionDenied, "permission denied"), - libc::EPIPE => (old_io::BrokenPipe, "broken pipe"), - libc::ENOTCONN => (old_io::NotConnected, "not connected"), - libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"), - libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"), - libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"), - libc::ENOENT => (old_io::FileNotFound, "no such file or directory"), - libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"), - libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"), - libc::EINVAL => (old_io::InvalidInput, "invalid argument"), - libc::ENOTTY => - (old_io::MismatchedFileTypeForOperation, - "file descriptor is not a TTY"), - libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"), - libc::ECANCELED => (old_io::TimedOut, "operation aborted"), - libc::consts::os::posix88::EEXIST => - (old_io::PathAlreadyExists, "path already exists"), - - // These two constants can have the same value on some systems, - // but different values on others, so we can't use a match - // clause - x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => - (old_io::ResourceUnavailable, "resource temporarily unavailable"), - - _ => (old_io::OtherIoError, "unknown error") - }; - IoError { kind: kind, desc: desc, detail: None } -} - -#[allow(deprecated)] -pub fn decode_error_detailed(errno: i32) -> IoError { - let mut err = decode_error(errno); - err.detail = Some(os::error_string(errno)); - err -} - -#[allow(deprecated)] pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno as libc::c_int { libc::ECONNREFUSED => ErrorKind::ConnectionRefused, @@ -199,18 +105,3 @@ pub fn ms_to_timeval(ms: u64) -> libc::timeval { tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t, } } - -#[allow(deprecated)] -pub fn wouldblock() -> bool { - let err = os::errno(); - err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32 -} - -#[allow(deprecated)] -pub fn set_nonblocking(fd: sock_t, nb: bool) { - let set = nb as libc::c_int; - mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) })).unwrap(); -} - -// nothing needed on unix platforms -pub fn init_net() {} diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index d2220bdec32..1c6a13352ff 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -22,14 +22,12 @@ use io; use iter; use libc::{self, c_int, c_char, c_void}; use mem; -#[allow(deprecated)] use old_io::{IoError, IoResult}; use ptr; use path::{self, PathBuf}; use slice; use str; use sys::c; use sys::fd; -use sys::fs::FileDesc; use vec; const BUF_BYTES: usize = 2048; @@ -448,16 +446,6 @@ pub fn unsetenv(n: &OsStr) { } } -#[allow(deprecated)] -pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { - let mut fds = [0; 2]; - if libc::pipe(fds.as_mut_ptr()) == 0 { - Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) - } else { - Err(IoError::last_error()) - } -} - pub fn page_size() -> usize { unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs deleted file mode 100644 index f0071295bf2..00000000000 --- a/src/libstd/sys/unix/pipe.rs +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] - -use prelude::v1::*; - -use ffi::CString; -use libc; -use mem; -use sync::{Arc, Mutex}; -use sync::atomic::{AtomicBool, Ordering}; -use old_io::{self, IoResult, IoError}; - -use sys::{self, timer, retry, c, set_nonblocking, wouldblock}; -use sys::fs::{fd_t, FileDesc}; -use sys_common::net::*; -use sys_common::net::SocketStatus::*; -use sys_common::{eof, mkerr_libc}; - -fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> { - match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } { - -1 => Err(super::last_error()), - fd => Ok(fd) - } -} - -fn addr_to_sockaddr_un(addr: &CString, - storage: &mut libc::sockaddr_storage) - -> IoResult<libc::socklen_t> { - // the sun_path length is limited to SUN_LEN (with null) - assert!(mem::size_of::<libc::sockaddr_storage>() >= - mem::size_of::<libc::sockaddr_un>()); - let s = unsafe { &mut *(storage as *mut _ as *mut libc::sockaddr_un) }; - - let len = addr.as_bytes().len(); - if len > s.sun_path.len() - 1 { - return Err(IoError { - kind: old_io::InvalidInput, - desc: "invalid argument: path must be smaller than SUN_LEN", - detail: None, - }) - } - s.sun_family = libc::AF_UNIX as libc::sa_family_t; - for (slot, value) in s.sun_path.iter_mut().zip(addr.as_bytes().iter()) { - *slot = *value as libc::c_char; - } - - // count the null terminator - let len = mem::size_of::<libc::sa_family_t>() + len + 1; - return Ok(len as libc::socklen_t); -} - -struct Inner { - fd: fd_t, - - // Unused on Linux, where this lock is not necessary. - #[allow(dead_code)] - lock: Mutex<()>, -} - -impl Inner { - fn new(fd: fd_t) -> Inner { - Inner { fd: fd, lock: Mutex::new(()) } - } -} - -impl Drop for Inner { - fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } } -} - -fn connect(addr: &CString, ty: libc::c_int, - timeout: Option<u64>) -> IoResult<Inner> { - let mut storage = unsafe { mem::zeroed() }; - let len = try!(addr_to_sockaddr_un(addr, &mut storage)); - let inner = Inner::new(try!(unix_socket(ty))); - let addrp = &storage as *const _ as *const libc::sockaddr; - - match timeout { - None => { - match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) { - -1 => Err(super::last_error()), - _ => Ok(inner) - } - } - Some(timeout_ms) => { - try!(connect_timeout(inner.fd, addrp, len, timeout_ms)); - Ok(inner) - } - } -} - -fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> { - let mut storage = unsafe { mem::zeroed() }; - let len = try!(addr_to_sockaddr_un(addr, &mut storage)); - let inner = Inner::new(try!(unix_socket(ty))); - let addrp = &storage as *const _ as *const libc::sockaddr; - match unsafe { - libc::bind(inner.fd, addrp, len) - } { - -1 => Err(super::last_error()), - _ => Ok(inner) - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Unix Streams -//////////////////////////////////////////////////////////////////////////////// - -pub struct UnixStream { - inner: Arc<Inner>, - read_deadline: u64, - write_deadline: u64, -} - -impl UnixStream { - pub fn connect(addr: &CString, - timeout: Option<u64>) -> IoResult<UnixStream> { - connect(addr, libc::SOCK_STREAM, timeout).map(|inner| { - UnixStream::new(Arc::new(inner)) - }) - } - - fn new(inner: Arc<Inner>) -> UnixStream { - UnixStream { - inner: inner, - read_deadline: 0, - write_deadline: 0, - } - } - - pub fn fd(&self) -> fd_t { self.inner.fd } - - #[cfg(target_os = "linux")] - fn lock_nonblocking(&self) {} - - #[cfg(not(target_os = "linux"))] - fn lock_nonblocking<'a>(&'a self) -> Guard<'a> { - let ret = Guard { - fd: self.fd(), - guard: self.inner.lock.lock().unwrap(), - }; - set_nonblocking(self.fd(), true); - ret - } - - pub fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - let fd = self.fd(); - let dolock = || self.lock_nonblocking(); - let doread = |nb| unsafe { - let flags = if nb {c::MSG_DONTWAIT} else {0}; - libc::recv(fd, - buf.as_mut_ptr() as *mut libc::c_void, - buf.len() as libc::size_t, - flags) as libc::c_int - }; - read(fd, self.read_deadline, dolock, doread) - } - - pub fn write(&mut self, buf: &[u8]) -> IoResult<()> { - let fd = self.fd(); - let dolock = || self.lock_nonblocking(); - let dowrite = |nb: bool, buf: *const u8, len: usize| unsafe { - let flags = if nb {c::MSG_DONTWAIT} else {0}; - libc::send(fd, - buf as *const _, - len as libc::size_t, - flags) as i64 - }; - match write(fd, self.write_deadline, buf, true, dolock, dowrite) { - Ok(_) => Ok(()), - Err(e) => Err(e) - } - } - - pub fn close_write(&mut self) -> IoResult<()> { - mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) }) - } - - pub fn close_read(&mut self) -> IoResult<()> { - mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) }) - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - self.read_deadline = deadline; - self.write_deadline = deadline; - } - - pub fn set_read_timeout(&mut self, timeout: Option<u64>) { - self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } - - pub fn set_write_timeout(&mut self, timeout: Option<u64>) { - self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } -} - -impl Clone for UnixStream { - fn clone(&self) -> UnixStream { - UnixStream::new(self.inner.clone()) - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Unix Listener -//////////////////////////////////////////////////////////////////////////////// - -pub struct UnixListener { - inner: Inner, - path: CString, -} - -// we currently own the CString, so these impls should be safe -unsafe impl Send for UnixListener {} -unsafe impl Sync for UnixListener {} - -impl UnixListener { - pub fn bind(addr: &CString) -> IoResult<UnixListener> { - bind(addr, libc::SOCK_STREAM).map(|fd| { - UnixListener { inner: fd, path: addr.clone() } - }) - } - - pub fn fd(&self) -> fd_t { self.inner.fd } - - pub fn listen(self) -> IoResult<UnixAcceptor> { - match unsafe { libc::listen(self.fd(), 128) } { - -1 => Err(super::last_error()), - - _ => { - let (reader, writer) = try!(unsafe { sys::os::pipe() }); - set_nonblocking(reader.fd(), true); - set_nonblocking(writer.fd(), true); - set_nonblocking(self.fd(), true); - Ok(UnixAcceptor { - inner: Arc::new(AcceptorInner { - listener: self, - reader: reader, - writer: writer, - closed: AtomicBool::new(false), - }), - deadline: 0, - }) - } - } - } -} - -pub struct UnixAcceptor { - inner: Arc<AcceptorInner>, - deadline: u64, -} - -struct AcceptorInner { - listener: UnixListener, - reader: FileDesc, - writer: FileDesc, - closed: AtomicBool, -} - -impl UnixAcceptor { - pub fn fd(&self) -> fd_t { self.inner.listener.fd() } - - pub fn accept(&mut self) -> IoResult<UnixStream> { - let deadline = if self.deadline == 0 {None} else {Some(self.deadline)}; - - while !self.inner.closed.load(Ordering::SeqCst) { - unsafe { - let mut storage: libc::sockaddr_storage = mem::zeroed(); - let storagep = &mut storage as *mut libc::sockaddr_storage; - let size = mem::size_of::<libc::sockaddr_storage>(); - let mut size = size as libc::socklen_t; - match retry(|| { - libc::accept(self.fd(), - storagep as *mut libc::sockaddr, - &mut size as *mut libc::socklen_t) as libc::c_int - }) { - -1 if wouldblock() => {} - -1 => return Err(super::last_error()), - fd => return Ok(UnixStream::new(Arc::new(Inner::new(fd)))), - } - } - try!(await(&[self.fd(), self.inner.reader.fd()], - deadline, Readable)); - } - - Err(eof()) - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } - - pub fn close_accept(&mut self) -> IoResult<()> { - self.inner.closed.store(true, Ordering::SeqCst); - let fd = FileDesc::new(self.inner.writer.fd(), false); - match fd.write(&[0]) { - Ok(..) => Ok(()), - Err(..) if wouldblock() => Ok(()), - Err(e) => Err(e), - } - } -} - -impl Clone for UnixAcceptor { - fn clone(&self) -> UnixAcceptor { - UnixAcceptor { inner: self.inner.clone(), deadline: 0 } - } -} - -impl Drop for UnixListener { - fn drop(&mut self) { - // Unlink the path to the socket to ensure that it doesn't linger. We're - // careful to unlink the path before we close the file descriptor to - // prevent races where we unlink someone else's path. - unsafe { - let _ = libc::unlink(self.path.as_ptr()); - } - } -} diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs deleted file mode 100644 index 8095325f83d..00000000000 --- a/src/libstd/sys/unix/process.rs +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] // this module itself is essentially deprecated - -use prelude::v1::*; -use self::Req::*; - -use collections::HashMap; -use ffi::CString; -use hash::Hash; -use old_io::process::{ProcessExit, ExitStatus, ExitSignal}; -use old_io::{IoResult, EndOfFile}; -use libc::{self, pid_t, c_void, c_int}; -use io; -use mem; -use sys::os; -use old_path::BytesContainer; -use ptr; -use sync::mpsc::{channel, Sender, Receiver}; -use sys::fs::FileDesc; -use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval}; -use sys_common::helper_thread::Helper; -use sys_common::{AsInner, mkerr_libc, timeout}; - -pub use sys_common::ProcessConfig; - -helper_init! { static HELPER: Helper<Req> } - -/// The unique id of the process (this should never be negative). -pub struct Process { - pub pid: pid_t -} - -enum Req { - NewChild(libc::pid_t, Sender<ProcessExit>, u64), -} - -const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX"; - -impl Process { - pub fn id(&self) -> pid_t { - self.pid - } - - pub unsafe fn kill(&self, signal: isize) -> IoResult<()> { - Process::killpid(self.pid, signal) - } - - pub unsafe fn killpid(pid: pid_t, signal: isize) -> IoResult<()> { - let r = libc::funcs::posix88::signal::kill(pid, signal as c_int); - mkerr_libc(r) - } - - pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>, - out_fd: Option<P>, err_fd: Option<P>) - -> IoResult<Process> - where C: ProcessConfig<K, V>, P: AsInner<FileDesc>, - K: BytesContainer + Eq + Hash, V: BytesContainer - { - use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp}; - - mod rustrt { - extern { - pub fn rust_unset_sigprocmask(); - } - } - - unsafe fn set_cloexec(fd: c_int) { - let ret = c::ioctl(fd, c::FIOCLEX); - assert_eq!(ret, 0); - } - - #[cfg(all(target_os = "android", target_arch = "aarch64"))] - unsafe fn getdtablesize() -> c_int { - libc::sysconf(libc::consts::os::sysconf::_SC_OPEN_MAX) as c_int - } - #[cfg(not(all(target_os = "android", target_arch = "aarch64")))] - unsafe fn getdtablesize() -> c_int { - libc::funcs::bsd44::getdtablesize() - } - - let dirp = cfg.cwd().map(|c| c.as_ptr()).unwrap_or(ptr::null()); - - // temporary until unboxed closures land - let cfg = unsafe { - mem::transmute::<&ProcessConfig<K,V>,&'static ProcessConfig<K,V>>(cfg) - }; - - with_envp(cfg.env(), move|envp: *const c_void| { - with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe { - let (input, mut output) = try!(sys::os::pipe()); - - // We may use this in the child, so perform allocations before the - // fork - let devnull = b"/dev/null\0"; - - set_cloexec(output.fd()); - - let pid = fork(); - if pid < 0 { - return Err(super::last_error()) - } else if pid > 0 { - #[inline] - fn combine(arr: &[u8]) -> i32 { - let a = arr[0] as u32; - let b = arr[1] as u32; - let c = arr[2] as u32; - let d = arr[3] as u32; - - ((a << 24) | (b << 16) | (c << 8) | (d << 0)) as i32 - } - - let p = Process{ pid: pid }; - drop(output); - let mut bytes = [0; 8]; - return match input.read(&mut bytes) { - Ok(8) => { - assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]), - "Validation on the CLOEXEC pipe failed: {:?}", bytes); - let errno = combine(&bytes[0.. 4]); - assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); - Err(super::decode_error(errno)) - } - Err(ref e) if e.kind == EndOfFile => Ok(p), - Err(e) => { - assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); - panic!("the CLOEXEC pipe failed: {:?}", e) - }, - Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic - assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); - panic!("short read on the CLOEXEC pipe") - } - }; - } - - // And at this point we've reached a special time in the life of the - // child. The child must now be considered hamstrung and unable to - // do anything other than syscalls really. Consider the following - // scenario: - // - // 1. Thread A of process 1 grabs the malloc() mutex - // 2. Thread B of process 1 forks(), creating thread C - // 3. Thread C of process 2 then attempts to malloc() - // 4. The memory of process 2 is the same as the memory of - // process 1, so the mutex is locked. - // - // This situation looks a lot like deadlock, right? It turns out - // that this is what pthread_atfork() takes care of, which is - // presumably implemented across platforms. The first thing that - // threads to *before* forking is to do things like grab the malloc - // mutex, and then after the fork they unlock it. - // - // Despite this information, libnative's spawn has been witnessed to - // deadlock on both OSX and FreeBSD. I'm not entirely sure why, but - // all collected backtraces point at malloc/free traffic in the - // child spawned process. - // - // For this reason, the block of code below should contain 0 - // invocations of either malloc of free (or their related friends). - // - // As an example of not having malloc/free traffic, we don't close - // this file descriptor by dropping the FileDesc (which contains an - // allocation). Instead we just close it manually. This will never - // have the drop glue anyway because this code never returns (the - // child will either exec() or invoke libc::exit) - let _ = libc::close(input.fd()); - - fn fail(output: &mut FileDesc) -> ! { - let errno = sys::os::errno() as u32; - let bytes = [ - (errno >> 24) as u8, - (errno >> 16) as u8, - (errno >> 8) as u8, - (errno >> 0) as u8, - CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1], - CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3] - ]; - // pipe I/O up to PIPE_BUF bytes should be atomic - assert!(output.write(&bytes).is_ok()); - unsafe { libc::_exit(1) } - } - - rustrt::rust_unset_sigprocmask(); - - // If a stdio file descriptor is set to be ignored (via a -1 file - // descriptor), then we don't actually close it, but rather open - // up /dev/null into that file descriptor. Otherwise, the first file - // descriptor opened up in the child would be numbered as one of the - // stdio file descriptors, which is likely to wreak havoc. - let setup = |src: Option<P>, dst: c_int| { - let src = match src { - None => { - let flags = if dst == libc::STDIN_FILENO { - libc::O_RDONLY - } else { - libc::O_RDWR - }; - libc::open(devnull.as_ptr() as *const _, flags, 0) - } - Some(obj) => { - let fd = obj.as_inner().fd(); - // Leak the memory and the file descriptor. We're in the - // child now an all our resources are going to be - // cleaned up very soon - mem::forget(obj); - fd - } - }; - src != -1 && retry(|| dup2(src, dst)) != -1 - }; - - if !setup(in_fd, libc::STDIN_FILENO) { fail(&mut output) } - if !setup(out_fd, libc::STDOUT_FILENO) { fail(&mut output) } - if !setup(err_fd, libc::STDERR_FILENO) { fail(&mut output) } - - // close all other fds - for fd in (3..getdtablesize()).rev() { - if fd != output.fd() { - let _ = close(fd as c_int); - } - } - - match cfg.gid() { - Some(u) => { - if libc::setgid(u as libc::gid_t) != 0 { - fail(&mut output); - } - } - None => {} - } - 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 even though our uid has dropped, we may still have - // groups that enable us to do super-user things. This will - // fail if we aren't root, so don't bother checking the - // return value, this is just done as an optimistic - // privilege dropping function. - extern { - fn setgroups(ngroups: libc::c_int, - ptr: *const libc::c_void) -> libc::c_int; - } - let _ = setgroups(0, ptr::null()); - - if libc::setuid(u as libc::uid_t) != 0 { - fail(&mut output); - } - } - None => {} - } - 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. - let _ = libc::setsid(); - } - if !dirp.is_null() && chdir(dirp) == -1 { - fail(&mut output); - } - if !envp.is_null() { - *sys::os::environ() = envp as *const _; - } - let _ = execvp(*argv, argv as *mut _); - fail(&mut output); - }) - }) - } - - pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> { - use cmp; - use sync::mpsc::TryRecvError; - - static mut WRITE_FD: libc::c_int = 0; - - let mut status = 0 as c_int; - if deadline == 0 { - return match retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) }) { - -1 => panic!("unknown waitpid error: {:?}", super::last_error()), - _ => Ok(translate_status(status)), - } - } - - // On unix, wait() and its friends have no timeout parameters, so there is - // no way to time out a thread in wait(). From some googling and some - // thinking, it appears that there are a few ways to handle timeouts in - // wait(), but the only real reasonable one for a multi-threaded program is - // to listen for SIGCHLD. - // - // With this in mind, the waiting mechanism with a timeout barely uses - // waitpid() at all. There are a few times that waitpid() is invoked with - // WNOHANG, but otherwise all the necessary blocking is done by waiting for - // a SIGCHLD to arrive (and that blocking has a timeout). Note, however, - // that waitpid() is still used to actually reap the child. - // - // Signal handling is super tricky in general, and this is no exception. Due - // to the async nature of SIGCHLD, we use the self-pipe trick to transmit - // data out of the signal handler to the rest of the application. The first - // idea would be to have each thread waiting with a timeout to read this - // output file descriptor, but a write() is akin to a signal(), not a - // broadcast(), so it would only wake up one thread, and possibly the wrong - // thread. Hence a helper thread is used. - // - // The helper thread here is responsible for farming requests for a - // waitpid() with a timeout, and then processing all of the wait requests. - // By guaranteeing that only this helper thread is reading half of the - // self-pipe, we're sure that we'll never lose a SIGCHLD. This helper thread - // is also responsible for select() to wait for incoming messages or - // incoming SIGCHLD messages, along with passing an appropriate timeout to - // select() to wake things up as necessary. - // - // The ordering of the following statements is also very purposeful. First, - // we must be guaranteed that the helper thread is booted and available to - // receive SIGCHLD signals, and then we must also ensure that we do a - // nonblocking waitpid() at least once before we go ask the sigchld helper. - // This prevents the race where the child exits, we boot the helper, and - // then we ask for the child's exit status (never seeing a sigchld). - // - // The actual communication between the helper thread and this thread is - // quite simple, just a channel moving data around. - - HELPER.boot(register_sigchld, waitpid_helper); - - match self.try_wait() { - Some(ret) => return Ok(ret), - None => {} - } - - let (tx, rx) = channel(); - HELPER.send(NewChild(self.pid, tx, deadline)); - return match rx.recv() { - Ok(e) => Ok(e), - Err(..) => Err(timeout("wait timed out")), - }; - - // Register a new SIGCHLD handler, returning the reading half of the - // self-pipe plus the old handler registered (return value of sigaction). - // - // Be sure to set up the self-pipe first because as soon as we register a - // handler we're going to start receiving signals. - fn register_sigchld() -> (libc::c_int, c::sigaction) { - unsafe { - let mut pipes = [0; 2]; - assert_eq!(libc::pipe(pipes.as_mut_ptr()), 0); - set_nonblocking(pipes[0], true); - set_nonblocking(pipes[1], true); - WRITE_FD = pipes[1]; - - let mut old: c::sigaction = mem::zeroed(); - let mut new: c::sigaction = mem::zeroed(); - new.sa_handler = sigchld_handler; - new.sa_flags = c::SA_NOCLDSTOP; - assert_eq!(c::sigaction(c::SIGCHLD, &new, &mut old), 0); - (pipes[0], old) - } - } - - // Helper thread for processing SIGCHLD messages - fn waitpid_helper(input: libc::c_int, - messages: Receiver<Req>, - (read_fd, old): (libc::c_int, c::sigaction)) { - set_nonblocking(input, true); - let mut set: c::fd_set = unsafe { mem::zeroed() }; - let mut tv: libc::timeval; - let mut active = Vec::<(libc::pid_t, Sender<ProcessExit>, u64)>::new(); - let max = cmp::max(input, read_fd) + 1; - - 'outer: loop { - // Figure out the timeout of our syscall-to-happen. If we're waiting - // for some processes, then they'll have a timeout, otherwise we - // wait indefinitely for a message to arrive. - // - // FIXME: sure would be nice to not have to scan the entire array - let min = active.iter().map(|a| a.2).enumerate().min_by(|p| { - p.1 - }); - let (p, idx) = match min { - Some((idx, deadline)) => { - let now = sys::timer::now(); - let ms = if now < deadline {deadline - now} else {0}; - tv = ms_to_timeval(ms); - (&mut tv as *mut _, idx) - } - None => (ptr::null_mut(), -1), - }; - - // Wait for something to happen - c::fd_set(&mut set, input); - c::fd_set(&mut set, read_fd); - match unsafe { c::select(max, &mut set, ptr::null_mut(), - ptr::null_mut(), p) } { - // interrupted, retry - -1 if os::errno() == libc::EINTR as i32 => continue, - - // We read something, break out and process - 1 | 2 => {} - - // Timeout, the pending request is removed - 0 => { - drop(active.remove(idx)); - continue - } - - n => panic!("error in select {:?} ({:?})", os::errno(), n), - } - - // Process any pending messages - if drain(input) { - loop { - match messages.try_recv() { - Ok(NewChild(pid, tx, deadline)) => { - active.push((pid, tx, deadline)); - } - // Once we've been disconnected it means the main - // thread is exiting (at_exit has run). We could - // still have active waiter for other threads, so - // we're just going to drop them all on the floor. - // This means that they won't receive a "you're - // done" message in which case they'll be considered - // as timed out, but more generally errors will - // start propagating. - Err(TryRecvError::Disconnected) => { - break 'outer; - } - Err(TryRecvError::Empty) => break, - } - } - } - - // If a child exited (somehow received SIGCHLD), then poll all - // children to see if any of them exited. - // - // We also attempt to be responsible netizens when dealing with - // SIGCHLD by invoking any previous SIGCHLD handler instead of just - // ignoring any previous SIGCHLD handler. Note that we don't provide - // a 1:1 mapping of our handler invocations to the previous handler - // invocations because we drain the `read_fd` entirely. This is - // probably OK because the kernel is already allowed to coalesce - // simultaneous signals, we're just doing some extra coalescing. - // - // Another point of note is that this likely runs the signal handler - // on a different thread than the one that received the signal. I - // *think* this is ok at this time. - // - // The main reason for doing this is to allow stdtest to run native - // tests as well. Both libgreen and libnative are running around - // with process timeouts, but libgreen should get there first - // (currently libuv doesn't handle old signal handlers). - if drain(read_fd) { - let i: usize = unsafe { mem::transmute(old.sa_handler) }; - if i != 0 { - assert!(old.sa_flags & c::SA_SIGINFO == 0); - (old.sa_handler)(c::SIGCHLD); - } - - // FIXME: sure would be nice to not have to scan the entire - // array... - active.retain(|&(pid, ref tx, _)| { - let pr = Process { pid: pid }; - match pr.try_wait() { - Some(msg) => { tx.send(msg).unwrap(); false } - None => true, - } - }); - } - } - - // Once this helper thread is done, we re-register the old sigchld - // handler and close our intermediate file descriptors. - unsafe { - assert_eq!(c::sigaction(c::SIGCHLD, &old, ptr::null_mut()), 0); - let _ = libc::close(read_fd); - let _ = libc::close(WRITE_FD); - WRITE_FD = -1; - } - } - - // Drain all pending data from the file descriptor, returning if any data - // could be drained. This requires that the file descriptor is in - // nonblocking mode. - fn drain(fd: libc::c_int) -> bool { - let mut ret = false; - loop { - let mut buf = [0u8; 1]; - match unsafe { - libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, - buf.len() as libc::size_t) - } { - n if n > 0 => { ret = true; } - 0 => return true, - -1 if wouldblock() => return ret, - n => panic!("bad read {} ({})", - io::Error::last_os_error(), n), - } - } - } - - // Signal handler for SIGCHLD signals, must be async-signal-safe! - // - // This function will write to the writing half of the "self pipe" to wake - // up the helper thread if it's waiting. Note that this write must be - // nonblocking because if it blocks and the reader is the thread we - // interrupted, then we'll deadlock. - // - // When writing, if the write returns EWOULDBLOCK then we choose to ignore - // it. At that point we're guaranteed that there's something in the pipe - // which will wake up the other end at some point, so we just allow this - // signal to be coalesced with the pending signals on the pipe. - extern fn sigchld_handler(_signum: libc::c_int) { - let msg = 1; - match unsafe { - libc::write(WRITE_FD, &msg as *const _ as *const libc::c_void, 1) - } { - 1 => {} - -1 if wouldblock() => {} // see above comments - n => panic!("bad error on write fd: {:?} {:?}", n, os::errno()), - } - } - } - - pub fn try_wait(&self) -> Option<ProcessExit> { - let mut status = 0 as c_int; - match retry(|| unsafe { - c::waitpid(self.pid, &mut status, c::WNOHANG) - }) { - n if n == self.pid => Some(translate_status(status)), - 0 => None, - n => panic!("unknown waitpid error `{:?}`: {:?}", n, - super::last_error()), - } - } -} - -fn with_argv<T,F>(prog: &CString, args: &[CString], - cb: F) - -> T - where F : FnOnce(*const *const libc::c_char) -> T -{ - let mut ptrs: Vec<*const 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.as_ptr()); - ptrs.extend(args.iter().map(|tmp| tmp.as_ptr())); - - // Add a terminating null pointer (required by libc). - ptrs.push(ptr::null()); - - cb(ptrs.as_ptr()) -} - -fn with_envp<K,V,T,F>(env: Option<&HashMap<K, V>>, - cb: F) - -> T - where F : FnOnce(*const c_void) -> T, - K : BytesContainer + Eq + Hash, - V : BytesContainer -{ - // On posixy systems 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 { - let mut kv = Vec::new(); - kv.push_all(pair.0.container_as_bytes()); - kv.push('=' as u8); - kv.push_all(pair.1.container_as_bytes()); - kv.push(0); // terminating null - tmps.push(kv); - } - - // As with `with_argv`, this is unsafe, since cb could leak the pointers. - let mut ptrs: Vec<*const libc::c_char> = - tmps.iter() - .map(|tmp| tmp.as_ptr() as *const libc::c_char) - .collect(); - ptrs.push(ptr::null()); - - cb(ptrs.as_ptr() as *const c_void) - } - _ => cb(ptr::null()) - } -} - -fn translate_status(status: c_int) -> ProcessExit { - #![allow(non_snake_case)] - #[cfg(any(target_os = "linux", target_os = "android"))] - mod imp { - pub fn WIFEXITED(status: i32) -> bool { (status & 0xff) == 0 } - pub fn WEXITSTATUS(status: i32) -> i32 { (status >> 8) & 0xff } - pub fn WTERMSIG(status: i32) -> i32 { status & 0x7f } - } - - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "bitrig", - target_os = "openbsd"))] - mod imp { - pub fn WIFEXITED(status: i32) -> bool { (status & 0x7f) == 0 } - pub fn WEXITSTATUS(status: i32) -> i32 { status >> 8 } - pub fn WTERMSIG(status: i32) -> i32 { status & 0o177 } - } - - if imp::WIFEXITED(status) { - ExitStatus(imp::WEXITSTATUS(status) as isize) - } else { - ExitSignal(imp::WTERMSIG(status) as isize) - } -} diff --git a/src/libstd/sys/unix/process2.rs b/src/libstd/sys/unix/process2.rs index 0b4e871454d..caa7b4eb29c 100644 --- a/src/libstd/sys/unix/process2.rs +++ b/src/libstd/sys/unix/process2.rs @@ -328,8 +328,8 @@ impl Process { }) { n if n == self.pid => Some(translate_status(status)), 0 => None, - n => panic!("unknown waitpid error `{:?}`: {:?}", n, - super::last_error()), + n => panic!("unknown waitpid error `{}`: {}", n, + io::Error::last_os_error()), } } } diff --git a/src/libstd/sys/unix/tcp.rs b/src/libstd/sys/unix/tcp.rs deleted file mode 100644 index a9f2198208b..00000000000 --- a/src/libstd/sys/unix/tcp.rs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] - -use prelude::v1::*; - -use old_io::net::ip; -use old_io::IoResult; -use libc; -use mem; -use ptr; -use super::{last_error, last_net_error, retry, sock_t}; -use sync::Arc; -use sync::atomic::{AtomicBool, Ordering}; -use sys::fs::FileDesc; -use sys::{set_nonblocking, wouldblock}; -use sys; -use sys_common; -use sys_common::net; -use sys_common::net::SocketStatus::Readable; - -pub use sys_common::net::TcpStream; - -//////////////////////////////////////////////////////////////////////////////// -// TCP listeners -//////////////////////////////////////////////////////////////////////////////// - -pub struct TcpListener { - pub inner: FileDesc, -} - -unsafe impl Sync for TcpListener {} - -impl TcpListener { - pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> { - let fd = try!(net::socket(addr, libc::SOCK_STREAM)); - let ret = TcpListener { inner: FileDesc::new(fd, true) }; - - let mut storage = unsafe { mem::zeroed() }; - let len = net::addr_to_sockaddr(addr, &mut storage); - let addrp = &storage as *const _ as *const libc::sockaddr; - - // On platforms with Berkeley-derived sockets, this allows - // to quickly rebind a socket, without needing to wait for - // the OS to clean up the previous one. - try!(net::setsockopt(fd, libc::SOL_SOCKET, - libc::SO_REUSEADDR, - 1 as libc::c_int)); - - - match unsafe { libc::bind(fd, addrp, len) } { - -1 => Err(last_error()), - _ => Ok(ret), - } - } - - pub fn fd(&self) -> sock_t { self.inner.fd() } - - pub fn listen(self, backlog: isize) -> IoResult<TcpAcceptor> { - match unsafe { libc::listen(self.fd(), backlog as libc::c_int) } { - -1 => Err(last_net_error()), - _ => { - let (reader, writer) = try!(unsafe { sys::os::pipe() }); - set_nonblocking(reader.fd(), true); - set_nonblocking(writer.fd(), true); - set_nonblocking(self.fd(), true); - Ok(TcpAcceptor { - inner: Arc::new(AcceptorInner { - listener: self, - reader: reader, - writer: writer, - closed: AtomicBool::new(false), - }), - deadline: 0, - }) - } - } - } - - pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> { - net::sockname(self.fd(), libc::getsockname) - } -} - -pub struct TcpAcceptor { - inner: Arc<AcceptorInner>, - deadline: u64, -} - -struct AcceptorInner { - listener: TcpListener, - reader: FileDesc, - writer: FileDesc, - closed: AtomicBool, -} - -unsafe impl Sync for AcceptorInner {} - -impl TcpAcceptor { - pub fn fd(&self) -> sock_t { self.inner.listener.fd() } - - pub fn accept(&mut self) -> IoResult<TcpStream> { - // In implementing accept, the two main concerns are dealing with - // close_accept() and timeouts. The unix implementation is based on a - // nonblocking accept plus a call to select(). Windows ends up having - // an entirely separate implementation than unix, which is explained - // below. - // - // To implement timeouts, all blocking is done via select() instead of - // accept() by putting the socket in non-blocking mode. Because - // select() takes a timeout argument, we just pass through the timeout - // to select(). - // - // To implement close_accept(), we have a self-pipe to ourselves which - // is passed to select() along with the socket being accepted on. The - // self-pipe is never written to unless close_accept() is called. - let deadline = if self.deadline == 0 {None} else {Some(self.deadline)}; - - while !self.inner.closed.load(Ordering::SeqCst) { - match retry(|| unsafe { - libc::accept(self.fd(), ptr::null_mut(), ptr::null_mut()) - }) { - -1 if wouldblock() => {} - -1 => return Err(last_net_error()), - fd => return Ok(TcpStream::new(fd as sock_t)), - } - try!(net::await(&[self.fd(), self.inner.reader.fd()], - deadline, Readable)); - } - - Err(sys_common::eof()) - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - self.deadline = timeout.map(|a| sys::timer::now() + a).unwrap_or(0); - } - - pub fn close_accept(&mut self) -> IoResult<()> { - self.inner.closed.store(true, Ordering::SeqCst); - let fd = FileDesc::new(self.inner.writer.fd(), false); - match fd.write(&[0]) { - Ok(..) => Ok(()), - Err(..) if wouldblock() => Ok(()), - Err(e) => Err(e), - } - } -} - -impl Clone for TcpAcceptor { - fn clone(&self) -> TcpAcceptor { - TcpAcceptor { - inner: self.inner.clone(), - deadline: 0, - } - } -} diff --git a/src/libstd/sys/unix/timer.rs b/src/libstd/sys/unix/timer.rs deleted file mode 100644 index 9309147b15c..00000000000 --- a/src/libstd/sys/unix/timer.rs +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Timers for non-Linux/non-Windows OSes -//! -//! This module implements timers with a worker thread, select(), and a lot of -//! witchcraft that turns out to be horribly inaccurate timers. The unfortunate -//! part is that I'm at a loss of what else to do one these OSes. This is also -//! why Linux has a specialized timerfd implementation and windows has its own -//! implementation (they're more accurate than this one). -//! -//! The basic idea is that there is a worker thread that's communicated to via a -//! channel and a pipe, the pipe is used by the worker thread in a select() -//! syscall with a timeout. The timeout is the "next timer timeout" while the -//! channel is used to send data over to the worker thread. -//! -//! Whenever the call to select() times out, then a channel receives a message. -//! Whenever the call returns that the file descriptor has information, then the -//! channel from timers is drained, enqueuing all incoming requests. -//! -//! The actual implementation of the helper thread is a sorted array of -//! timers in terms of target firing date. The target is the absolute time at -//! which the timer should fire. Timers are then re-enqueued after a firing if -//! the repeat boolean is set. -//! -//! Naturally, all this logic of adding times and keeping track of -//! relative/absolute time is a little lossy and not quite exact. I've done the -//! best I could to reduce the amount of calls to 'now()', but there's likely -//! still inaccuracies trickling in here and there. -//! -//! One of the tricky parts of this implementation is that whenever a timer is -//! acted upon, it must cancel whatever the previous action was (if one is -//! active) in order to act like the other implementations of this timer. In -//! order to do this, the timer's inner pointer is transferred to the worker -//! thread. Whenever the timer is modified, it first takes ownership back from -//! the worker thread in order to modify the same data structure. This has the -//! side effect of "cancelling" the previous requests while allowing a -//! re-enqueuing later on. -//! -//! Note that all time units in this file are in *milliseconds*. - -#![allow(deprecated)] - -use prelude::v1::*; -use self::Req::*; - -use old_io::IoResult; -use libc; -use mem; -use sys::os; -use io; -use ptr; -use sync::atomic::{self, Ordering}; -use sync::mpsc::{channel, Sender, Receiver, TryRecvError}; -use sys::c; -use sys::fs::FileDesc; -use sys_common::helper_thread::Helper; - -helper_init! { static HELPER: Helper<Req> } - -pub trait Callback { - fn call(&mut self); -} - -pub struct Timer { - id: usize, - inner: Option<Box<Inner>>, -} - -pub struct Inner { - cb: Option<Box<Callback + Send>>, - interval: u64, - repeat: bool, - target: u64, - id: usize, -} - -pub enum Req { - // Add a new timer to the helper thread. - NewTimer(Box<Inner>), - - // Remove a timer based on its id and then send it back on the channel - // provided - RemoveTimer(usize, Sender<Box<Inner>>), -} - -// returns the current time (in milliseconds) -pub fn now() -> u64 { - unsafe { - let mut now: libc::timeval = mem::zeroed(); - assert_eq!(c::gettimeofday(&mut now, ptr::null_mut()), 0); - return (now.tv_sec as u64) * 1000 + (now.tv_usec as u64) / 1000; - } -} - -fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) { - let mut set: c::fd_set = unsafe { mem::zeroed() }; - - let fd = FileDesc::new(input, true); - let mut timeout: libc::timeval = unsafe { mem::zeroed() }; - - // active timers are those which are able to be selected upon (and it's a - // sorted list, and dead timers are those which have expired, but ownership - // hasn't yet been transferred back to the timer itself. - let mut active: Vec<Box<Inner>> = vec![]; - let mut dead = vec![]; - - // inserts a timer into an array of timers (sorted by firing time) - fn insert(t: Box<Inner>, active: &mut Vec<Box<Inner>>) { - match active.iter().position(|tm| tm.target > t.target) { - Some(pos) => { active.insert(pos, t); } - None => { active.push(t); } - } - } - - // signals the first requests in the queue, possible re-enqueueing it. - fn signal(active: &mut Vec<Box<Inner>>, - dead: &mut Vec<(usize, Box<Inner>)>) { - if active.is_empty() { return } - - let mut timer = active.remove(0); - let mut cb = timer.cb.take().unwrap(); - cb.call(); - if timer.repeat { - timer.cb = Some(cb); - timer.target += timer.interval; - insert(timer, active); - } else { - dead.push((timer.id, timer)); - } - } - - 'outer: loop { - let timeout = if active.len() == 0 { - // Empty array? no timeout (wait forever for the next request) - ptr::null_mut() - } else { - let now = now(); - // If this request has already expired, then signal it and go - // through another iteration - if active[0].target <= now { - signal(&mut active, &mut dead); - continue; - } - - // The actual timeout listed in the requests array is an - // absolute date, so here we translate the absolute time to a - // relative time. - let tm = active[0].target - now; - timeout.tv_sec = (tm / 1000) as libc::time_t; - timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t; - &mut timeout as *mut libc::timeval - }; - - c::fd_set(&mut set, input); - match unsafe { - c::select(input + 1, &mut set, ptr::null_mut(), - ptr::null_mut(), timeout) - } { - // timed out - 0 => signal(&mut active, &mut dead), - - // file descriptor write woke us up, we've got some new requests - 1 => { - loop { - match messages.try_recv() { - // Once we've been disconnected it means the main thread - // is exiting (at_exit has run). We could still have - // active timers for other threads, so we're just going - // to drop them all on the floor. This is all we can - // really do, however, to prevent resource leakage. The - // remaining timers will likely start panicking quickly - // as they attempt to re-use this thread but are - // disallowed to do so. - Err(TryRecvError::Disconnected) => { - break 'outer; - } - - Ok(NewTimer(timer)) => insert(timer, &mut active), - - Ok(RemoveTimer(id, ack)) => { - match dead.iter().position(|&(i, _)| id == i) { - Some(i) => { - let (_, i) = dead.remove(i); - ack.send(i).unwrap(); - continue - } - None => {} - } - let i = active.iter().position(|i| i.id == id); - let i = i.expect("no timer found"); - let t = active.remove(i); - ack.send(t).unwrap(); - } - Err(..) => break - } - } - - // drain the file descriptor - let mut buf = [0]; - assert_eq!(fd.read(&mut buf).unwrap(), 1); - } - - -1 if os::errno() == libc::EINTR as i32 => {} - n => panic!("helper thread failed in select() with error: {} ({})", - n, io::Error::last_os_error()) - } - } -} - -impl Timer { - pub fn new() -> IoResult<Timer> { - // See notes above regarding using isize return value - // instead of () - HELPER.boot(|| {}, helper); - - static ID: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT; - let id = ID.fetch_add(1, Ordering::Relaxed); - Ok(Timer { - id: id, - inner: Some(box Inner { - cb: None, - interval: 0, - target: 0, - repeat: false, - id: id, - }) - }) - } - - pub fn sleep(&mut self, ms: u64) { - let mut inner = self.inner(); - inner.cb = None; // cancel any previous request - self.inner = Some(inner); - - let mut to_sleep = libc::timespec { - tv_sec: (ms / 1000) as libc::time_t, - tv_nsec: ((ms % 1000) * 1000000) as libc::c_long, - }; - while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 { - if os::errno() as isize != libc::EINTR as isize { - panic!("failed to sleep, but not because of EINTR?"); - } - } - } - - pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) { - let now = now(); - let mut inner = self.inner(); - - inner.repeat = false; - inner.cb = Some(cb); - inner.interval = msecs; - inner.target = now + msecs; - - HELPER.send(NewTimer(inner)); - } - - pub fn period(&mut self, msecs: u64, cb: Box<Callback + Send>) { - let now = now(); - let mut inner = self.inner(); - - inner.repeat = true; - inner.cb = Some(cb); - inner.interval = msecs; - inner.target = now + msecs; - - HELPER.send(NewTimer(inner)); - } - - fn inner(&mut self) -> Box<Inner> { - match self.inner.take() { - Some(i) => i, - None => { - let (tx, rx) = channel(); - HELPER.send(RemoveTimer(self.id, tx)); - rx.recv().unwrap() - } - } - } -} - -impl Drop for Timer { - fn drop(&mut self) { - self.inner = Some(self.inner()); - } -} diff --git a/src/libstd/sys/unix/tty.rs b/src/libstd/sys/unix/tty.rs deleted file mode 100644 index 2f6fd713bfb..00000000000 --- a/src/libstd/sys/unix/tty.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] - -use prelude::v1::*; - -use sys::fs::FileDesc; -use libc::{self, c_int, c_ulong}; -use old_io::{self, IoResult, IoError}; -use sys::c; -use sys_common; - -pub struct TTY { - pub fd: FileDesc, -} - -#[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "bitrig", - target_os = "openbsd"))] -const TIOCGWINSZ: c_ulong = 0x40087468; - -#[cfg(any(target_os = "linux", target_os = "android"))] -const TIOCGWINSZ: c_ulong = 0x00005413; - -impl TTY { - pub fn new(fd: c_int) -> IoResult<TTY> { - if unsafe { libc::isatty(fd) } != 0 { - Ok(TTY { fd: FileDesc::new(fd, true) }) - } else { - Err(IoError { - kind: old_io::MismatchedFileTypeForOperation, - desc: "file descriptor is not a TTY", - detail: None, - }) - } - } - - pub fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - self.fd.read(buf) - } - pub fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.fd.write(buf) - } - pub fn set_raw(&mut self, _raw: bool) -> IoResult<()> { - Err(sys_common::unimpl()) - } - - pub fn get_winsize(&mut self) -> IoResult<(isize, isize)> { - unsafe { - #[repr(C)] - struct winsize { - ws_row: u16, - ws_col: u16, - ws_xpixel: u16, - ws_ypixel: u16 - } - - let mut size = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0 }; - if c::ioctl(self.fd.fd(), TIOCGWINSZ, &mut size) == -1 { - Err(IoError { - kind: old_io::OtherIoError, - desc: "Size of terminal could not be determined", - detail: None, - }) - } else { - Ok((size.ws_col as isize, size.ws_row as isize)) - } - } - } -} diff --git a/src/libstd/sys/unix/udp.rs b/src/libstd/sys/unix/udp.rs deleted file mode 100644 index 50f8fb828ad..00000000000 --- a/src/libstd/sys/unix/udp.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -pub use sys_common::net::UdpSocket; diff --git a/src/libstd/sys/windows/ext.rs b/src/libstd/sys/windows/ext.rs index 5f6e74d4b72..ea95cc5bfd5 100644 --- a/src/libstd/sys/windows/ext.rs +++ b/src/libstd/sys/windows/ext.rs @@ -24,9 +24,6 @@ pub mod io { use sys_common::{net2, AsInner, FromInner}; use sys; - #[allow(deprecated)] - use old_io; - /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] pub type RawHandle = libc::HANDLE; @@ -61,14 +58,6 @@ pub mod io { unsafe fn from_raw_handle(handle: RawHandle) -> Self; } - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawHandle for old_io::fs::File { - fn as_raw_handle(&self) -> RawHandle { - self.as_inner().handle() - } - } - #[stable(feature = "rust1", since = "1.0.0")] impl AsRawHandle for fs::File { fn as_raw_handle(&self) -> RawHandle { @@ -83,38 +72,6 @@ pub mod io { } } - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawHandle for old_io::pipe::PipeStream { - fn as_raw_handle(&self) -> RawHandle { - self.as_inner().handle() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawHandle for old_io::net::pipe::UnixStream { - fn as_raw_handle(&self) -> RawHandle { - self.as_inner().handle() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawHandle for old_io::net::pipe::UnixListener { - fn as_raw_handle(&self) -> RawHandle { - self.as_inner().handle() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawHandle for old_io::net::pipe::UnixAcceptor { - fn as_raw_handle(&self) -> RawHandle { - self.as_inner().handle() - } - } - /// Extract raw sockets. #[stable(feature = "rust1", since = "1.0.0")] pub trait AsRawSocket { @@ -139,38 +96,6 @@ pub mod io { unsafe fn from_raw_socket(sock: RawSocket) -> Self; } - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawSocket for old_io::net::tcp::TcpStream { - fn as_raw_socket(&self) -> RawSocket { - self.as_inner().fd() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawSocket for old_io::net::tcp::TcpListener { - fn as_raw_socket(&self) -> RawSocket { - self.as_inner().socket() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawSocket for old_io::net::tcp::TcpAcceptor { - fn as_raw_socket(&self) -> RawSocket { - self.as_inner().socket() - } - } - - #[allow(deprecated)] - #[stable(feature = "rust1", since = "1.0.0")] - impl AsRawSocket for old_io::net::udp::UdpSocket { - fn as_raw_socket(&self) -> RawSocket { - self.as_inner().fd() - } - } - #[stable(feature = "rust1", since = "1.0.0")] impl AsRawSocket for net::TcpStream { fn as_raw_socket(&self) -> RawSocket { diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs deleted file mode 100644 index 0bbb1a9e927..00000000000 --- a/src/libstd/sys/windows/fs.rs +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Blocking Windows-based file I/O - -#![allow(deprecated)] // this module itself is essentially deprecated - -use libc::{self, c_int}; - -use mem; -use ptr; -use old_io; - -use prelude::v1::*; -use sys; -use sys_common::{self, mkerr_libc}; - -use old_path::{Path, GenericPath}; -use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; -use old_io::{IoResult, IoError, FileStat, SeekStyle}; -use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; - -pub type fd_t = libc::c_int; - -pub struct FileDesc { - /// The underlying C file descriptor. - pub fd: fd_t, - - /// Whether to close the file descriptor on drop. - close_on_drop: bool, -} - -impl FileDesc { - pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc { - FileDesc { fd: fd, close_on_drop: close_on_drop } - } - - pub fn read(&self, buf: &mut [u8]) -> IoResult<usize> { - let mut read = 0; - let ret = unsafe { - libc::ReadFile(self.handle(), buf.as_ptr() as libc::LPVOID, - buf.len() as libc::DWORD, &mut read, - ptr::null_mut()) - }; - if ret != 0 { - Ok(read as usize) - } else { - Err(super::last_error()) - } - } - - pub fn write(&self, buf: &[u8]) -> IoResult<()> { - let mut cur = buf.as_ptr(); - let mut remaining = buf.len(); - while remaining > 0 { - let mut amt = 0; - let ret = unsafe { - libc::WriteFile(self.handle(), cur as libc::LPVOID, - remaining as libc::DWORD, &mut amt, - ptr::null_mut()) - }; - if ret != 0 { - remaining -= amt as usize; - cur = unsafe { cur.offset(amt as isize) }; - } else { - return Err(super::last_error()) - } - } - Ok(()) - } - - pub fn fd(&self) -> fd_t { self.fd } - - pub fn handle(&self) -> libc::HANDLE { - unsafe { libc::get_osfhandle(self.fd()) as libc::HANDLE } - } - - // A version of seek that takes &self so that tell can call it - // - the private seek should of course take &mut self. - fn seek_common(&self, pos: i64, style: SeekStyle) -> IoResult<u64> { - let whence = match style { - SeekSet => libc::FILE_BEGIN, - SeekEnd => libc::FILE_END, - SeekCur => libc::FILE_CURRENT, - }; - unsafe { - let mut newpos = 0; - match libc::SetFilePointerEx(self.handle(), pos, &mut newpos, whence) { - 0 => Err(super::last_error()), - _ => Ok(newpos as u64), - } - } - } - - pub fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<u64> { - self.seek_common(pos, style) - } - - pub fn tell(&self) -> IoResult<u64> { - self.seek_common(0, SeekCur) - } - - pub fn fsync(&mut self) -> IoResult<()> { - super::mkerr_winbool(unsafe { - libc::FlushFileBuffers(self.handle()) - }) - } - - pub fn datasync(&mut self) -> IoResult<()> { return self.fsync(); } - - pub fn truncate(&mut self, offset: i64) -> IoResult<()> { - let orig_pos = try!(self.tell()); - let _ = try!(self.seek(offset, SeekSet)); - let ret = unsafe { - match libc::SetEndOfFile(self.handle()) { - 0 => Err(super::last_error()), - _ => Ok(()) - } - }; - let _ = self.seek(orig_pos as i64, SeekSet); - return ret; - } - - pub fn fstat(&self) -> IoResult<old_io::FileStat> { - let mut stat: libc::stat = unsafe { mem::zeroed() }; - match unsafe { libc::fstat(self.fd(), &mut stat) } { - 0 => Ok(mkstat(&stat)), - _ => Err(super::last_error()), - } - } - - #[allow(dead_code)] - pub fn unwrap(self) -> fd_t { - let fd = self.fd; - unsafe { mem::forget(self) }; - fd - } -} - -impl Drop for FileDesc { - fn drop(&mut self) { - // closing stdio file handles makes no sense, so never do it. Also, note - // that errors are ignored when closing a file descriptor. The reason - // for this is that if an error occurs we don't actually know if the - // file descriptor was closed or not, and if we retried (for something - // like EINTR), we might close another valid file descriptor (opened - // after we closed ours. - if self.close_on_drop && self.fd > libc::STDERR_FILENO { - let n = unsafe { libc::close(self.fd) }; - if n != 0 { - println!("error {} when closing file descriptor {}", n, self.fd); - } - } - } -} - -pub fn to_utf16(s: &Path) -> IoResult<Vec<u16>> { - sys::to_utf16(s.as_str()) -} - -pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> { - // Flags passed to open_osfhandle - let flags = match fm { - Open => 0, - Append => libc::O_APPEND, - Truncate => libc::O_TRUNC, - }; - let flags = match fa { - Read => flags | libc::O_RDONLY, - Write => flags | libc::O_WRONLY | libc::O_CREAT, - ReadWrite => flags | libc::O_RDWR | libc::O_CREAT, - }; - let mut dwDesiredAccess = match fa { - Read => libc::FILE_GENERIC_READ, - Write => libc::FILE_GENERIC_WRITE, - ReadWrite => libc::FILE_GENERIC_READ | libc::FILE_GENERIC_WRITE - }; - - // libuv has a good comment about this, but the basic idea is what we try to - // emulate unix semantics by enabling all sharing by allowing things such as - // deleting a file while it's still open. - let dwShareMode = libc::FILE_SHARE_READ | libc::FILE_SHARE_WRITE | - libc::FILE_SHARE_DELETE; - - let dwCreationDisposition = match (fm, fa) { - (Truncate, Read) => libc::TRUNCATE_EXISTING, - (Truncate, _) => libc::CREATE_ALWAYS, - (Open, Read) => libc::OPEN_EXISTING, - (Open, _) => libc::OPEN_ALWAYS, - (Append, Read) => { - dwDesiredAccess |= libc::FILE_APPEND_DATA; - libc::OPEN_EXISTING - } - (Append, _) => { - dwDesiredAccess &= !libc::FILE_WRITE_DATA; - dwDesiredAccess |= libc::FILE_APPEND_DATA; - libc::OPEN_ALWAYS - } - }; - - let mut dwFlagsAndAttributes = libc::FILE_ATTRIBUTE_NORMAL; - // Compat with unix, this allows opening directories (see libuv) - dwFlagsAndAttributes |= libc::FILE_FLAG_BACKUP_SEMANTICS; - - let path = try!(to_utf16(path)); - let handle = unsafe { - libc::CreateFileW(path.as_ptr(), - dwDesiredAccess, - dwShareMode, - ptr::null_mut(), - dwCreationDisposition, - dwFlagsAndAttributes, - ptr::null_mut()) - }; - if handle == libc::INVALID_HANDLE_VALUE { - Err(super::last_error()) - } else { - let fd = unsafe { - libc::open_osfhandle(handle as libc::intptr_t, flags) - }; - if fd < 0 { - let _ = unsafe { libc::CloseHandle(handle) }; - Err(super::last_error()) - } else { - Ok(FileDesc::new(fd, true)) - } - } -} - -pub fn mkdir(p: &Path, _mode: usize) -> IoResult<()> { - let p = try!(to_utf16(p)); - super::mkerr_winbool(unsafe { - // FIXME: turn mode into something useful? #2623 - libc::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) - }) -} - -pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { - fn prune(root: &Path, dirs: Vec<Path>) -> Vec<Path> { - dirs.into_iter().filter(|path| { - path.as_vec() != b"." && path.as_vec() != b".." - }).map(|path| root.join(path)).collect() - } - - let star = p.join("*"); - let path = try!(to_utf16(&star)); - - unsafe { - let mut wfd = mem::zeroed(); - let find_handle = libc::FindFirstFileW(path.as_ptr(), &mut wfd); - if find_handle != libc::INVALID_HANDLE_VALUE { - let mut paths = vec![]; - let mut more_files = 1 as libc::BOOL; - while more_files != 0 { - { - let filename = super::truncate_utf16_at_nul(&wfd.cFileName); - match String::from_utf16(filename) { - Ok(filename) => paths.push(Path::new(filename)), - Err(..) => { - assert!(libc::FindClose(find_handle) != 0); - return Err(IoError { - kind: old_io::InvalidInput, - desc: "path was not valid UTF-16", - detail: Some(format!("path was not valid UTF-16: {:?}", filename)), - }) - }, // FIXME #12056: Convert the UCS-2 to invalid utf-8 instead of erroring - } - } - more_files = libc::FindNextFileW(find_handle, &mut wfd); - } - assert!(libc::FindClose(find_handle) != 0); - Ok(prune(p, paths)) - } else { - Err(super::last_error()) - } - } -} - -pub fn unlink(p: &Path) -> IoResult<()> { - fn do_unlink(p_utf16: &Vec<u16>) -> IoResult<()> { - super::mkerr_winbool(unsafe { libc::DeleteFileW(p_utf16.as_ptr()) }) - } - - let p_utf16 = try!(to_utf16(p)); - let res = do_unlink(&p_utf16); - match res { - Ok(()) => Ok(()), - Err(e) => { - // FIXME: change the code below to use more direct calls - // than `stat` and `chmod`, to avoid re-conversion to - // utf16 etc. - - // On unix, a readonly file can be successfully removed. On windows, - // however, it cannot. To keep the two platforms in line with - // respect to their behavior, catch this case on windows, attempt to - // change it to read-write, and then remove the file. - if e.kind == old_io::PermissionDenied { - let stat = match stat(p) { - Ok(stat) => stat, - Err(..) => return Err(e), - }; - if stat.perm.intersects(old_io::USER_WRITE) { return Err(e) } - - match chmod(p, (stat.perm | old_io::USER_WRITE).bits() as usize) { - Ok(()) => do_unlink(&p_utf16), - Err(..) => { - // Try to put it back as we found it - let _ = chmod(p, stat.perm.bits() as usize); - Err(e) - } - } - } else { - Err(e) - } - } - } -} - -pub fn rename(old: &Path, new: &Path) -> IoResult<()> { - let old = try!(to_utf16(old)); - let new = try!(to_utf16(new)); - super::mkerr_winbool(unsafe { - libc::MoveFileExW(old.as_ptr(), new.as_ptr(), libc::MOVEFILE_REPLACE_EXISTING) - }) -} - -pub fn chmod(p: &Path, mode: usize) -> IoResult<()> { - let p = try!(to_utf16(p)); - mkerr_libc(unsafe { - libc::wchmod(p.as_ptr(), mode as libc::c_int) - }) -} - -pub fn rmdir(p: &Path) -> IoResult<()> { - let p = try!(to_utf16(p)); - super::mkerr_winbool(unsafe { libc::RemoveDirectoryW(p.as_ptr()) }) -} - -pub fn chown(_p: &Path, _uid: isize, _gid: isize) -> IoResult<()> { - // libuv has this as a no-op, so seems like this should as well? - Ok(()) -} - -pub fn readlink(p: &Path) -> IoResult<Path> { - // FIXME: I have a feeling that this reads intermediate symlinks as well. - use sys::c::compat::kernel32::GetFinalPathNameByHandleW; - let p = try!(to_utf16(p)); - let handle = unsafe { - libc::CreateFileW(p.as_ptr(), - libc::GENERIC_READ, - libc::FILE_SHARE_READ, - ptr::null_mut(), - libc::OPEN_EXISTING, - libc::FILE_ATTRIBUTE_NORMAL, - ptr::null_mut()) - }; - if handle == libc::INVALID_HANDLE_VALUE { - return Err(super::last_error()) - } - // Specify (sz - 1) because the documentation states that it's the size - // without the null pointer - let ret = super::fill_utf16_buf(|buf, sz| unsafe { - GetFinalPathNameByHandleW(handle, - buf as *const u16, - sz - 1, - libc::VOLUME_NAME_DOS) - }, |data| { - Path::new(String::from_utf16(data).unwrap()) - }); - assert!(unsafe { libc::CloseHandle(handle) } != 0); - return ret; -} - -pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { - use sys::c::compat::kernel32::CreateSymbolicLinkW; - let src = try!(to_utf16(src)); - let dst = try!(to_utf16(dst)); - super::mkerr_winbool(unsafe { - CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), 0) as libc::BOOL - }) -} - -pub fn link(src: &Path, dst: &Path) -> IoResult<()> { - let src = try!(to_utf16(src)); - let dst = try!(to_utf16(dst)); - super::mkerr_winbool(unsafe { - libc::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) - }) -} - -fn mkstat(stat: &libc::stat) -> FileStat { - FileStat { - size: stat.st_size as u64, - kind: match (stat.st_mode as libc::c_int) & libc::S_IFMT { - libc::S_IFREG => old_io::FileType::RegularFile, - libc::S_IFDIR => old_io::FileType::Directory, - libc::S_IFIFO => old_io::FileType::NamedPipe, - libc::S_IFBLK => old_io::FileType::BlockSpecial, - libc::S_IFLNK => old_io::FileType::Symlink, - _ => old_io::FileType::Unknown, - }, - perm: FilePermission::from_bits_truncate(stat.st_mode as u32), - created: stat.st_ctime as u64, - modified: stat.st_mtime as u64, - accessed: stat.st_atime as u64, - unstable: UnstableFileStat { - device: stat.st_dev as u64, - inode: stat.st_ino as u64, - rdev: stat.st_rdev as u64, - nlink: stat.st_nlink as u64, - uid: stat.st_uid as u64, - gid: stat.st_gid as u64, - blksize:0, - blocks: 0, - flags: 0, - gen: 0, - }, - } -} - -pub fn stat(p: &Path) -> IoResult<FileStat> { - let mut stat: libc::stat = unsafe { mem::zeroed() }; - let p = try!(to_utf16(p)); - match unsafe { libc::wstat(p.as_ptr(), &mut stat) } { - 0 => Ok(mkstat(&stat)), - _ => Err(super::last_error()), - } -} - -// FIXME: move this to platform-specific modules (for now)? -pub fn lstat(_p: &Path) -> IoResult<FileStat> { - // FIXME: implementation is missing - Err(sys_common::unimpl()) -} - -pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> { - let mut buf = libc::utimbuf { - actime: atime as libc::time64_t, - modtime: mtime as libc::time64_t, - }; - let p = try!(to_utf16(p)); - mkerr_libc(unsafe { - libc::wutime(p.as_ptr(), &mut buf) - }) -} diff --git a/src/libstd/sys/windows/helper_signal.rs b/src/libstd/sys/windows/helper_signal.rs deleted file mode 100644 index a9fb2c68227..00000000000 --- a/src/libstd/sys/windows/helper_signal.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::{self, BOOL, LPCSTR, HANDLE, LPSECURITY_ATTRIBUTES, CloseHandle}; -use ptr; - -pub type signal = HANDLE; - -pub fn new() -> (HANDLE, HANDLE) { - unsafe { - let handle = CreateEventA(ptr::null_mut(), libc::FALSE, libc::FALSE, - ptr::null()); - (handle, handle) - } -} - -pub fn signal(handle: HANDLE) { - assert!(unsafe { SetEvent(handle) != 0 }); -} - -pub fn close(handle: HANDLE) { - assert!(unsafe { CloseHandle(handle) != 0 }); -} - -extern "system" { - fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: BOOL, - bInitialState: BOOL, - lpName: LPCSTR) -> HANDLE; - fn SetEvent(hEvent: HANDLE) -> BOOL; -} diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index e9d5fca531f..1171c6c068b 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -17,136 +17,31 @@ use prelude::v1::*; use ffi::{OsStr, OsString}; use io::{self, ErrorKind}; use libc; -use mem; #[allow(deprecated)] use num::Int; -use old_io::{self, IoResult, IoError}; use os::windows::ffi::{OsStrExt, OsStringExt}; use path::PathBuf; -use sync::{Once, ONCE_INIT}; pub mod backtrace; pub mod c; pub mod condvar; pub mod ext; -pub mod fs; pub mod fs2; pub mod handle; -pub mod helper_signal; pub mod mutex; pub mod net; pub mod os; pub mod os_str; -pub mod pipe; pub mod pipe2; -pub mod process; pub mod process2; pub mod rwlock; pub mod stack_overflow; pub mod sync; -pub mod tcp; pub mod thread; pub mod thread_local; pub mod time; -pub mod timer; -pub mod tty; -pub mod udp; pub mod stdio; -pub mod addrinfo { - pub use sys_common::net::get_host_addresses; - pub use sys_common::net::get_address_name; -} - -// FIXME: move these to c module -pub type sock_t = libc::SOCKET; -pub type wrlen = libc::c_int; -pub type msglen_t = libc::c_int; -pub unsafe fn close_sock(sock: sock_t) { let _ = libc::closesocket(sock); } - -// windows has zero values as errors -#[allow(deprecated)] -fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> { - if ret == 0 { - Err(last_error()) - } else { - Ok(()) - } -} - -#[allow(deprecated)] -pub fn last_error() -> IoError { - let errno = os::errno() as i32; - let mut err = decode_error(errno); - err.detail = Some(os::error_string(errno)); - err -} - -#[allow(deprecated)] -pub fn last_net_error() -> IoError { - let errno = unsafe { c::WSAGetLastError() as i32 }; - let mut err = decode_error(errno); - err.detail = Some(os::error_string(errno)); - err -} - -#[allow(deprecated)] -pub fn last_gai_error(_errno: i32) -> IoError { - last_net_error() -} - -/// Convert an `errno` value into a high-level error variant and description. -#[allow(deprecated)] -pub fn decode_error(errno: i32) -> IoError { - let (kind, desc) = match errno { - libc::EOF => (old_io::EndOfFile, "end of file"), - libc::ERROR_NO_DATA => (old_io::BrokenPipe, "the pipe is being closed"), - libc::ERROR_FILE_NOT_FOUND => (old_io::FileNotFound, "file not found"), - libc::ERROR_INVALID_NAME => (old_io::InvalidInput, "invalid file name"), - libc::WSAECONNREFUSED => (old_io::ConnectionRefused, "connection refused"), - libc::WSAECONNRESET => (old_io::ConnectionReset, "connection reset"), - libc::ERROR_ACCESS_DENIED | libc::WSAEACCES => - (old_io::PermissionDenied, "permission denied"), - libc::WSAEWOULDBLOCK => { - (old_io::ResourceUnavailable, "resource temporarily unavailable") - } - libc::WSAENOTCONN => (old_io::NotConnected, "not connected"), - libc::WSAECONNABORTED => (old_io::ConnectionAborted, "connection aborted"), - libc::WSAEADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"), - libc::WSAEADDRINUSE => (old_io::ConnectionRefused, "address in use"), - libc::ERROR_BROKEN_PIPE => (old_io::EndOfFile, "the pipe has ended"), - libc::ERROR_OPERATION_ABORTED => - (old_io::TimedOut, "operation timed out"), - libc::WSAEINVAL => (old_io::InvalidInput, "invalid argument"), - libc::ERROR_CALL_NOT_IMPLEMENTED => - (old_io::IoUnavailable, "function not implemented"), - libc::ERROR_INVALID_HANDLE => - (old_io::MismatchedFileTypeForOperation, - "invalid handle provided to function"), - libc::ERROR_NOTHING_TO_TERMINATE => - (old_io::InvalidInput, "no process to kill"), - libc::ERROR_ALREADY_EXISTS => - (old_io::PathAlreadyExists, "path already exists"), - - // libuv maps this error code to EISDIR. we do too. if it is found - // to be incorrect, we can add in some more machinery to only - // return this message when ERROR_INVALID_FUNCTION after certain - // Windows calls. - libc::ERROR_INVALID_FUNCTION => (old_io::InvalidInput, - "illegal operation on a directory"), - - _ => (old_io::OtherIoError, "unknown error") - }; - IoError { kind: kind, desc: desc, detail: None } -} - -#[allow(deprecated)] -pub fn decode_error_detailed(errno: i32) -> IoError { - let mut err = decode_error(errno); - err.detail = Some(os::error_string(errno)); - err -} - pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno as libc::c_int { libc::ERROR_ACCESS_DENIED => ErrorKind::PermissionDenied, @@ -170,58 +65,6 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { } } - -#[inline] -pub fn retry<I, F>(f: F) -> I where F: FnOnce() -> I { f() } // PR rust-lang/rust/#17020 - -pub fn ms_to_timeval(ms: u64) -> libc::timeval { - libc::timeval { - tv_sec: (ms / 1000) as libc::c_long, - tv_usec: ((ms % 1000) * 1000) as libc::c_long, - } -} - -#[allow(deprecated)] -pub fn wouldblock() -> bool { - let err = os::errno(); - err == libc::WSAEWOULDBLOCK as i32 -} - -#[allow(deprecated)] -pub fn set_nonblocking(fd: sock_t, nb: bool) { - let mut set = nb as libc::c_ulong; - if unsafe { c::ioctlsocket(fd, c::FIONBIO, &mut set) } != 0 { - // The above function should not return an error unless we passed it - // invalid parameters. Panic on errors. - panic!("set_nonblocking called with invalid parameters: {}", last_error()); - } -} - -pub fn init_net() { - unsafe { - static START: Once = ONCE_INIT; - - START.call_once(|| { - let mut data: c::WSADATA = mem::zeroed(); - let ret = c::WSAStartup(0x202, // version 2.2 - &mut data); - assert_eq!(ret, 0); - }); - } -} - -#[allow(deprecated)] -pub fn to_utf16(s: Option<&str>) -> IoResult<Vec<u16>> { - match s { - Some(s) => Ok(to_utf16_os(OsStr::from_str(s))), - None => Err(IoError { - kind: old_io::InvalidInput, - desc: "valid unicode input required", - detail: None, - }), - } -} - fn to_utf16_os(s: &OsStr) -> Vec<u16> { let mut v: Vec<_> = s.encode_wide().collect(); v.push(0); @@ -242,7 +85,7 @@ fn to_utf16_os(s: &OsStr) -> Vec<u16> { // Once the syscall has completed (errors bail out early) the second closure is // yielded the data which has been read from the syscall. The return value // from this closure is then the return value of the function. -fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()> +fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, F2: FnOnce(&[u16]) -> T { @@ -274,7 +117,7 @@ fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()> c::SetLastError(0); let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) { 0 if libc::GetLastError() == 0 => 0, - 0 => return Err(()), + 0 => return Err(io::Error::last_os_error()), n => n, } as usize; if k == n && libc::GetLastError() == @@ -289,21 +132,6 @@ fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()> } } -#[allow(deprecated)] -fn fill_utf16_buf<F1, F2, T>(f1: F1, f2: F2) -> IoResult<T> - where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, - F2: FnOnce(&[u16]) -> T -{ - fill_utf16_buf_base(f1, f2).map_err(|()| IoError::last_error()) -} - -fn fill_utf16_buf_new<F1, F2, T>(f1: F1, f2: F2) -> io::Result<T> - where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, - F2: FnOnce(&[u16]) -> T -{ - fill_utf16_buf_base(f1, f2).map_err(|()| io::Error::last_os_error()) -} - fn os2path(s: &[u16]) -> PathBuf { PathBuf::from(OsString::from_wide(s)) } diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index d5843a2f998..ebf5532b0ca 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -22,15 +22,12 @@ use io; use libc::types::os::arch::extra::LPWCH; use libc::{self, c_int, c_void}; use mem; -#[allow(deprecated)] -use old_io::{IoError, IoResult}; use ops::Range; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; use ptr; use slice; use sys::c; -use sys::fs::FileDesc; use sys::handle::Handle; use libc::funcs::extra::kernel32::{ @@ -233,13 +230,13 @@ impl StdError for JoinPathsError { } pub fn current_exe() -> io::Result<PathBuf> { - super::fill_utf16_buf_new(|buf, sz| unsafe { + super::fill_utf16_buf(|buf, sz| unsafe { libc::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { - super::fill_utf16_buf_new(|buf, sz| unsafe { + super::fill_utf16_buf(|buf, sz| unsafe { libc::GetCurrentDirectoryW(sz, buf) }, super::os2path) } @@ -259,7 +256,7 @@ pub fn chdir(p: &path::Path) -> io::Result<()> { pub fn getenv(k: &OsStr) -> Option<OsString> { let k = super::to_utf16_os(k); - super::fill_utf16_buf_new(|buf, sz| unsafe { + super::fill_utf16_buf(|buf, sz| unsafe { libc::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) @@ -336,27 +333,8 @@ pub fn page_size() -> usize { } } -#[allow(deprecated)] -pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> { - // Windows pipes work subtly differently than unix pipes, and their - // inheritance has to be handled in a different way that I do not - // fully understand. Here we explicitly make the pipe non-inheritable, - // which means to pass it to a subprocess they need to be duplicated - // first, as in std::run. - let mut fds = [0; 2]; - match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint, - (libc::O_BINARY | libc::O_NOINHERIT) as c_int) { - 0 => { - assert!(fds[0] != -1 && fds[0] != 0); - assert!(fds[1] != -1 && fds[1] != 0); - Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true))) - } - _ => Err(IoError::last_error()), - } -} - pub fn temp_dir() -> PathBuf { - super::fill_utf16_buf_new(|buf, sz| unsafe { + super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap() } @@ -371,7 +349,7 @@ pub fn home_dir() -> Option<PathBuf> { return None } let _handle = Handle::new(token); - super::fill_utf16_buf_new(|buf, mut sz| { + super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { 0 if libc::GetLastError() != 0 => 0, 0 => sz, diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs deleted file mode 100644 index 064c003bd15..00000000000 --- a/src/libstd/sys/windows/pipe.rs +++ /dev/null @@ -1,775 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Named pipes implementation for windows -//! -//! If are unfortunate enough to be reading this code, I would like to first -//! apologize. This was my first encounter with windows named pipes, and it -//! didn't exactly turn out very cleanly. If you, too, are new to named pipes, -//! read on as I'll try to explain some fun things that I ran into. -//! -//! # Unix pipes vs Named pipes -//! -//! As with everything else, named pipes on windows are pretty different from -//! unix pipes on unix. On unix, you use one "server pipe" to accept new client -//! pipes. So long as this server pipe is active, new children pipes can -//! connect. On windows, you instead have a number of "server pipes", and each -//! of these server pipes can throughout their lifetime be attached to a client -//! or not. Once attached to a client, a server pipe may then disconnect at a -//! later date. -//! -//! # Accepting clients -//! -//! As with most other I/O interfaces, our Listener/Acceptor/Stream interfaces -//! are built around the unix flavors. This means that we have one "server -//! pipe" to which many clients can connect. In order to make this compatible -//! with the windows model, each connected client consumes ownership of a server -//! pipe, and then a new server pipe is created for the next client. -//! -//! Note that the server pipes attached to clients are never given back to the -//! listener for recycling. This could possibly be implemented with a channel so -//! the listener half can re-use server pipes, but for now I err'd on the simple -//! side of things. Each stream accepted by a listener will destroy the server -//! pipe after the stream is dropped. -//! -//! This model ends up having a small race or two, and you can find more details -//! on the `native_accept` method. -//! -//! # Simultaneous reads and writes -//! -//! In testing, I found that two simultaneous writes and two simultaneous reads -//! on a pipe ended up working out just fine, but problems were encountered when -//! a read was executed simultaneously with a write. After some googling around, -//! it sounded like named pipes just weren't built for this kind of interaction, -//! and the suggested solution was to use overlapped I/O. -//! -//! I don't really know what overlapped I/O is, but my basic understanding after -//! reading about it is that you have an external Event which is used to signal -//! I/O completion, passed around in some OVERLAPPED structures. As to what this -//! is, I'm not exactly sure. -//! -//! This problem implies that all named pipes are created with the -//! FILE_FLAG_OVERLAPPED option. This means that all of their I/O is -//! asynchronous. Each I/O operation has an associated OVERLAPPED structure, and -//! inside of this structure is a HANDLE from CreateEvent. After the I/O is -//! determined to be pending (may complete in the future), the -//! GetOverlappedResult function is used to block on the event, waiting for the -//! I/O to finish. -//! -//! This scheme ended up working well enough. There were two snags that I ran -//! into, however: -//! -//! * Each UnixStream instance needs its own read/write events to wait on. These -//! can't be shared among clones of the same stream because the documentation -//! states that it unsets the event when the I/O is started (would possibly -//! corrupt other events simultaneously waiting). For convenience's sake, -//! these events are lazily initialized. -//! -//! * Each server pipe needs to be created with FILE_FLAG_OVERLAPPED in addition -//! to all pipes created through `connect`. Notably this means that the -//! ConnectNamedPipe function is nonblocking, implying that the Listener needs -//! to have yet another event to do the actual blocking. -//! -//! # Conclusion -//! -//! The conclusion here is that I probably don't know the best way to work with -//! windows named pipes, but the solution here seems to work well enough to get -//! the test suite passing (the suite is in libstd), and that's good enough for -//! me! - -#![allow(deprecated)] - -use prelude::v1::*; - -use libc; -use ffi::CString; -use old_io::{self, IoError, IoResult}; -use mem; -use ptr; -use str; -use sync::atomic::{AtomicBool, Ordering}; -use sync::{Arc, Mutex}; - -use sys_common::{self, eof}; - -use super::{c, os, timer, decode_error_detailed}; - -fn to_utf16(c: &CString) -> IoResult<Vec<u16>> { - super::to_utf16(str::from_utf8(c.as_bytes()).ok()) -} - -struct Event(libc::HANDLE); - -impl Event { - fn new(manual_reset: bool, initial_state: bool) -> IoResult<Event> { - let event = unsafe { - libc::CreateEventW(ptr::null_mut(), - manual_reset as libc::BOOL, - initial_state as libc::BOOL, - ptr::null()) - }; - if event as usize == 0 { - Err(super::last_error()) - } else { - Ok(Event(event)) - } - } - - fn handle(&self) -> libc::HANDLE { let Event(handle) = *self; handle } -} - -impl Drop for Event { - fn drop(&mut self) { - unsafe { let _ = libc::CloseHandle(self.handle()); } - } -} - -unsafe impl Send for Event {} -unsafe impl Sync for Event {} - -struct Inner { - handle: libc::HANDLE, - lock: Mutex<()>, - read_closed: AtomicBool, - write_closed: AtomicBool, -} - -impl Inner { - fn new(handle: libc::HANDLE) -> Inner { - Inner { - handle: handle, - lock: Mutex::new(()), - read_closed: AtomicBool::new(false), - write_closed: AtomicBool::new(false), - } - } -} - -impl Drop for Inner { - fn drop(&mut self) { - unsafe { - let _ = libc::FlushFileBuffers(self.handle); - let _ = libc::CloseHandle(self.handle); - } - } -} - -unsafe impl Send for Inner {} -unsafe impl Sync for Inner {} - -unsafe fn pipe(name: *const u16, init: bool) -> libc::HANDLE { - libc::CreateNamedPipeW( - name, - libc::PIPE_ACCESS_DUPLEX | - if init {libc::FILE_FLAG_FIRST_PIPE_INSTANCE} else {0} | - libc::FILE_FLAG_OVERLAPPED, - libc::PIPE_TYPE_BYTE | libc::PIPE_READMODE_BYTE | - libc::PIPE_WAIT, - libc::PIPE_UNLIMITED_INSTANCES, - 65536, - 65536, - 0, - ptr::null_mut() - ) -} - -pub fn await(handle: libc::HANDLE, deadline: u64, - events: &[libc::HANDLE]) -> IoResult<usize> { - use libc::consts::os::extra::{WAIT_FAILED, WAIT_TIMEOUT, WAIT_OBJECT_0}; - - // If we've got a timeout, use WaitForSingleObject in tandem with CancelIo - // to figure out if we should indeed get the result. - let ms = if deadline == 0 { - libc::INFINITE as u64 - } else { - let now = timer::now(); - if deadline < now {0} else {deadline - now} - }; - let ret = unsafe { - c::WaitForMultipleObjects(events.len() as libc::DWORD, - events.as_ptr(), - libc::FALSE, - ms as libc::DWORD) - }; - match ret { - WAIT_FAILED => Err(super::last_error()), - WAIT_TIMEOUT => unsafe { - let _ = c::CancelIo(handle); - Err(sys_common::timeout("operation timed out")) - }, - n => Ok((n - WAIT_OBJECT_0) as usize) - } -} - -fn epipe() -> IoError { - IoError { - kind: old_io::EndOfFile, - desc: "the pipe has ended", - detail: None, - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Unix Streams -//////////////////////////////////////////////////////////////////////////////// - -pub struct UnixStream { - inner: Arc<Inner>, - write: Option<Event>, - read: Option<Event>, - read_deadline: u64, - write_deadline: u64, -} - -impl UnixStream { - fn try_connect(p: *const u16) -> Option<libc::HANDLE> { - // Note that most of this is lifted from the libuv implementation. - // The idea is that if we fail to open a pipe in read/write mode - // that we try afterwards in just read or just write - let mut result = unsafe { - libc::CreateFileW(p, - libc::GENERIC_READ | libc::GENERIC_WRITE, - 0, - ptr::null_mut(), - libc::OPEN_EXISTING, - libc::FILE_FLAG_OVERLAPPED, - ptr::null_mut()) - }; - if result != libc::INVALID_HANDLE_VALUE { - return Some(result) - } - - let err = unsafe { libc::GetLastError() }; - if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { - result = unsafe { - libc::CreateFileW(p, - libc::GENERIC_READ | libc::FILE_WRITE_ATTRIBUTES, - 0, - ptr::null_mut(), - libc::OPEN_EXISTING, - libc::FILE_FLAG_OVERLAPPED, - ptr::null_mut()) - }; - if result != libc::INVALID_HANDLE_VALUE { - return Some(result) - } - } - let err = unsafe { libc::GetLastError() }; - if err == libc::ERROR_ACCESS_DENIED as libc::DWORD { - result = unsafe { - libc::CreateFileW(p, - libc::GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES, - 0, - ptr::null_mut(), - libc::OPEN_EXISTING, - libc::FILE_FLAG_OVERLAPPED, - ptr::null_mut()) - }; - if result != libc::INVALID_HANDLE_VALUE { - return Some(result) - } - } - None - } - - pub fn connect(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { - let addr = try!(to_utf16(addr)); - let start = timer::now(); - loop { - match UnixStream::try_connect(addr.as_ptr()) { - Some(handle) => { - let inner = Inner::new(handle); - let mut mode = libc::PIPE_TYPE_BYTE | - libc::PIPE_READMODE_BYTE | - libc::PIPE_WAIT; - let ret = unsafe { - libc::SetNamedPipeHandleState(inner.handle, - &mut mode, - ptr::null_mut(), - ptr::null_mut()) - }; - return if ret == 0 { - Err(super::last_error()) - } else { - Ok(UnixStream { - inner: Arc::new(inner), - read: None, - write: None, - read_deadline: 0, - write_deadline: 0, - }) - } - } - None => {} - } - - // On windows, if you fail to connect, you may need to call the - // `WaitNamedPipe` function, and this is indicated with an error - // code of ERROR_PIPE_BUSY. - let code = unsafe { libc::GetLastError() }; - if code as isize != libc::ERROR_PIPE_BUSY as isize { - return Err(super::last_error()) - } - - match timeout { - Some(timeout) => { - let now = timer::now(); - let timed_out = (now - start) >= timeout || unsafe { - let ms = (timeout - (now - start)) as libc::DWORD; - libc::WaitNamedPipeW(addr.as_ptr(), ms) == 0 - }; - if timed_out { - return Err(sys_common::timeout("connect timed out")) - } - } - - // An example I found on Microsoft's website used 20 - // seconds, libuv uses 30 seconds, hence we make the - // obvious choice of waiting for 25 seconds. - None => { - if unsafe { libc::WaitNamedPipeW(addr.as_ptr(), 25000) } == 0 { - return Err(super::last_error()) - } - } - } - } - } - - pub fn handle(&self) -> libc::HANDLE { self.inner.handle } - - fn read_closed(&self) -> bool { - self.inner.read_closed.load(Ordering::SeqCst) - } - - fn write_closed(&self) -> bool { - self.inner.write_closed.load(Ordering::SeqCst) - } - - fn cancel_io(&self) -> IoResult<()> { - match unsafe { c::CancelIoEx(self.handle(), ptr::null_mut()) } { - 0 if os::errno() == libc::ERROR_NOT_FOUND as i32 => { - Ok(()) - } - 0 => Err(super::last_error()), - _ => Ok(()) - } - } - - pub fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - if self.read.is_none() { - self.read = Some(try!(Event::new(true, false))); - } - - let mut bytes_read = 0; - let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; - overlapped.hEvent = self.read.as_ref().unwrap().handle(); - - // Pre-flight check to see if the reading half has been closed. This - // must be done before issuing the ReadFile request, but after we - // acquire the lock. - // - // See comments in close_read() about why this lock is necessary. - let guard = self.inner.lock.lock(); - if self.read_closed() { - return Err(eof()) - } - - // Issue a nonblocking requests, succeeding quickly if it happened to - // succeed. - let ret = unsafe { - libc::ReadFile(self.handle(), - buf.as_ptr() as libc::LPVOID, - buf.len() as libc::DWORD, - &mut bytes_read, - &mut overlapped) - }; - if ret != 0 { return Ok(bytes_read as usize) } - - // If our errno doesn't say that the I/O is pending, then we hit some - // legitimate error and return immediately. - if os::errno() != libc::ERROR_IO_PENDING as i32 { - return Err(super::last_error()) - } - - // Now that we've issued a successful nonblocking request, we need to - // wait for it to finish. This can all be done outside the lock because - // we'll see any invocation of CancelIoEx. We also call this in a loop - // because we're woken up if the writing half is closed, we just need to - // realize that the reading half wasn't closed and we go right back to - // sleep. - drop(guard); - loop { - // Process a timeout if one is pending - let wait_succeeded = await(self.handle(), self.read_deadline, - &[overlapped.hEvent]); - - let ret = unsafe { - libc::GetOverlappedResult(self.handle(), - &mut overlapped, - &mut bytes_read, - libc::TRUE) - }; - // If we succeeded, or we failed for some reason other than - // CancelIoEx, return immediately - if ret != 0 { return Ok(bytes_read as usize) } - if os::errno() != libc::ERROR_OPERATION_ABORTED as i32 { - return Err(super::last_error()) - } - - // If the reading half is now closed, then we're done. If we woke up - // because the writing half was closed, keep trying. - if wait_succeeded.is_err() { - return Err(sys_common::timeout("read timed out")) - } - if self.read_closed() { - return Err(eof()) - } - } - } - - pub fn write(&mut self, buf: &[u8]) -> IoResult<()> { - if self.write.is_none() { - self.write = Some(try!(Event::new(true, false))); - } - - let mut offset = 0; - let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; - overlapped.hEvent = self.write.as_ref().unwrap().handle(); - - while offset < buf.len() { - let mut bytes_written = 0; - - // This sequence below is quite similar to the one found in read(). - // Some careful looping is done to ensure that if close_write() is - // invoked we bail out early, and if close_read() is invoked we keep - // going after we woke up. - // - // See comments in close_read() about why this lock is necessary. - let guard = self.inner.lock.lock(); - if self.write_closed() { - return Err(epipe()) - } - let ret = unsafe { - libc::WriteFile(self.handle(), - buf[offset..].as_ptr() as libc::LPVOID, - (buf.len() - offset) as libc::DWORD, - &mut bytes_written, - &mut overlapped) - }; - let err = os::errno(); - drop(guard); - - if ret == 0 { - if err != libc::ERROR_IO_PENDING as i32 { - return Err(decode_error_detailed(err as i32)) - } - // Process a timeout if one is pending - let wait_succeeded = await(self.handle(), self.write_deadline, - &[overlapped.hEvent]); - let ret = unsafe { - libc::GetOverlappedResult(self.handle(), - &mut overlapped, - &mut bytes_written, - libc::TRUE) - }; - // If we weren't aborted, this was a legit error, if we were - // aborted, then check to see if the write half was actually - // closed or whether we woke up from the read half closing. - if ret == 0 { - if os::errno() != libc::ERROR_OPERATION_ABORTED as i32 { - return Err(super::last_error()) - } - if !wait_succeeded.is_ok() { - let amt = offset + bytes_written as usize; - return if amt > 0 { - Err(IoError { - kind: old_io::ShortWrite(amt), - desc: "short write during write", - detail: None, - }) - } else { - Err(sys_common::timeout("write timed out")) - } - } - if self.write_closed() { - return Err(epipe()) - } - continue // retry - } - } - offset += bytes_written as usize; - } - Ok(()) - } - - pub fn close_read(&mut self) -> IoResult<()> { - // On windows, there's no actual shutdown() method for pipes, so we're - // forced to emulate the behavior manually at the application level. To - // do this, we need to both cancel any pending requests, as well as - // prevent all future requests from succeeding. These two operations are - // not atomic with respect to one another, so we must use a lock to do - // so. - // - // The read() code looks like: - // - // 1. Make sure the pipe is still open - // 2. Submit a read request - // 3. Wait for the read request to finish - // - // The race this lock is preventing is if another thread invokes - // close_read() between steps 1 and 2. By atomically executing steps 1 - // and 2 with a lock with respect to close_read(), we're guaranteed that - // no thread will erroneously sit in a read forever. - let _guard = self.inner.lock.lock(); - self.inner.read_closed.store(true, Ordering::SeqCst); - self.cancel_io() - } - - pub fn close_write(&mut self) -> IoResult<()> { - // see comments in close_read() for why this lock is necessary - let _guard = self.inner.lock.lock(); - self.inner.write_closed.store(true, Ordering::SeqCst); - self.cancel_io() - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - self.read_deadline = deadline; - self.write_deadline = deadline; - } - pub fn set_read_timeout(&mut self, timeout: Option<u64>) { - self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } - pub fn set_write_timeout(&mut self, timeout: Option<u64>) { - self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } -} - -impl Clone for UnixStream { - fn clone(&self) -> UnixStream { - UnixStream { - inner: self.inner.clone(), - read: None, - write: None, - read_deadline: 0, - write_deadline: 0, - } - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Unix Listener -//////////////////////////////////////////////////////////////////////////////// - -pub struct UnixListener { - handle: libc::HANDLE, - name: CString, -} - -unsafe impl Send for UnixListener {} -unsafe impl Sync for UnixListener {} - -impl UnixListener { - pub fn bind(addr: &CString) -> IoResult<UnixListener> { - // Although we technically don't need the pipe until much later, we - // create the initial handle up front to test the validity of the name - // and such. - let addr_v = try!(to_utf16(addr)); - let ret = unsafe { pipe(addr_v.as_ptr(), true) }; - if ret == libc::INVALID_HANDLE_VALUE { - Err(super::last_error()) - } else { - Ok(UnixListener { handle: ret, name: addr.clone() }) - } - } - - pub fn listen(self) -> IoResult<UnixAcceptor> { - Ok(UnixAcceptor { - listener: self, - event: try!(Event::new(true, false)), - deadline: 0, - inner: Arc::new(AcceptorState { - abort: try!(Event::new(true, false)), - closed: AtomicBool::new(false), - }), - }) - } - - pub fn handle(&self) -> libc::HANDLE { - self.handle - } -} - -impl Drop for UnixListener { - fn drop(&mut self) { - unsafe { let _ = libc::CloseHandle(self.handle); } - } -} - -pub struct UnixAcceptor { - inner: Arc<AcceptorState>, - listener: UnixListener, - event: Event, - deadline: u64, -} - -struct AcceptorState { - abort: Event, - closed: AtomicBool, -} - -impl UnixAcceptor { - pub fn accept(&mut self) -> IoResult<UnixStream> { - // This function has some funky implementation details when working with - // unix pipes. On windows, each server named pipe handle can be - // connected to a one or zero clients. To the best of my knowledge, a - // named server is considered active and present if there exists at - // least one server named pipe for it. - // - // The model of this function is to take the current known server - // handle, connect a client to it, and then transfer ownership to the - // UnixStream instance. The next time accept() is invoked, it'll need a - // different server handle to connect a client to. - // - // Note that there is a possible race here. Once our server pipe is - // handed off to a `UnixStream` object, the stream could be closed, - // meaning that there would be no active server pipes, hence even though - // we have a valid `UnixAcceptor`, no one can connect to it. For this - // reason, we generate the next accept call's server pipe at the end of - // this function call. - // - // This provides us an invariant that we always have at least one server - // connection open at a time, meaning that all connects to this acceptor - // should succeed while this is active. - // - // The actual implementation of doing this is a little tricky. Once a - // server pipe is created, a client can connect to it at any time. I - // assume that which server a client connects to is nondeterministic, so - // we also need to guarantee that the only server able to be connected - // to is the one that we're calling ConnectNamedPipe on. This means that - // we have to create the second server pipe *after* we've already - // accepted a connection. In order to at least somewhat gracefully - // handle errors, this means that if the second server pipe creation - // fails that we disconnect the connected client and then just keep - // using the original server pipe. - let handle = self.listener.handle; - - // If we've had an artificial call to close_accept, be sure to never - // proceed in accepting new clients in the future - if self.inner.closed.load(Ordering::SeqCst) { return Err(eof()) } - - let name = try!(to_utf16(&self.listener.name)); - - // Once we've got a "server handle", we need to wait for a client to - // connect. The ConnectNamedPipe function will block this thread until - // someone on the other end connects. This function can "fail" if a - // client connects after we created the pipe but before we got down - // here. Thanks windows. - let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; - overlapped.hEvent = self.event.handle(); - if unsafe { libc::ConnectNamedPipe(handle, &mut overlapped) == 0 } { - let mut err = unsafe { libc::GetLastError() }; - - if err == libc::ERROR_IO_PENDING as libc::DWORD { - // Process a timeout if one is pending - let wait_succeeded = await(handle, self.deadline, - &[self.inner.abort.handle(), - overlapped.hEvent]); - - // This will block until the overlapped I/O is completed. The - // timeout was previously handled, so this will either block in - // the normal case or succeed very quickly in the timeout case. - let ret = unsafe { - let mut transfer = 0; - libc::GetOverlappedResult(handle, - &mut overlapped, - &mut transfer, - libc::TRUE) - }; - if ret == 0 { - if wait_succeeded.is_ok() { - err = unsafe { libc::GetLastError() }; - } else { - return Err(sys_common::timeout("accept timed out")) - } - } else { - // we succeeded, bypass the check below - err = libc::ERROR_PIPE_CONNECTED as libc::DWORD; - } - } - if err != libc::ERROR_PIPE_CONNECTED as libc::DWORD { - return Err(super::last_error()) - } - } - - // Now that we've got a connected client to our handle, we need to - // create a second server pipe. If this fails, we disconnect the - // connected client and return an error (see comments above). - let new_handle = unsafe { pipe(name.as_ptr(), false) }; - if new_handle == libc::INVALID_HANDLE_VALUE { - let ret = Err(super::last_error()); - // If our disconnection fails, then there's not really a whole lot - // that we can do, so panic - let err = unsafe { libc::DisconnectNamedPipe(handle) }; - assert!(err != 0); - return ret; - } else { - self.listener.handle = new_handle; - } - - // Transfer ownership of our handle into this stream - Ok(UnixStream { - inner: Arc::new(Inner::new(handle)), - read: None, - write: None, - read_deadline: 0, - write_deadline: 0, - }) - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - self.deadline = timeout.map(|i| i + timer::now()).unwrap_or(0); - } - - pub fn close_accept(&mut self) -> IoResult<()> { - self.inner.closed.store(true, Ordering::SeqCst); - let ret = unsafe { - c::SetEvent(self.inner.abort.handle()) - }; - if ret == 0 { - Err(super::last_error()) - } else { - Ok(()) - } - } - - pub fn handle(&self) -> libc::HANDLE { - self.listener.handle() - } -} - -impl Clone for UnixAcceptor { - fn clone(&self) -> UnixAcceptor { - let name = to_utf16(&self.listener.name).unwrap(); - UnixAcceptor { - inner: self.inner.clone(), - event: Event::new(true, false).unwrap(), - deadline: 0, - listener: UnixListener { - name: self.listener.name.clone(), - handle: unsafe { - let p = pipe(name.as_ptr(), false) ; - assert!(p != libc::INVALID_HANDLE_VALUE as libc::HANDLE); - p - }, - }, - } - } -} diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs deleted file mode 100644 index b10042090dd..00000000000 --- a/src/libstd/sys/windows/process.rs +++ /dev/null @@ -1,518 +0,0 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] // this module itself is essentially deprecated - -use prelude::v1::*; - -use collections; -use env; -use ffi::CString; -use hash::Hash; -use libc::{pid_t, c_void}; -use libc; -use mem; -#[allow(deprecated)] use old_io::fs::PathExtensions; -use old_io::process::{ProcessExit, ExitStatus}; -use old_io::{IoResult, IoError}; -use old_io; -use fs::PathExt; -use old_path::{BytesContainer, GenericPath}; -use ptr; -use str; -use sync::{StaticMutex, MUTEX_INIT}; -use sys::fs::FileDesc; -use sys::timer; -use sys_common::{AsInner, timeout}; - -pub use sys_common::ProcessConfig; - -// `CreateProcess` is racy! -// http://support.microsoft.com/kb/315939 -static CREATE_PROCESS_LOCK: StaticMutex = MUTEX_INIT; - -/// A value representing a child process. -/// -/// The lifetime of this value is linked to the lifetime of the actual -/// process - the Process destructor calls self.finish() which waits -/// for the process to terminate. -pub struct Process { - /// The unique id of the process (this should never be negative). - pid: pid_t, - - /// A HANDLE to the process, which will prevent the pid being - /// re-used until the handle is closed. - handle: *mut (), -} - -impl Drop for Process { - fn drop(&mut self) { - free_handle(self.handle); - } -} - -impl Process { - pub fn id(&self) -> pid_t { - self.pid - } - - pub unsafe fn kill(&self, signal: isize) -> IoResult<()> { - Process::killpid(self.pid, signal) - } - - pub unsafe fn killpid(pid: pid_t, signal: isize) -> IoResult<()> { - let handle = libc::OpenProcess(libc::PROCESS_TERMINATE | - libc::PROCESS_QUERY_INFORMATION, - libc::FALSE, pid as libc::DWORD); - if handle.is_null() { - return Err(super::last_error()) - } - let ret = match signal { - // test for existence on signal 0 - 0 => { - let mut status = 0; - let ret = libc::GetExitCodeProcess(handle, &mut status); - if ret == 0 { - Err(super::last_error()) - } else if status != libc::STILL_ACTIVE { - Err(IoError { - kind: old_io::InvalidInput, - desc: "no process to kill", - detail: None, - }) - } else { - Ok(()) - } - } - 15 | 9 => { // sigterm or sigkill - let ret = libc::TerminateProcess(handle, 1); - super::mkerr_winbool(ret) - } - _ => Err(IoError { - kind: old_io::IoUnavailable, - desc: "unsupported signal on windows", - detail: None, - }) - }; - let _ = libc::CloseHandle(handle); - return ret; - } - - #[allow(deprecated)] - pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>, - out_fd: Option<P>, err_fd: Option<P>) - -> IoResult<Process> - where C: ProcessConfig<K, V>, P: AsInner<FileDesc>, - K: BytesContainer + Eq + Hash, V: BytesContainer - { - use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO}; - use libc::consts::os::extra::{ - TRUE, FALSE, - STARTF_USESTDHANDLES, - INVALID_HANDLE_VALUE, - DUPLICATE_SAME_ACCESS - }; - use libc::funcs::extra::kernel32::{ - GetCurrentProcess, - DuplicateHandle, - CloseHandle, - CreateProcessW - }; - use libc::funcs::extra::msvcrt::get_osfhandle; - - use mem; - - if cfg.gid().is_some() || cfg.uid().is_some() { - return Err(IoError { - kind: old_io::IoUnavailable, - desc: "unsupported gid/uid requested on windows", - detail: None, - }) - } - - // To have the spawning semantics of unix/windows stay the same, we need to - // read the *child's* PATH if one is provided. See #15149 for more details. - let program = cfg.env().and_then(|env| { - for (key, v) in env { - if b"PATH" != key.container_as_bytes() { continue } - let v = match ::str::from_utf8(v.container_as_bytes()) { - Ok(s) => s, - Err(..) => continue, - }; - - // Split the value and test each path to see if the - // program exists. - for path in ::env::split_paths(v) { - let program = str::from_utf8(cfg.program().as_bytes()).unwrap(); - let path = path.join(program) - .with_extension(env::consts::EXE_EXTENSION); - if path.exists() { - return Some(CString::new(path.to_str().unwrap()).unwrap()) - } - } - break - } - None - }); - - unsafe { - let mut si = zeroed_startupinfo(); - si.cb = mem::size_of::<STARTUPINFO>() as DWORD; - si.dwFlags = STARTF_USESTDHANDLES; - - let cur_proc = GetCurrentProcess(); - - // Similarly to unix, we don't actually leave holes for the stdio file - // descriptors, but rather open up /dev/null equivalents. These - // equivalents are drawn from libuv's windows process spawning. - let set_fd = |fd: &Option<P>, slot: &mut HANDLE, - is_stdin: bool| { - match *fd { - None => { - let access = if is_stdin { - libc::FILE_GENERIC_READ - } else { - libc::FILE_GENERIC_WRITE | libc::FILE_READ_ATTRIBUTES - }; - let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>(); - let mut sa = libc::SECURITY_ATTRIBUTES { - nLength: size as libc::DWORD, - lpSecurityDescriptor: ptr::null_mut(), - bInheritHandle: 1, - }; - let mut filename: Vec<u16> = "NUL".utf16_units().collect(); - filename.push(0); - *slot = libc::CreateFileW(filename.as_ptr(), - access, - libc::FILE_SHARE_READ | - libc::FILE_SHARE_WRITE, - &mut sa, - libc::OPEN_EXISTING, - 0, - ptr::null_mut()); - if *slot == INVALID_HANDLE_VALUE { - return Err(super::last_error()) - } - } - Some(ref fd) => { - let orig = get_osfhandle(fd.as_inner().fd()) as HANDLE; - if orig == INVALID_HANDLE_VALUE { - return Err(super::last_error()) - } - if DuplicateHandle(cur_proc, orig, cur_proc, slot, - 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE { - return Err(super::last_error()) - } - } - } - Ok(()) - }; - - try!(set_fd(&in_fd, &mut si.hStdInput, true)); - try!(set_fd(&out_fd, &mut si.hStdOutput, false)); - try!(set_fd(&err_fd, &mut si.hStdError, false)); - - let cmd_str = make_command_line(program.as_ref().unwrap_or(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 cfg.detach() { - flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP; - } - - with_envp(cfg.env(), |envp| { - with_dirp(cfg.cwd(), |dirp| { - let mut cmd_str: Vec<u16> = cmd_str.utf16_units().collect(); - cmd_str.push(0); - let _lock = CREATE_PROCESS_LOCK.lock().unwrap(); - let created = CreateProcessW(ptr::null(), - cmd_str.as_mut_ptr(), - ptr::null_mut(), - ptr::null_mut(), - TRUE, - flags, envp, dirp, - &mut si, &mut pi); - if created == FALSE { - create_err = Some(super::last_error()); - } - }) - }); - - assert!(CloseHandle(si.hStdInput) != 0); - assert!(CloseHandle(si.hStdOutput) != 0); - assert!(CloseHandle(si.hStdError) != 0); - - match create_err { - Some(err) => return Err(err), - None => {} - } - - // We close the thread handle because we don't care about keeping the - // thread id valid, and we aren't keeping the thread handle around to be - // able to close it later. We don't close the process handle however - // because std::we want the process id to stay valid at least until the - // calling code closes the process handle. - assert!(CloseHandle(pi.hThread) != 0); - - Ok(Process { - pid: pi.dwProcessId as pid_t, - handle: pi.hProcess as *mut () - }) - } - } - - /// Waits for a process to exit and returns the exit code, failing - /// if there is no process with the specified id. - /// - /// Note that this is private to avoid race conditions on unix where if - /// a user calls waitpid(some_process.get_id()) then some_process.finish() - /// and some_process.destroy() and some_process.finalize() will then either - /// operate on a none-existent process or, even worse, on a newer process - /// with the same id. - pub fn wait(&self, deadline: u64) -> IoResult<ProcessExit> { - use libc::types::os::arch::extra::DWORD; - use libc::consts::os::extra::{ - SYNCHRONIZE, - PROCESS_QUERY_INFORMATION, - FALSE, - STILL_ACTIVE, - INFINITE, - WAIT_TIMEOUT, - WAIT_OBJECT_0, - }; - use libc::funcs::extra::kernel32::{ - OpenProcess, - GetExitCodeProcess, - CloseHandle, - WaitForSingleObject, - }; - - unsafe { - let process = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, - FALSE, - self.pid as DWORD); - if process.is_null() { - return Err(super::last_error()) - } - - loop { - let mut status = 0; - if GetExitCodeProcess(process, &mut status) == FALSE { - let err = Err(super::last_error()); - assert!(CloseHandle(process) != 0); - return err; - } - if status != STILL_ACTIVE { - assert!(CloseHandle(process) != 0); - return Ok(ExitStatus(status as isize)); - } - let interval = if deadline == 0 { - INFINITE - } else { - let now = timer::now(); - if deadline < now {0} else {(deadline - now) as u32} - }; - match WaitForSingleObject(process, interval) { - WAIT_OBJECT_0 => {} - WAIT_TIMEOUT => { - assert!(CloseHandle(process) != 0); - return Err(timeout("process wait timed out")) - } - _ => { - let err = Err(super::last_error()); - assert!(CloseHandle(process) != 0); - return err - } - } - } - } - } -} - -fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO { - libc::types::os::arch::extra::STARTUPINFO { - cb: 0, - lpReserved: ptr::null_mut(), - lpDesktop: ptr::null_mut(), - lpTitle: ptr::null_mut(), - dwX: 0, - dwY: 0, - dwXSize: 0, - dwYSize: 0, - dwXCountChars: 0, - dwYCountCharts: 0, - dwFillAttribute: 0, - dwFlags: 0, - wShowWindow: 0, - cbReserved2: 0, - lpReserved2: ptr::null_mut(), - hStdInput: libc::INVALID_HANDLE_VALUE, - hStdOutput: libc::INVALID_HANDLE_VALUE, - hStdError: libc::INVALID_HANDLE_VALUE, - } -} - -fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION { - libc::types::os::arch::extra::PROCESS_INFORMATION { - hProcess: ptr::null_mut(), - hThread: ptr::null_mut(), - dwProcessId: 0, - dwThreadId: 0 - } -} - -fn make_command_line(prog: &CString, args: &[CString]) -> String { - let mut cmd = String::new(); - append_arg(&mut cmd, str::from_utf8(prog.as_bytes()).ok() - .expect("expected program name to be utf-8 encoded")); - for arg in args { - cmd.push(' '); - append_arg(&mut cmd, str::from_utf8(arg.as_bytes()).ok() - .expect("expected argument to be utf-8 encoded")); - } - return cmd; - - fn append_arg(cmd: &mut String, arg: &str) { - // If an argument has 0 characters then we need to quote it to ensure - // that it actually gets passed through on the command line or otherwise - // it will be dropped entirely when parsed on the other end. - let quote = arg.chars().any(|c| c == ' ' || c == '\t') || arg.len() == 0; - if quote { - cmd.push('"'); - } - let argvec: Vec<char> = arg.chars().collect(); - for i in 0..argvec.len() { - append_char_at(cmd, &argvec, i); - } - if quote { - cmd.push('"'); - } - } - - fn append_char_at(cmd: &mut String, arg: &[char], i: usize) { - match arg[i] { - '"' => { - // Escape quotes. - cmd.push_str("\\\""); - } - '\\' => { - if backslash_run_ends_in_quote(arg, i) { - // Double all backslashes that are in runs before quotes. - cmd.push_str("\\\\"); - } else { - // Pass other backslashes through unescaped. - cmd.push('\\'); - } - } - c => { - cmd.push(c); - } - } - } - - fn backslash_run_ends_in_quote(s: &[char], mut i: usize) -> bool { - while i < s.len() && s[i] == '\\' { - i += 1; - } - return i < s.len() && s[i] == '"'; - } -} - -fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T - where K: BytesContainer + Eq + Hash, - V: BytesContainer, - F: FnOnce(*mut c_void) -> T, -{ - // On Windows 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. - match env { - Some(env) => { - let mut blk = Vec::new(); - - for pair in env { - let kv = format!("{}={}", - pair.0.container_as_str().unwrap(), - pair.1.container_as_str().unwrap()); - blk.extend(kv.utf16_units()); - blk.push(0); - } - - blk.push(0); - - cb(blk.as_mut_ptr() as *mut c_void) - } - _ => cb(ptr::null_mut()) - } -} - -fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where - F: FnOnce(*const u16) -> T, -{ - match d { - Some(dir) => { - let dir_str = str::from_utf8(dir.as_bytes()).ok() - .expect("expected workingdirectory to be utf-8 encoded"); - let mut dir_str: Vec<u16> = dir_str.utf16_units().collect(); - dir_str.push(0); - cb(dir_str.as_ptr()) - }, - None => cb(ptr::null()) - } -} - -fn free_handle(handle: *mut ()) { - assert!(unsafe { - libc::CloseHandle(mem::transmute(handle)) != 0 - }) -} - -#[cfg(test)] -mod tests { - use prelude::v1::*; - use str; - use ffi::CString; - use super::make_command_line; - - #[test] - fn test_make_command_line() { - fn test_wrapper(prog: &str, args: &[&str]) -> String { - make_command_line(&CString::new(prog).unwrap(), - &args.iter() - .map(|a| CString::new(*a).unwrap()) - .collect::<Vec<CString>>()) - } - - assert_eq!( - test_wrapper("prog", &["aaa", "bbb", "ccc"]), - "prog aaa bbb ccc" - ); - - assert_eq!( - test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]), - "\"C:\\Program Files\\blah\\blah.exe\" aaa" - ); - assert_eq!( - test_wrapper("C:\\Program Files\\test", &["aa\"bb"]), - "\"C:\\Program Files\\test\" aa\\\"bb" - ); - assert_eq!( - test_wrapper("echo", &["a b c"]), - "echo \"a b c\"" - ); - assert_eq!( - test_wrapper("\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}", &[]), - "\u{03c0}\u{042f}\u{97f3}\u{00e6}\u{221e}" - ); - } -} diff --git a/src/libstd/sys/windows/tcp.rs b/src/libstd/sys/windows/tcp.rs deleted file mode 100644 index 41e97dc8475..00000000000 --- a/src/libstd/sys/windows/tcp.rs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(deprecated)] - -use prelude::v1::*; - -use old_io::net::ip; -use old_io::IoResult; -use libc; -use libc::consts::os::extra::INVALID_SOCKET; -use mem; -use ptr; -use super::{last_error, last_net_error, sock_t}; -use sync::Arc; -use sync::atomic::{AtomicBool, Ordering}; -use sys::{self, c, set_nonblocking, wouldblock, timer}; -use sys_common::{timeout, eof, net}; - -pub use sys_common::net::TcpStream; - -pub struct Event(c::WSAEVENT); - -unsafe impl Send for Event {} -unsafe impl Sync for Event {} - -impl Event { - pub fn new() -> IoResult<Event> { - let event = unsafe { c::WSACreateEvent() }; - if event == c::WSA_INVALID_EVENT { - Err(super::last_error()) - } else { - Ok(Event(event)) - } - } - - pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle } -} - -impl Drop for Event { - fn drop(&mut self) { - unsafe { let _ = c::WSACloseEvent(self.handle()); } - } -} - -//////////////////////////////////////////////////////////////////////////////// -// TCP listeners -//////////////////////////////////////////////////////////////////////////////// - -pub struct TcpListener { sock: sock_t } - -unsafe impl Send for TcpListener {} -unsafe impl Sync for TcpListener {} - -impl TcpListener { - pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> { - sys::init_net(); - - let sock = try!(net::socket(addr, libc::SOCK_STREAM)); - let ret = TcpListener { sock: sock }; - - let mut storage = unsafe { mem::zeroed() }; - let len = net::addr_to_sockaddr(addr, &mut storage); - let addrp = &storage as *const _ as *const libc::sockaddr; - - match unsafe { libc::bind(sock, addrp, len) } { - -1 => Err(last_net_error()), - _ => Ok(ret), - } - } - - pub fn socket(&self) -> sock_t { self.sock } - - pub fn listen(self, backlog: isize) -> IoResult<TcpAcceptor> { - match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } { - -1 => Err(last_net_error()), - - _ => { - let accept = try!(Event::new()); - let ret = unsafe { - c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT) - }; - if ret != 0 { - return Err(last_net_error()) - } - Ok(TcpAcceptor { - inner: Arc::new(AcceptorInner { - listener: self, - abort: try!(Event::new()), - accept: accept, - closed: AtomicBool::new(false), - }), - deadline: 0, - }) - } - } - } - - pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> { - net::sockname(self.socket(), libc::getsockname) - } -} - -impl Drop for TcpListener { - fn drop(&mut self) { - unsafe { super::close_sock(self.sock); } - } -} - -pub struct TcpAcceptor { - inner: Arc<AcceptorInner>, - deadline: u64, -} - -struct AcceptorInner { - listener: TcpListener, - abort: Event, - accept: Event, - closed: AtomicBool, -} - -unsafe impl Sync for AcceptorInner {} - -impl TcpAcceptor { - pub fn socket(&self) -> sock_t { self.inner.listener.socket() } - - pub fn accept(&mut self) -> IoResult<TcpStream> { - // Unlink unix, windows cannot invoke `select` on arbitrary file - // descriptors like pipes, only sockets. Consequently, windows cannot - // use the same implementation as unix for accept() when close_accept() - // is considered. - // - // In order to implement close_accept() and timeouts, windows uses - // event handles. An acceptor-specific abort event is created which - // will only get set in close_accept(), and it will never be un-set. - // Additionally, another acceptor-specific event is associated with the - // FD_ACCEPT network event. - // - // These two events are then passed to WaitForMultipleEvents to see - // which one triggers first, and the timeout passed to this function is - // the local timeout for the acceptor. - // - // If the wait times out, then the accept timed out. If the wait - // succeeds with the abort event, then we were closed, and if the wait - // succeeds otherwise, then we do a nonblocking poll via `accept` to - // see if we can accept a connection. The connection is candidate to be - // stolen, so we do all of this in a loop as well. - let events = [self.inner.abort.handle(), self.inner.accept.handle()]; - - while !self.inner.closed.load(Ordering::SeqCst) { - let ms = if self.deadline == 0 { - c::WSA_INFINITE as u64 - } else { - let now = timer::now(); - if self.deadline < now {0} else {self.deadline - now} - }; - let ret = unsafe { - c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE, - ms as libc::DWORD, libc::FALSE) - }; - match ret { - c::WSA_WAIT_TIMEOUT => { - return Err(timeout("accept timed out")) - } - c::WSA_WAIT_FAILED => return Err(last_net_error()), - c::WSA_WAIT_EVENT_0 => break, - n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1), - } - - let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() }; - let ret = unsafe { - c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents) - }; - if ret != 0 { return Err(last_net_error()) } - - if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue } - match unsafe { - libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut()) - } { - INVALID_SOCKET if wouldblock() => {} - INVALID_SOCKET => return Err(last_net_error()), - - // Accepted sockets inherit the same properties as the caller, - // so we need to deregister our event and switch the socket back - // to blocking mode - socket => { - let stream = TcpStream::new(socket); - let ret = unsafe { - c::WSAEventSelect(socket, events[1], 0) - }; - if ret != 0 { return Err(last_net_error()) } - set_nonblocking(socket, false); - return Ok(stream) - } - } - } - - Err(eof()) - } - - pub fn set_timeout(&mut self, timeout: Option<u64>) { - self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); - } - - pub fn close_accept(&mut self) -> IoResult<()> { - self.inner.closed.store(true, Ordering::SeqCst); - let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) }; - if ret == libc::TRUE { - Ok(()) - } else { - Err(last_net_error()) - } - } -} - -impl Clone for TcpAcceptor { - fn clone(&self) -> TcpAcceptor { - TcpAcceptor { - inner: self.inner.clone(), - deadline: 0, - } - } -} diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs deleted file mode 100644 index 8856cc26b2e..00000000000 --- a/src/libstd/sys/windows/timer.rs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Timers based on Windows WaitableTimers -//! -//! This implementation is meant to be used solely on windows. As with other -//! implementations, there is a worker thread which is doing all the waiting on -//! a large number of timers for all active timers in the system. This worker -//! thread uses the select() equivalent, WaitForMultipleObjects. One of the -//! objects being waited on is a signal into the worker thread to notify that -//! the incoming channel should be looked at. -//! -//! Other than that, the implementation is pretty straightforward in terms of -//! the other two implementations of timers with nothing *that* new showing up. - -#![allow(deprecated)] - -use prelude::v1::*; -use self::Req::*; - -use libc; -use ptr; - -use old_io::IoResult; -use sys_common::helper_thread::Helper; -use sync::mpsc::{channel, TryRecvError, Sender, Receiver}; - -helper_init! { static HELPER: Helper<Req> } - -pub trait Callback { - fn call(&mut self); -} - -pub struct Timer { - obj: libc::HANDLE, - on_worker: bool, -} - -pub enum Req { - NewTimer(libc::HANDLE, Box<Callback + Send>, bool), - RemoveTimer(libc::HANDLE, Sender<()>), -} - -unsafe impl Send for Timer {} -unsafe impl Send for Req {} - -fn helper(input: libc::HANDLE, messages: Receiver<Req>, _: ()) { - let mut objs = vec![input]; - let mut chans = vec![]; - - 'outer: loop { - let idx = unsafe { - imp::WaitForMultipleObjects(objs.len() as libc::DWORD, - objs.as_ptr(), - 0 as libc::BOOL, - libc::INFINITE) - }; - - if idx == 0 { - loop { - match messages.try_recv() { - Ok(NewTimer(obj, c, one)) => { - objs.push(obj); - chans.push((c, one)); - } - Ok(RemoveTimer(obj, c)) => { - c.send(()).unwrap(); - match objs.iter().position(|&o| o == obj) { - Some(i) => { - drop(objs.remove(i)); - drop(chans.remove(i - 1)); - } - None => {} - } - } - // See the comment in unix::timer for why we don't have any - // asserts here and why we're likely just leaving timers on - // the floor as we exit. - Err(TryRecvError::Disconnected) => { - break 'outer; - } - Err(..) => break - } - } - } else { - let remove = { - match &mut chans[idx as usize - 1] { - &mut (ref mut c, oneshot) => { c.call(); oneshot } - } - }; - if remove { - drop(objs.remove(idx as usize)); - drop(chans.remove(idx as usize - 1)); - } - } - } -} - -// returns the current time (in milliseconds) -pub fn now() -> u64 { - let mut ticks_per_s = 0; - assert_eq!(unsafe { libc::QueryPerformanceFrequency(&mut ticks_per_s) }, 1); - let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s}; - let mut ticks = 0; - assert_eq!(unsafe { libc::QueryPerformanceCounter(&mut ticks) }, 1); - - return (ticks as u64 * 1000) / (ticks_per_s as u64); -} - -impl Timer { - pub fn new() -> IoResult<Timer> { - HELPER.boot(|| {}, helper); - - let obj = unsafe { - imp::CreateWaitableTimerA(ptr::null_mut(), 0, ptr::null()) - }; - if obj.is_null() { - Err(super::last_error()) - } else { - Ok(Timer { obj: obj, on_worker: false, }) - } - } - - fn remove(&mut self) { - if !self.on_worker { return } - - let (tx, rx) = channel(); - HELPER.send(RemoveTimer(self.obj, tx)); - rx.recv().unwrap(); - - self.on_worker = false; - } - - pub fn sleep(&mut self, msecs: u64) { - self.remove(); - - // there are 10^6 nanoseconds in a millisecond, and the parameter is in - // 100ns intervals, so we multiply by 10^4. - let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; - assert_eq!(unsafe { - imp::SetWaitableTimer(self.obj, &due, 0, ptr::null_mut(), - ptr::null_mut(), 0) - }, 1); - - let _ = unsafe { imp::WaitForSingleObject(self.obj, libc::INFINITE) }; - } - - pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) { - self.remove(); - - // see above for the calculation - let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; - assert_eq!(unsafe { - imp::SetWaitableTimer(self.obj, &due, 0, ptr::null_mut(), - ptr::null_mut(), 0) - }, 1); - - HELPER.send(NewTimer(self.obj, cb, true)); - self.on_worker = true; - } - - pub fn period(&mut self, msecs: u64, cb: Box<Callback + Send>) { - self.remove(); - - // see above for the calculation - let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; - assert_eq!(unsafe { - imp::SetWaitableTimer(self.obj, &due, msecs as libc::LONG, - ptr::null_mut(), ptr::null_mut(), 0) - }, 1); - - HELPER.send(NewTimer(self.obj, cb, false)); - self.on_worker = true; - } -} - -impl Drop for Timer { - fn drop(&mut self) { - self.remove(); - assert!(unsafe { libc::CloseHandle(self.obj) != 0 }); - } -} - -mod imp { - use libc::{LPSECURITY_ATTRIBUTES, BOOL, LPCSTR, HANDLE, LARGE_INTEGER, - LONG, LPVOID, DWORD, c_void}; - - pub type PTIMERAPCROUTINE = *mut c_void; - - extern "system" { - pub fn CreateWaitableTimerA(lpTimerAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: BOOL, - lpTimerName: LPCSTR) -> HANDLE; - pub fn SetWaitableTimer(hTimer: HANDLE, - pDueTime: *const LARGE_INTEGER, - lPeriod: LONG, - pfnCompletionRoutine: PTIMERAPCROUTINE, - lpArgToCompletionRoutine: LPVOID, - fResume: BOOL) -> BOOL; - pub fn WaitForMultipleObjects(nCount: DWORD, - lpHandles: *const HANDLE, - bWaitAll: BOOL, - dwMilliseconds: DWORD) -> DWORD; - pub fn WaitForSingleObject(hHandle: HANDLE, - dwMilliseconds: DWORD) -> DWORD; - } -} diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs deleted file mode 100644 index 791c7532bd0..00000000000 --- a/src/libstd/sys/windows/tty.rs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-lexer-test FIXME #15877 - -//! Windows specific console TTY implementation -//! -//! This module contains the implementation of a Windows specific console TTY. -//! Also converts between UTF-16 and UTF-8. Windows has very poor support for -//! UTF-8 and some functions will panic. In particular ReadFile and ReadConsole -//! will panic when the codepage is set to UTF-8 and a Unicode character is -//! entered. -//! -//! FIXME -//! This implementation does not account for codepoints that are split across -//! multiple reads and writes. Also, this implementation does not expose a way -//! to read/write UTF-16 directly. When/if Rust receives a Reader/Writer -//! wrapper that performs encoding/decoding, this implementation should switch -//! to working in raw UTF-16, with such a wrapper around it. - -#![allow(deprecated)] - -use prelude::v1::*; - -use old_io::{self, IoError, IoResult, MemReader, Reader}; -use iter::repeat; -use libc::types::os::arch::extra::LPCVOID; -use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID}; -use libc::{get_osfhandle, CloseHandle}; -use mem; -use ptr; -use str::from_utf8; -use super::c::{ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS}; -use super::c::{ENABLE_INSERT_MODE, ENABLE_LINE_INPUT}; -use super::c::{ENABLE_PROCESSED_INPUT, ENABLE_QUICK_EDIT_MODE}; -use super::c::CONSOLE_SCREEN_BUFFER_INFO; -use super::c::{ReadConsoleW, WriteConsoleW, GetConsoleMode, SetConsoleMode}; -use super::c::GetConsoleScreenBufferInfo; - -fn invalid_encoding() -> IoError { - IoError { - kind: old_io::InvalidInput, - desc: "text was not valid unicode", - detail: None, - } -} - -pub fn is_tty(fd: c_int) -> bool { - let mut out: DWORD = 0; - // If this function doesn't return an error, then fd is a TTY - match unsafe { GetConsoleMode(get_osfhandle(fd) as HANDLE, - &mut out as LPDWORD) } { - 0 => false, - _ => true, - } -} - -pub struct TTY { - closeme: bool, - handle: HANDLE, - utf8: MemReader, -} - -impl TTY { - pub fn new(fd: c_int) -> IoResult<TTY> { - if is_tty(fd) { - // If the file descriptor is one of stdin, stderr, or stdout - // then it should not be closed by us - let closeme = match fd { - 0...2 => false, - _ => true, - }; - let handle = unsafe { get_osfhandle(fd) as HANDLE }; - Ok(TTY { - handle: handle, - utf8: MemReader::new(Vec::new()), - closeme: closeme, - }) - } else { - Err(IoError { - kind: old_io::MismatchedFileTypeForOperation, - desc: "invalid handle provided to function", - detail: None, - }) - } - } - - pub fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { - // Read more if the buffer is empty - if self.utf8.eof() { - let mut utf16: Vec<u16> = repeat(0u16).take(0x1000).collect(); - let mut num: DWORD = 0; - match unsafe { ReadConsoleW(self.handle, - utf16.as_mut_ptr() as LPVOID, - utf16.len() as u32, - &mut num as LPDWORD, - ptr::null_mut()) } { - 0 => return Err(super::last_error()), - _ => (), - }; - utf16.truncate(num as usize); - let utf8 = match String::from_utf16(&utf16) { - Ok(utf8) => utf8.into_bytes(), - Err(..) => return Err(invalid_encoding()), - }; - self.utf8 = MemReader::new(utf8); - } - // MemReader shouldn't error here since we just filled it - Ok(self.utf8.read(buf).unwrap()) - } - - pub fn write(&mut self, buf: &[u8]) -> IoResult<()> { - let utf16 = match from_utf8(buf).ok() { - Some(utf8) => { - utf8.utf16_units().collect::<Vec<u16>>() - } - None => return Err(invalid_encoding()), - }; - let mut num: DWORD = 0; - match unsafe { WriteConsoleW(self.handle, - utf16.as_ptr() as LPCVOID, - utf16.len() as u32, - &mut num as LPDWORD, - ptr::null_mut()) } { - 0 => Err(super::last_error()), - _ => Ok(()), - } - } - - pub fn set_raw(&mut self, raw: bool) -> IoResult<()> { - // FIXME - // Somebody needs to decide on which of these flags we want - match unsafe { SetConsoleMode(self.handle, - match raw { - true => 0, - false => ENABLE_ECHO_INPUT | ENABLE_EXTENDED_FLAGS | - ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | - ENABLE_PROCESSED_INPUT | ENABLE_QUICK_EDIT_MODE, - }) } { - 0 => Err(super::last_error()), - _ => Ok(()), - } - } - - pub fn get_winsize(&mut self) -> IoResult<(isize, isize)> { - let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { mem::zeroed() }; - match unsafe { GetConsoleScreenBufferInfo(self.handle, &mut info as *mut _) } { - 0 => Err(super::last_error()), - _ => Ok(((info.srWindow.Right + 1 - info.srWindow.Left) as isize, - (info.srWindow.Bottom + 1 - info.srWindow.Top) as isize)), - } - } -} - -impl Drop for TTY { - fn drop(&mut self) { - if self.closeme { - // Nobody cares about the return value - let _ = unsafe { CloseHandle(self.handle) }; - } - } -} diff --git a/src/libstd/sys/windows/udp.rs b/src/libstd/sys/windows/udp.rs deleted file mode 100644 index 50f8fb828ad..00000000000 --- a/src/libstd/sys/windows/udp.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -pub use sys_common::net::UdpSocket; |
