std: Remove old_io/old_path/rand modules
This commit entirely removes the old I/O, path, and rand modules. All functionality has been deprecated and unstable for quite some time now!
This commit is contained in:
parent
dabf0c6371
commit
bf4e77d4b5
57 changed files with 60 additions and 22827 deletions
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue