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;
26 fn max_len() -> usize {
27 // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
28 // with the man page quoting that if the count of bytes to read is
29 // greater than `SSIZE_MAX` the result is "unspecified".
31 // On macOS, however, apparently the 64-bit libc is either buggy or
32 // intentionally showing odd behavior by rejecting any read with a size
33 // larger than or equal to INT_MAX. To handle both of these the read
34 // size is capped on both platforms.
35 if cfg!(target_os = "macos") {
36 <c_int>::max_value() as usize - 1
38 <ssize_t>::max_value() as usize
43 pub fn new(fd: c_int) -> FileDesc {
47 pub fn raw(&self) -> c_int { self.fd }
49 /// Extracts the actual filedescriptor without closing it.
50 pub fn into_raw(self) -> c_int {
56 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
57 let ret = cvt(unsafe {
59 buf.as_mut_ptr() as *mut c_void,
60 cmp::min(buf.len(), max_len()))
65 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
67 (&mut me).read_to_end(buf)
70 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
71 #[cfg(target_os = "android")]
72 use super::android::cvt_pread64;
74 #[cfg(target_os = "emscripten")]
75 unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
80 // pread64 on emscripten actually takes a 32 bit offset
81 if let Ok(o) = offset.try_into() {
82 cvt(pread64(fd, buf, count, o))
84 Err(io::Error::new(io::ErrorKind::InvalidInput,
89 #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
90 unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
93 #[cfg(target_os = "linux")]
95 #[cfg(not(target_os = "linux"))]
96 use libc::pread as pread64;
97 cvt(pread64(fd, buf, count, offset))
102 buf.as_mut_ptr() as *mut c_void,
103 cmp::min(buf.len(), max_len()),
109 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
110 let ret = cvt(unsafe {
112 buf.as_ptr() as *const c_void,
113 cmp::min(buf.len(), max_len()))
118 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
119 #[cfg(target_os = "android")]
120 use super::android::cvt_pwrite64;
122 #[cfg(target_os = "emscripten")]
123 unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
126 use convert::TryInto;
128 // pwrite64 on emscripten actually takes a 32 bit offset
129 if let Ok(o) = offset.try_into() {
130 cvt(pwrite64(fd, buf, count, o))
132 Err(io::Error::new(io::ErrorKind::InvalidInput,
133 "cannot pwrite >2GB"))
137 #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
138 unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
141 #[cfg(target_os = "linux")]
143 #[cfg(not(target_os = "linux"))]
144 use libc::pwrite as pwrite64;
145 cvt(pwrite64(fd, buf, count, offset))
149 cvt_pwrite64(self.fd,
150 buf.as_ptr() as *const c_void,
151 cmp::min(buf.len(), max_len()),
157 #[cfg(not(any(target_env = "newlib",
158 target_os = "solaris",
159 target_os = "emscripten",
160 target_os = "fuchsia",
162 target_os = "haiku")))]
163 pub fn set_cloexec(&self) -> io::Result<()> {
165 cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
169 #[cfg(any(target_env = "newlib",
170 target_os = "solaris",
171 target_os = "emscripten",
172 target_os = "fuchsia",
174 target_os = "haiku"))]
175 pub fn set_cloexec(&self) -> io::Result<()> {
177 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
178 let new = previous | libc::FD_CLOEXEC;
180 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
186 #[cfg(target_os = "linux")]
187 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
189 let v = nonblocking as c_int;
190 cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
195 #[cfg(not(target_os = "linux"))]
196 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
198 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
199 let new = if nonblocking {
200 previous | libc::O_NONBLOCK
202 previous & !libc::O_NONBLOCK
205 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
211 pub fn duplicate(&self) -> io::Result<FileDesc> {
212 // We want to atomically duplicate this file descriptor and set the
213 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
214 // flag, however, isn't supported on older Linux kernels (earlier than
217 // To detect this and ensure that CLOEXEC is still set, we
218 // follow a strategy similar to musl [1] where if passing
219 // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
220 // supported (the third parameter, 0, is always valid), so we stop
223 // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
224 // resolve so we at least compile this.
226 // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
227 #[cfg(any(target_os = "android", target_os = "haiku"))]
228 use libc::F_DUPFD as F_DUPFD_CLOEXEC;
229 #[cfg(not(any(target_os = "android", target_os="haiku")))]
230 use libc::F_DUPFD_CLOEXEC;
232 let make_filedesc = |fd| {
233 let fd = FileDesc::new(fd);
237 static TRY_CLOEXEC: AtomicBool =
238 AtomicBool::new(!cfg!(target_os = "android"));
240 if TRY_CLOEXEC.load(Ordering::Relaxed) {
241 match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
242 // We *still* call the `set_cloexec` method as apparently some
243 // linux kernel at some point stopped setting CLOEXEC even
244 // though it reported doing so on F_DUPFD_CLOEXEC.
246 return Ok(if cfg!(target_os = "linux") {
252 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
253 TRY_CLOEXEC.store(false, Ordering::Relaxed);
255 Err(e) => return Err(e),
258 cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
262 impl<'a> Read for &'a FileDesc {
263 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
268 impl AsInner<c_int> for FileDesc {
269 fn as_inner(&self) -> &c_int { &self.fd }
272 impl Drop for FileDesc {
274 // Note that errors are ignored when closing a file descriptor. The
275 // reason for this is that if an error occurs we don't actually know if
276 // the file descriptor was closed or not, and if we retried (for
277 // something like EINTR), we might close another valid file descriptor
278 // (opened after we closed ours.
279 let _ = unsafe { libc::close(self.fd) };