1 #![unstable(reason = "not public", issue = "0", feature = "fd")]
4 use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut};
6 use crate::sync::atomic::{AtomicBool, Ordering};
8 use crate::sys_common::AsInner;
10 use libc::{c_int, c_void, ssize_t};
17 fn max_len() -> usize {
18 // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
19 // with the man page quoting that if the count of bytes to read is
20 // greater than `SSIZE_MAX` the result is "unspecified".
22 // On macOS, however, apparently the 64-bit libc is either buggy or
23 // intentionally showing odd behavior by rejecting any read with a size
24 // larger than or equal to INT_MAX. To handle both of these the read
25 // size is capped on both platforms.
26 if cfg!(target_os = "macos") {
27 <c_int>::max_value() as usize - 1
29 <ssize_t>::max_value() as usize
34 pub fn new(fd: c_int) -> FileDesc {
38 pub fn raw(&self) -> c_int { self.fd }
40 /// Extracts the actual file descriptor without closing it.
41 pub fn into_raw(self) -> c_int {
47 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
48 let ret = cvt(unsafe {
50 buf.as_mut_ptr() as *mut c_void,
51 cmp::min(buf.len(), max_len()))
56 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
57 let ret = cvt(unsafe {
59 bufs.as_ptr() as *const libc::iovec,
60 cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
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)
78 use crate::convert::TryInto;
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_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
119 let ret = cvt(unsafe {
120 libc::writev(self.fd,
121 bufs.as_ptr() as *const libc::iovec,
122 cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
127 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
128 #[cfg(target_os = "android")]
129 use super::android::cvt_pwrite64;
131 #[cfg(target_os = "emscripten")]
132 unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
135 use crate::convert::TryInto;
137 // pwrite64 on emscripten actually takes a 32 bit offset
138 if let Ok(o) = offset.try_into() {
139 cvt(pwrite64(fd, buf, count, o))
141 Err(io::Error::new(io::ErrorKind::InvalidInput,
142 "cannot pwrite >2GB"))
146 #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
147 unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
150 #[cfg(target_os = "linux")]
152 #[cfg(not(target_os = "linux"))]
153 use libc::pwrite as pwrite64;
154 cvt(pwrite64(fd, buf, count, offset))
158 cvt_pwrite64(self.fd,
159 buf.as_ptr() as *const c_void,
160 cmp::min(buf.len(), max_len()),
166 #[cfg(target_os = "linux")]
167 pub fn get_cloexec(&self) -> io::Result<bool> {
169 Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0)
173 #[cfg(not(any(target_env = "newlib",
174 target_os = "solaris",
175 target_os = "emscripten",
176 target_os = "fuchsia",
180 target_os = "redox")))]
181 pub fn set_cloexec(&self) -> io::Result<()> {
183 cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
187 #[cfg(any(target_env = "newlib",
188 target_os = "solaris",
189 target_os = "emscripten",
190 target_os = "fuchsia",
194 target_os = "redox"))]
195 pub fn set_cloexec(&self) -> io::Result<()> {
197 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
198 let new = previous | libc::FD_CLOEXEC;
200 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
206 #[cfg(target_os = "linux")]
207 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
209 let v = nonblocking as c_int;
210 cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
215 #[cfg(not(target_os = "linux"))]
216 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
218 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
219 let new = if nonblocking {
220 previous | libc::O_NONBLOCK
222 previous & !libc::O_NONBLOCK
225 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
231 pub fn duplicate(&self) -> io::Result<FileDesc> {
232 // We want to atomically duplicate this file descriptor and set the
233 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
234 // flag, however, isn't supported on older Linux kernels (earlier than
237 // To detect this and ensure that CLOEXEC is still set, we
238 // follow a strategy similar to musl [1] where if passing
239 // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
240 // supported (the third parameter, 0, is always valid), so we stop
243 // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
244 // resolve so we at least compile this.
246 // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
247 #[cfg(any(target_os = "android", target_os = "haiku"))]
248 use libc::F_DUPFD as F_DUPFD_CLOEXEC;
249 #[cfg(not(any(target_os = "android", target_os="haiku")))]
250 use libc::F_DUPFD_CLOEXEC;
252 let make_filedesc = |fd| {
253 let fd = FileDesc::new(fd);
257 static TRY_CLOEXEC: AtomicBool =
258 AtomicBool::new(!cfg!(target_os = "android"));
260 if TRY_CLOEXEC.load(Ordering::Relaxed) {
261 match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
262 // We *still* call the `set_cloexec` method as apparently some
263 // linux kernel at some point stopped setting CLOEXEC even
264 // though it reported doing so on F_DUPFD_CLOEXEC.
266 return Ok(if cfg!(target_os = "linux") {
272 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
273 TRY_CLOEXEC.store(false, Ordering::Relaxed);
275 Err(e) => return Err(e),
278 cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
282 impl<'a> Read for &'a FileDesc {
283 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
288 unsafe fn initializer(&self) -> Initializer {
293 impl AsInner<c_int> for FileDesc {
294 fn as_inner(&self) -> &c_int { &self.fd }
297 impl Drop for FileDesc {
299 // Note that errors are ignored when closing a file descriptor. The
300 // reason for this is that if an error occurs we don't actually know if
301 // the file descriptor was closed or not, and if we retried (for
302 // something like EINTR), we might close another valid file descriptor
303 // opened after we closed ours.
304 let _ = unsafe { libc::close(self.fd) };