]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/mod.rs
native: Deal with the rtio changes
[rust.git] / src / libnative / io / mod.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Native thread-blocking I/O implementation
12 //!
13 //! This module contains the implementation of native thread-blocking
14 //! implementations of I/O on all platforms. This module is not intended to be
15 //! used directly, but rather the rust runtime will fall back to using it if
16 //! necessary.
17 //!
18 //! Rust code normally runs inside of green tasks with a local scheduler using
19 //! asynchronous I/O to cooperate among tasks. This model is not always
20 //! available, however, and that's where these native implementations come into
21 //! play. The only dependencies of these modules are the normal system libraries
22 //! that you would find on the respective platform.
23
24 #![allow(non_snake_case_functions)]
25
26 use libc::c_int;
27 use libc;
28 use std::c_str::CString;
29 use std::os;
30 use std::rt::rtio;
31 use std::rt::rtio::{IoResult, IoError};
32
33 // Local re-exports
34 pub use self::file::FileDesc;
35 pub use self::process::Process;
36
37 mod helper_thread;
38
39 // Native I/O implementations
40 pub mod addrinfo;
41 pub mod net;
42 pub mod process;
43 mod util;
44
45 #[cfg(unix)]
46 #[path = "file_unix.rs"]
47 pub mod file;
48 #[cfg(windows)]
49 #[path = "file_win32.rs"]
50 pub mod file;
51
52 #[cfg(target_os = "macos")]
53 #[cfg(target_os = "freebsd")]
54 #[cfg(target_os = "android")]
55 #[cfg(target_os = "linux")]
56 #[path = "timer_unix.rs"]
57 pub mod timer;
58
59 #[cfg(target_os = "win32")]
60 #[path = "timer_win32.rs"]
61 pub mod timer;
62
63 #[cfg(unix)]
64 #[path = "pipe_unix.rs"]
65 pub mod pipe;
66
67 #[cfg(windows)]
68 #[path = "pipe_win32.rs"]
69 pub mod pipe;
70
71 #[cfg(unix)]    #[path = "c_unix.rs"]  mod c;
72 #[cfg(windows)] #[path = "c_win32.rs"] mod c;
73
74 fn unimpl() -> IoError {
75     #[cfg(unix)] use ERROR = libc::ENOSYS;
76     #[cfg(windows)] use ERROR = libc::ERROR_CALL_NOT_IMPLEMENTED;
77     IoError {
78         code: ERROR as uint,
79         extra: 0,
80         detail: None,
81     }
82 }
83
84 fn last_error() -> IoError {
85     let errno = os::errno() as uint;
86     IoError {
87         code: os::errno() as uint,
88         extra: 0,
89         detail: Some(os::error_string(errno)),
90     }
91 }
92
93 // unix has nonzero values as errors
94 fn mkerr_libc(ret: libc::c_int) -> IoResult<()> {
95     if ret != 0 {
96         Err(last_error())
97     } else {
98         Ok(())
99     }
100 }
101
102 // windows has zero values as errors
103 #[cfg(windows)]
104 fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> {
105     if ret == 0 {
106         Err(last_error())
107     } else {
108         Ok(())
109     }
110 }
111
112 #[cfg(windows)]
113 #[inline]
114 fn retry(f: || -> libc::c_int) -> libc::c_int {
115     loop {
116         match f() {
117             -1 if os::errno() as int == libc::WSAEINTR as int => {}
118             n => return n,
119         }
120     }
121 }
122
123 #[cfg(unix)]
124 #[inline]
125 fn retry(f: || -> libc::c_int) -> libc::c_int {
126     loop {
127         match f() {
128             -1 if os::errno() as int == libc::EINTR as int => {}
129             n => return n,
130         }
131     }
132 }
133
134 fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 {
135     let origamt = data.len();
136     let mut data = data.as_ptr();
137     let mut amt = origamt;
138     while amt > 0 {
139         let ret = retry(|| f(data, amt) as libc::c_int);
140         if ret == 0 {
141             break
142         } else if ret != -1 {
143             amt -= ret as uint;
144             data = unsafe { data.offset(ret as int) };
145         } else {
146             return ret as i64;
147         }
148     }
149     return (origamt - amt) as i64;
150 }
151
152 /// Implementation of rt::rtio's IoFactory trait to generate handles to the
153 /// native I/O functionality.
154 pub struct IoFactory {
155     cannot_construct_outside_of_this_module: ()
156 }
157
158 impl IoFactory {
159     pub fn new() -> IoFactory {
160         net::init();
161         IoFactory { cannot_construct_outside_of_this_module: () }
162     }
163 }
164
165 impl rtio::IoFactory for IoFactory {
166     // networking
167     fn tcp_connect(&mut self, addr: rtio::SocketAddr,
168                    timeout: Option<u64>)
169         -> IoResult<Box<rtio::RtioTcpStream:Send>>
170     {
171         net::TcpStream::connect(addr, timeout).map(|s| {
172             box s as Box<rtio::RtioTcpStream:Send>
173         })
174     }
175     fn tcp_bind(&mut self, addr: rtio::SocketAddr)
176                 -> IoResult<Box<rtio::RtioTcpListener:Send>> {
177         net::TcpListener::bind(addr).map(|s| {
178             box s as Box<rtio::RtioTcpListener:Send>
179         })
180     }
181     fn udp_bind(&mut self, addr: rtio::SocketAddr)
182                 -> IoResult<Box<rtio::RtioUdpSocket:Send>> {
183         net::UdpSocket::bind(addr).map(|u| {
184             box u as Box<rtio::RtioUdpSocket:Send>
185         })
186     }
187     fn unix_bind(&mut self, path: &CString)
188                  -> IoResult<Box<rtio::RtioUnixListener:Send>> {
189         pipe::UnixListener::bind(path).map(|s| {
190             box s as Box<rtio::RtioUnixListener:Send>
191         })
192     }
193     fn unix_connect(&mut self, path: &CString,
194                     timeout: Option<u64>) -> IoResult<Box<rtio::RtioPipe:Send>> {
195         pipe::UnixStream::connect(path, timeout).map(|s| {
196             box s as Box<rtio::RtioPipe:Send>
197         })
198     }
199     fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
200                           hint: Option<rtio::AddrinfoHint>)
201         -> IoResult<Vec<rtio::AddrinfoInfo>>
202     {
203         addrinfo::GetAddrInfoRequest::run(host, servname, hint)
204     }
205
206     // filesystem operations
207     fn fs_from_raw_fd(&mut self, fd: c_int, close: rtio::CloseBehavior)
208                       -> Box<rtio::RtioFileStream:Send> {
209         let close = match close {
210             rtio::CloseSynchronously | rtio::CloseAsynchronously => true,
211             rtio::DontClose => false
212         };
213         box file::FileDesc::new(fd, close) as Box<rtio::RtioFileStream:Send>
214     }
215     fn fs_open(&mut self, path: &CString, fm: rtio::FileMode,
216                fa: rtio::FileAccess)
217         -> IoResult<Box<rtio::RtioFileStream:Send>>
218     {
219         file::open(path, fm, fa).map(|fd| box fd as Box<rtio::RtioFileStream:Send>)
220     }
221     fn fs_unlink(&mut self, path: &CString) -> IoResult<()> {
222         file::unlink(path)
223     }
224     fn fs_stat(&mut self, path: &CString) -> IoResult<rtio::FileStat> {
225         file::stat(path)
226     }
227     fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()> {
228         file::mkdir(path, mode)
229     }
230     fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()> {
231         file::chmod(path, mode)
232     }
233     fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> {
234         file::rmdir(path)
235     }
236     fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> {
237         file::rename(path, to)
238     }
239     fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<CString>> {
240         file::readdir(path)
241     }
242     fn fs_lstat(&mut self, path: &CString) -> IoResult<rtio::FileStat> {
243         file::lstat(path)
244     }
245     fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> {
246         file::chown(path, uid, gid)
247     }
248     fn fs_readlink(&mut self, path: &CString) -> IoResult<CString> {
249         file::readlink(path)
250     }
251     fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
252         file::symlink(src, dst)
253     }
254     fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
255         file::link(src, dst)
256     }
257     fn fs_utime(&mut self, src: &CString, atime: u64,
258                 mtime: u64) -> IoResult<()> {
259         file::utime(src, atime, mtime)
260     }
261
262     // misc
263     fn timer_init(&mut self) -> IoResult<Box<rtio::RtioTimer:Send>> {
264         timer::Timer::new().map(|t| box t as Box<rtio::RtioTimer:Send>)
265     }
266     fn spawn(&mut self, cfg: rtio::ProcessConfig)
267             -> IoResult<(Box<rtio::RtioProcess:Send>,
268                          Vec<Option<Box<rtio::RtioPipe:Send>>>)> {
269         process::Process::spawn(cfg).map(|(p, io)| {
270             (box p as Box<rtio::RtioProcess:Send>,
271              io.move_iter().map(|p| p.map(|p| {
272                  box p as Box<rtio::RtioPipe:Send>
273              })).collect())
274         })
275     }
276     fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> {
277         process::Process::kill(pid, signum)
278     }
279     fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<rtio::RtioPipe:Send>> {
280         Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioPipe:Send>)
281     }
282     fn tty_open(&mut self, fd: c_int, _readable: bool)
283                 -> IoResult<Box<rtio::RtioTTY:Send>> {
284         #[cfg(unix)] use ERROR = libc::ENOTTY;
285         #[cfg(windows)] use ERROR = libc::ERROR_INVALID_HANDLE;
286         if unsafe { libc::isatty(fd) } != 0 {
287             Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioTTY:Send>)
288         } else {
289             Err(IoError {
290                 code: ERROR as uint,
291                 extra: 0,
292                 detail: None,
293             })
294         }
295     }
296     fn signal(&mut self, _signal: int, _cb: Box<rtio::Callback>)
297               -> IoResult<Box<rtio::RtioSignal:Send>> {
298         Err(unimpl())
299     }
300 }