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.
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.
11 #![unstable(reason = "not public", issue = "0", feature = "fd")]
15 use libc::{self, c_int, c_void, ssize_t};
17 use sync::atomic::{AtomicBool, Ordering};
19 use sys_common::AsInner;
20 use sys_common::io::read_to_end_uninitialized;
27 fn max_len() -> usize {
28 // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
29 // with the man page quoting that if the count of bytes to read is
30 // greater than `SSIZE_MAX` the result is "unspecified".
32 // On macOS, however, apparently the 64-bit libc is either buggy or
33 // intentionally showing odd behavior by rejecting any read with a size
34 // larger than or equal to INT_MAX. To handle both of these the read
35 // size is capped on both platforms.
36 if cfg!(target_os = "macos") {
37 <c_int>::max_value() as usize - 1
39 <ssize_t>::max_value() as usize
44 pub fn new(fd: c_int) -> FileDesc {
48 pub fn raw(&self) -> c_int { self.fd }
50 /// Extracts the actual filedescriptor without closing it.
51 pub fn into_raw(self) -> c_int {
57 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
58 let ret = cvt(unsafe {
60 buf.as_mut_ptr() as *mut c_void,
61 cmp::min(buf.len(), max_len()))
66 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
68 (&mut me).read_to_end(buf)
71 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
72 #[cfg(target_os = "android")]
73 use super::android::cvt_pread64;
75 #[cfg(not(target_os = "android"))]
76 unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
79 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
81 #[cfg(not(any(target_os = "linux", target_os = "emscripten")))]
82 use libc::pread as pread64;
83 cvt(pread64(fd, buf, count, offset))
88 buf.as_mut_ptr() as *mut c_void,
89 cmp::min(buf.len(), max_len()),
95 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
96 let ret = cvt(unsafe {
98 buf.as_ptr() as *const c_void,
99 cmp::min(buf.len(), max_len()))
104 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
105 #[cfg(target_os = "android")]
106 use super::android::cvt_pwrite64;
108 #[cfg(not(target_os = "android"))]
109 unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
112 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
114 #[cfg(not(any(target_os = "linux", target_os = "emscripten")))]
115 use libc::pwrite as pwrite64;
116 cvt(pwrite64(fd, buf, count, offset))
120 cvt_pwrite64(self.fd,
121 buf.as_ptr() as *const c_void,
122 cmp::min(buf.len(), max_len()),
128 #[cfg(not(any(target_env = "newlib",
129 target_os = "solaris",
130 target_os = "emscripten",
131 target_os = "fuchsia",
132 target_os = "haiku")))]
133 pub fn set_cloexec(&self) -> io::Result<()> {
135 cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
139 #[cfg(any(target_env = "newlib",
140 target_os = "solaris",
141 target_os = "emscripten",
142 target_os = "fuchsia",
143 target_os = "haiku"))]
144 pub fn set_cloexec(&self) -> io::Result<()> {
146 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
147 let new = previous | libc::FD_CLOEXEC;
149 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
155 #[cfg(target_os = "linux")]
156 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
158 let v = nonblocking as c_int;
159 cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
164 #[cfg(not(target_os = "linux"))]
165 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
167 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
168 let new = if nonblocking {
169 previous | libc::O_NONBLOCK
171 previous & !libc::O_NONBLOCK
174 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
180 pub fn duplicate(&self) -> io::Result<FileDesc> {
181 // We want to atomically duplicate this file descriptor and set the
182 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
183 // flag, however, isn't supported on older Linux kernels (earlier than
186 // To detect this and ensure that CLOEXEC is still set, we
187 // follow a strategy similar to musl [1] where if passing
188 // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
189 // supported (the third parameter, 0, is always valid), so we stop
192 // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
193 // resolve so we at least compile this.
195 // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
196 #[cfg(any(target_os = "android", target_os = "haiku"))]
197 use libc::F_DUPFD as F_DUPFD_CLOEXEC;
198 #[cfg(not(any(target_os = "android", target_os="haiku")))]
199 use libc::F_DUPFD_CLOEXEC;
201 let make_filedesc = |fd| {
202 let fd = FileDesc::new(fd);
206 static TRY_CLOEXEC: AtomicBool =
207 AtomicBool::new(!cfg!(target_os = "android"));
209 if TRY_CLOEXEC.load(Ordering::Relaxed) {
210 match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
211 // We *still* call the `set_cloexec` method as apparently some
212 // linux kernel at some point stopped setting CLOEXEC even
213 // though it reported doing so on F_DUPFD_CLOEXEC.
215 return Ok(if cfg!(target_os = "linux") {
221 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
222 TRY_CLOEXEC.store(false, Ordering::Relaxed);
224 Err(e) => return Err(e),
227 cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
231 impl<'a> Read for &'a FileDesc {
232 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
236 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
237 unsafe { read_to_end_uninitialized(self, buf) }
241 impl AsInner<c_int> for FileDesc {
242 fn as_inner(&self) -> &c_int { &self.fd }
245 impl Drop for FileDesc {
247 // Note that errors are ignored when closing a file descriptor. The
248 // reason for this is that if an error occurs we don't actually know if
249 // the file descriptor was closed or not, and if we retried (for
250 // something like EINTR), we might close another valid file descriptor
251 // (opened after we closed ours.
252 let _ = unsafe { libc::close(self.fd) };