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",
178 target_os = "haiku")))]
179 pub fn set_cloexec(&self) -> io::Result<()> {
181 cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
185 #[cfg(any(target_env = "newlib",
186 target_os = "solaris",
187 target_os = "emscripten",
188 target_os = "fuchsia",
190 target_os = "haiku"))]
191 pub fn set_cloexec(&self) -> io::Result<()> {
193 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
194 let new = previous | libc::FD_CLOEXEC;
196 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
202 #[cfg(target_os = "linux")]
203 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
205 let v = nonblocking as c_int;
206 cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
211 #[cfg(not(target_os = "linux"))]
212 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
214 let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
215 let new = if nonblocking {
216 previous | libc::O_NONBLOCK
218 previous & !libc::O_NONBLOCK
221 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
227 pub fn duplicate(&self) -> io::Result<FileDesc> {
228 // We want to atomically duplicate this file descriptor and set the
229 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
230 // flag, however, isn't supported on older Linux kernels (earlier than
233 // To detect this and ensure that CLOEXEC is still set, we
234 // follow a strategy similar to musl [1] where if passing
235 // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
236 // supported (the third parameter, 0, is always valid), so we stop
239 // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
240 // resolve so we at least compile this.
242 // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
243 #[cfg(any(target_os = "android", target_os = "haiku"))]
244 use libc::F_DUPFD as F_DUPFD_CLOEXEC;
245 #[cfg(not(any(target_os = "android", target_os="haiku")))]
246 use libc::F_DUPFD_CLOEXEC;
248 let make_filedesc = |fd| {
249 let fd = FileDesc::new(fd);
253 static TRY_CLOEXEC: AtomicBool =
254 AtomicBool::new(!cfg!(target_os = "android"));
256 if TRY_CLOEXEC.load(Ordering::Relaxed) {
257 match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
258 // We *still* call the `set_cloexec` method as apparently some
259 // linux kernel at some point stopped setting CLOEXEC even
260 // though it reported doing so on F_DUPFD_CLOEXEC.
262 return Ok(if cfg!(target_os = "linux") {
268 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
269 TRY_CLOEXEC.store(false, Ordering::Relaxed);
271 Err(e) => return Err(e),
274 cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
278 impl<'a> Read for &'a FileDesc {
279 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
284 unsafe fn initializer(&self) -> Initializer {
289 impl AsInner<c_int> for FileDesc {
290 fn as_inner(&self) -> &c_int { &self.fd }
293 impl Drop for FileDesc {
295 // Note that errors are ignored when closing a file descriptor. The
296 // reason for this is that if an error occurs we don't actually know if
297 // the file descriptor was closed or not, and if we retried (for
298 // something like EINTR), we might close another valid file descriptor
299 // opened after we closed ours.
300 let _ = unsafe { libc::close(self.fd) };