]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Add support for the Haiku operating system on x86 and x86_64 machines
[rust.git] / src / libstd / sys / unix / fd.rs
1 // Copyright 2015 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 #![unstable(reason = "not public", issue = "0", feature = "fd")]
12
13 use io::{self, Read};
14 use libc::{self, c_int, size_t, c_void};
15 use mem;
16 use sync::atomic::{AtomicBool, Ordering};
17 use sys::cvt;
18 use sys_common::AsInner;
19 use sys_common::io::read_to_end_uninitialized;
20
21 pub struct FileDesc {
22     fd: c_int,
23 }
24
25 impl FileDesc {
26     pub fn new(fd: c_int) -> FileDesc {
27         FileDesc { fd: fd }
28     }
29
30     pub fn raw(&self) -> c_int { self.fd }
31
32     /// Extracts the actual filedescriptor without closing it.
33     pub fn into_raw(self) -> c_int {
34         let fd = self.fd;
35         mem::forget(self);
36         fd
37     }
38
39     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
40         let ret = cvt(unsafe {
41             libc::read(self.fd,
42                        buf.as_mut_ptr() as *mut c_void,
43                        buf.len() as size_t)
44         })?;
45         Ok(ret as usize)
46     }
47
48     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
49         let mut me = self;
50         (&mut me).read_to_end(buf)
51     }
52
53     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
54         let ret = cvt(unsafe {
55             libc::write(self.fd,
56                         buf.as_ptr() as *const c_void,
57                         buf.len() as size_t)
58         })?;
59         Ok(ret as usize)
60     }
61
62     #[cfg(not(any(target_env = "newlib", target_os = "solaris", target_os = "emscripten")))]
63     pub fn set_cloexec(&self) -> io::Result<()> {
64         unsafe {
65             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
66             Ok(())
67         }
68     }
69     #[cfg(any(target_env = "newlib", target_os = "solaris", target_os = "emscripten"))]
70     pub fn set_cloexec(&self) -> io::Result<()> {
71         unsafe {
72             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
73             cvt(libc::fcntl(self.fd, libc::F_SETFD, previous | libc::FD_CLOEXEC))?;
74             Ok(())
75         }
76     }
77
78     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
79         unsafe {
80             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
81             let new = if nonblocking {
82                 previous | libc::O_NONBLOCK
83             } else {
84                 previous & !libc::O_NONBLOCK
85             };
86             cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
87             Ok(())
88         }
89     }
90
91     pub fn duplicate(&self) -> io::Result<FileDesc> {
92         // We want to atomically duplicate this file descriptor and set the
93         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
94         // flag, however, isn't supported on older Linux kernels (earlier than
95         // 2.6.24).
96         //
97         // To detect this and ensure that CLOEXEC is still set, we
98         // follow a strategy similar to musl [1] where if passing
99         // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
100         // supported (the third parameter, 0, is always valid), so we stop
101         // trying that.
102         //
103         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
104         // resolve so we at least compile this.
105         //
106         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
107         #[cfg(any(target_os = "android", target_os = "haiku"))]
108         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
109         #[cfg(not(any(target_os = "android", target_os="haiku")))]
110         use libc::F_DUPFD_CLOEXEC;
111
112         let make_filedesc = |fd| {
113             let fd = FileDesc::new(fd);
114             fd.set_cloexec()?;
115             Ok(fd)
116         };
117         static TRY_CLOEXEC: AtomicBool =
118             AtomicBool::new(!cfg!(target_os = "android"));
119         let fd = self.raw();
120         if TRY_CLOEXEC.load(Ordering::Relaxed) {
121             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
122                 // We *still* call the `set_cloexec` method as apparently some
123                 // linux kernel at some point stopped setting CLOEXEC even
124                 // though it reported doing so on F_DUPFD_CLOEXEC.
125                 Ok(fd) => {
126                     return Ok(if cfg!(target_os = "linux") {
127                         make_filedesc(fd)?
128                     } else {
129                         FileDesc::new(fd)
130                     })
131                 }
132                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
133                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
134                 }
135                 Err(e) => return Err(e),
136             }
137         }
138         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
139     }
140 }
141
142 impl<'a> Read for &'a FileDesc {
143     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
144         (**self).read(buf)
145     }
146
147     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
148         unsafe { read_to_end_uninitialized(self, buf) }
149     }
150 }
151
152 impl AsInner<c_int> for FileDesc {
153     fn as_inner(&self) -> &c_int { &self.fd }
154 }
155
156 impl Drop for FileDesc {
157     fn drop(&mut self) {
158         // Note that errors are ignored when closing a file descriptor. The
159         // reason for this is that if an error occurs we don't actually know if
160         // the file descriptor was closed or not, and if we retried (for
161         // something like EINTR), we might close another valid file descriptor
162         // (opened after we closed ours.
163         let _ = unsafe { libc::close(self.fd) };
164     }
165 }