rust/src/libnative/io/mod.rs

293 lines
8.8 KiB
Rust
Raw Normal View History

// 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.
//! Native thread-blocking I/O implementation
//!
//! This module contains the implementation of native thread-blocking
//! implementations of I/O on all platforms. This module is not intended to be
//! used directly, but rather the rust runtime will fall back to using it if
//! necessary.
//!
//! Rust code normally runs inside of green tasks with a local scheduler using
//! asynchronous I/O to cooperate among tasks. This model is not always
//! available, however, and that's where these native implementations come into
//! play. The only dependencies of these modules are the normal system libraries
//! that you would find on the respective platform.
use libc::c_int;
use libc;
use std::c_str::CString;
use std::io;
use std::io::IoError;
use std::io::net::ip::SocketAddr;
use std::io::signal::Signum;
use std::os;
use std::rt::rtio;
use std::rt::rtio::{RtioTcpStream, RtioTcpListener, RtioUdpSocket};
use std::rt::rtio::{RtioUnixListener, RtioPipe, RtioFileStream, RtioProcess};
use std::rt::rtio::{RtioSignal, RtioTTY, CloseBehavior, RtioTimer, ProcessConfig};
use ai = std::io::net::addrinfo;
// Local re-exports
pub use self::file::FileDesc;
pub use self::process::Process;
mod helper_thread;
// Native I/O implementations
pub mod addrinfo;
2013-12-27 19:50:16 -06:00
pub mod net;
pub mod process;
mod util;
#[cfg(unix)]
#[path = "file_unix.rs"]
pub mod file;
#[cfg(windows)]
#[path = "file_win32.rs"]
pub mod file;
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "android")]
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
#[cfg(target_os = "linux")]
#[path = "timer_unix.rs"]
Implement native timers Native timers are a much hairier thing to deal with than green timers due to the interface that we would like to expose (both a blocking sleep() and a channel-based interface). I ended up implementing timers in three different ways for the various platforms that we supports. In all three of the implementations, there is a worker thread which does send()s on channels for timers. This worker thread is initialized once and then communicated to in a platform-specific manner, but there's always a shared channel available for sending messages to the worker thread. * Windows - I decided to use windows kernel timer objects via CreateWaitableTimer and SetWaitableTimer in order to provide sleeping capabilities. The worker thread blocks via WaitForMultipleObjects where one of the objects is an event that is used to wake up the helper thread (which then drains the incoming message channel for requests). * Linux/(Android?) - These have the ideal interface for implementing timers, timerfd_create. Each timer corresponds to a timerfd, and the helper thread uses epoll to wait for all active timers and then send() for the next one that wakes up. The tricky part in this implementation is updating a timerfd, but see the implementation for the fun details * OSX/FreeBSD - These obviously don't have the windows APIs, and sadly don't have the timerfd api available to them, so I have thrown together a solution which uses select() plus a timeout in order to ad-hoc-ly implement a timer solution for threads. The implementation is backed by a sorted array of timers which need to fire. As I said, this is an ad-hoc solution which is certainly not accurate timing-wise. I have done this implementation due to the lack of other primitives to provide an implementation, and I've done it the best that I could, but I'm sure that there's room for improvement. I'm pretty happy with how these implementations turned out. In theory we could drop the timerfd implementation and have linux use the select() + timeout implementation, but it's so inaccurate that I would much rather continue to use timerfd rather than my ad-hoc select() implementation. The only change that I would make to the API in general is to have a generic sleep() method on an IoFactory which doesn't require allocating a Timer object. For everything but windows it's super-cheap to request a blocking sleep for a set amount of time, and it's probably worth it to provide a sleep() which doesn't do something like allocate a file descriptor on linux.
2013-12-29 01:33:56 -06:00
pub mod timer;
#[cfg(target_os = "win32")]
#[path = "timer_win32.rs"]
pub mod timer;
#[cfg(unix)]
#[path = "pipe_unix.rs"]
pub mod pipe;
#[cfg(windows)]
#[path = "pipe_win32.rs"]
pub mod pipe;
#[cfg(unix)] #[path = "c_unix.rs"] mod c;
#[cfg(windows)] #[path = "c_win32.rs"] mod c;
pub type IoResult<T> = Result<T, IoError>;
fn unimpl() -> IoError {
IoError {
kind: io::IoUnavailable,
desc: "unimplemented I/O interface",
detail: None,
}
}
fn last_error() -> IoError {
IoError::last_error()
}
// unix has nonzero values as errors
fn mkerr_libc(ret: libc::c_int) -> IoResult<()> {
if ret != 0 {
Err(last_error())
} else {
Ok(())
}
}
// windows has zero values as errors
2013-12-08 01:55:28 -06:00
#[cfg(windows)]
fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> {
if ret == 0 {
Err(last_error())
} else {
Ok(())
}
}
#[cfg(windows)]
#[inline]
fn retry(f: || -> libc::c_int) -> libc::c_int {
loop {
match f() {
-1 if os::errno() as int == libc::WSAEINTR as int => {}
n => return n,
}
}
}
#[cfg(unix)]
#[inline]
fn retry(f: || -> libc::c_int) -> libc::c_int {
loop {
match f() {
-1 if os::errno() as int == libc::EINTR as int => {}
n => return n,
}
}
}
fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 {
let origamt = data.len();
let mut data = data.as_ptr();
let mut amt = origamt;
while amt > 0 {
let ret = retry(|| f(data, amt) as libc::c_int);
if ret == 0 {
break
} else if ret != -1 {
amt -= ret as uint;
data = unsafe { data.offset(ret as int) };
} else {
return ret as i64;
}
}
return (origamt - amt) as i64;
}
/// Implementation of rt::rtio's IoFactory trait to generate handles to the
/// native I/O functionality.
2013-12-27 19:50:16 -06:00
pub struct IoFactory {
cannot_construct_outside_of_this_module: ()
2013-12-27 19:50:16 -06:00
}
impl IoFactory {
pub fn new() -> IoFactory {
net::init();
IoFactory { cannot_construct_outside_of_this_module: () }
}
}
impl rtio::IoFactory for IoFactory {
// networking
fn tcp_connect(&mut self, addr: SocketAddr,
timeout: Option<u64>) -> IoResult<Box<RtioTcpStream:Send>> {
net::TcpStream::connect(addr, timeout).map(|s| {
box s as Box<RtioTcpStream:Send>
})
}
fn tcp_bind(&mut self, addr: SocketAddr)
-> IoResult<Box<RtioTcpListener:Send>> {
net::TcpListener::bind(addr).map(|s| {
box s as Box<RtioTcpListener:Send>
})
}
fn udp_bind(&mut self, addr: SocketAddr)
-> IoResult<Box<RtioUdpSocket:Send>> {
net::UdpSocket::bind(addr).map(|u| box u as Box<RtioUdpSocket:Send>)
}
fn unix_bind(&mut self, path: &CString)
-> IoResult<Box<RtioUnixListener:Send>> {
pipe::UnixListener::bind(path).map(|s| {
box s as Box<RtioUnixListener:Send>
})
}
fn unix_connect(&mut self, path: &CString,
timeout: Option<u64>) -> IoResult<Box<RtioPipe:Send>> {
pipe::UnixStream::connect(path, timeout).map(|s| {
box s as Box<RtioPipe:Send>
})
}
fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
hint: Option<ai::Hint>) -> IoResult<Vec<ai::Info>> {
addrinfo::GetAddrInfoRequest::run(host, servname, hint)
}
// filesystem operations
fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior)
-> Box<RtioFileStream:Send> {
let close = match close {
rtio::CloseSynchronously | rtio::CloseAsynchronously => true,
rtio::DontClose => false
};
box file::FileDesc::new(fd, close) as Box<RtioFileStream:Send>
}
fn fs_open(&mut self, path: &CString, fm: io::FileMode, fa: io::FileAccess)
-> IoResult<Box<RtioFileStream:Send>> {
file::open(path, fm, fa).map(|fd| box fd as Box<RtioFileStream:Send>)
}
fn fs_unlink(&mut self, path: &CString) -> IoResult<()> {
file::unlink(path)
}
fn fs_stat(&mut self, path: &CString) -> IoResult<io::FileStat> {
file::stat(path)
}
fn fs_mkdir(&mut self, path: &CString,
mode: io::FilePermission) -> IoResult<()> {
file::mkdir(path, mode)
}
fn fs_chmod(&mut self, path: &CString,
mode: io::FilePermission) -> IoResult<()> {
file::chmod(path, mode)
}
fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> {
file::rmdir(path)
}
fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> {
file::rename(path, to)
}
fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<Path>> {
file::readdir(path)
}
fn fs_lstat(&mut self, path: &CString) -> IoResult<io::FileStat> {
file::lstat(path)
}
fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> {
file::chown(path, uid, gid)
}
fn fs_readlink(&mut self, path: &CString) -> IoResult<Path> {
file::readlink(path)
}
fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
file::symlink(src, dst)
}
fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
file::link(src, dst)
}
fn fs_utime(&mut self, src: &CString, atime: u64,
mtime: u64) -> IoResult<()> {
file::utime(src, atime, mtime)
}
// misc
fn timer_init(&mut self) -> IoResult<Box<RtioTimer:Send>> {
timer::Timer::new().map(|t| box t as Box<RtioTimer:Send>)
}
fn spawn(&mut self, cfg: ProcessConfig)
-> IoResult<(Box<RtioProcess:Send>,
Vec<Option<Box<RtioPipe:Send>>>)> {
process::Process::spawn(cfg).map(|(p, io)| {
(box p as Box<RtioProcess:Send>,
io.move_iter().map(|p| p.map(|p| {
box p as Box<RtioPipe:Send>
})).collect())
})
}
fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> {
process::Process::kill(pid, signum)
}
fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<RtioPipe:Send>> {
Ok(box file::FileDesc::new(fd, true) as Box<RtioPipe:Send>)
}
fn tty_open(&mut self, fd: c_int, _readable: bool)
-> IoResult<Box<RtioTTY:Send>> {
if unsafe { libc::isatty(fd) } != 0 {
Ok(box file::FileDesc::new(fd, true) as Box<RtioTTY:Send>)
} else {
Err(IoError {
kind: io::MismatchedFileTypeForOperation,
desc: "file descriptor is not a TTY",
detail: None,
})
}
}
fn signal(&mut self, _signal: Signum, _channel: Sender<Signum>)
-> IoResult<Box<RtioSignal:Send>> {
Err(unimpl())
}
}