]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/fd.rs
Query maximum vector count on Linux and macOS
[rust.git] / library / std / src / sys / unix / fd.rs
1 #![unstable(reason = "not public", issue = "none", feature = "fd")]
2
3 use crate::cmp;
4 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read};
5 use crate::mem;
6 use crate::sys::cvt;
7 use crate::sys_common::AsInner;
8
9 use libc::{c_int, c_void};
10
11 #[derive(Debug)]
12 pub struct FileDesc {
13     fd: c_int,
14 }
15
16 // The maximum read limit on most POSIX-like systems is `SSIZE_MAX`,
17 // with the man page quoting that if the count of bytes to read is
18 // greater than `SSIZE_MAX` the result is "unspecified".
19 //
20 // On macOS, however, apparently the 64-bit libc is either buggy or
21 // intentionally showing odd behavior by rejecting any read with a size
22 // larger than or equal to INT_MAX. To handle both of these the read
23 // size is capped on both platforms.
24 #[cfg(target_os = "macos")]
25 const READ_LIMIT: usize = c_int::MAX as usize - 1;
26 #[cfg(not(target_os = "macos"))]
27 const READ_LIMIT: usize = libc::ssize_t::MAX as usize;
28
29 #[cfg(any(target_os = "linux", target_os = "macos"))]
30 fn max_iov() -> c_int {
31     let ret = unsafe {
32         libc::sysconf(
33             #[cfg(target_os = "linux")]
34             libc::_SC_IOV_MAX,
35             #[cfg(target_os = "macos")]
36             libc::_SC_UIO_MAXIOV,
37         )
38     };
39
40     // 1024 is the default value on modern Linux systems
41     // and hopefully more useful than `c_int::MAX`.
42     if ret > 0 { ret as c_int } else { 1024 }
43 }
44
45 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
46 fn max_iov() -> c_int {
47     c_int::MAX
48 }
49
50 impl FileDesc {
51     pub fn new(fd: c_int) -> FileDesc {
52         FileDesc { fd }
53     }
54
55     pub fn raw(&self) -> c_int {
56         self.fd
57     }
58
59     /// Extracts the actual file descriptor without closing it.
60     pub fn into_raw(self) -> c_int {
61         let fd = self.fd;
62         mem::forget(self);
63         fd
64     }
65
66     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
67         let ret = cvt(unsafe {
68             libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), READ_LIMIT))
69         })?;
70         Ok(ret as usize)
71     }
72
73     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
74         let ret = cvt(unsafe {
75             libc::readv(
76                 self.fd,
77                 bufs.as_ptr() as *const libc::iovec,
78                 cmp::min(bufs.len(), max_iov() as usize) as c_int,
79             )
80         })?;
81         Ok(ret as usize)
82     }
83
84     #[inline]
85     pub fn is_read_vectored(&self) -> bool {
86         true
87     }
88
89     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
90         let mut me = self;
91         (&mut me).read_to_end(buf)
92     }
93
94     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
95         #[cfg(target_os = "android")]
96         use super::android::cvt_pread64;
97
98         #[cfg(not(target_os = "android"))]
99         unsafe fn cvt_pread64(
100             fd: c_int,
101             buf: *mut c_void,
102             count: usize,
103             offset: i64,
104         ) -> io::Result<isize> {
105             #[cfg(not(target_os = "linux"))]
106             use libc::pread as pread64;
107             #[cfg(target_os = "linux")]
108             use libc::pread64;
109             cvt(pread64(fd, buf, count, offset))
110         }
111
112         unsafe {
113             cvt_pread64(
114                 self.fd,
115                 buf.as_mut_ptr() as *mut c_void,
116                 cmp::min(buf.len(), READ_LIMIT),
117                 offset as i64,
118             )
119             .map(|n| n as usize)
120         }
121     }
122
123     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
124         let ret = cvt(unsafe {
125             libc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), READ_LIMIT))
126         })?;
127         Ok(ret as usize)
128     }
129
130     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
131         let ret = cvt(unsafe {
132             libc::writev(
133                 self.fd,
134                 bufs.as_ptr() as *const libc::iovec,
135                 cmp::min(bufs.len(), max_iov() as usize) as c_int,
136             )
137         })?;
138         Ok(ret as usize)
139     }
140
141     #[inline]
142     pub fn is_write_vectored(&self) -> bool {
143         true
144     }
145
146     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
147         #[cfg(target_os = "android")]
148         use super::android::cvt_pwrite64;
149
150         #[cfg(not(target_os = "android"))]
151         unsafe fn cvt_pwrite64(
152             fd: c_int,
153             buf: *const c_void,
154             count: usize,
155             offset: i64,
156         ) -> io::Result<isize> {
157             #[cfg(not(target_os = "linux"))]
158             use libc::pwrite as pwrite64;
159             #[cfg(target_os = "linux")]
160             use libc::pwrite64;
161             cvt(pwrite64(fd, buf, count, offset))
162         }
163
164         unsafe {
165             cvt_pwrite64(
166                 self.fd,
167                 buf.as_ptr() as *const c_void,
168                 cmp::min(buf.len(), READ_LIMIT),
169                 offset as i64,
170             )
171             .map(|n| n as usize)
172         }
173     }
174
175     #[cfg(target_os = "linux")]
176     pub fn get_cloexec(&self) -> io::Result<bool> {
177         unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) }
178     }
179
180     #[cfg(not(any(
181         target_env = "newlib",
182         target_os = "solaris",
183         target_os = "illumos",
184         target_os = "emscripten",
185         target_os = "fuchsia",
186         target_os = "l4re",
187         target_os = "linux",
188         target_os = "haiku",
189         target_os = "redox"
190     )))]
191     pub fn set_cloexec(&self) -> io::Result<()> {
192         unsafe {
193             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
194             Ok(())
195         }
196     }
197     #[cfg(any(
198         target_env = "newlib",
199         target_os = "solaris",
200         target_os = "illumos",
201         target_os = "emscripten",
202         target_os = "fuchsia",
203         target_os = "l4re",
204         target_os = "linux",
205         target_os = "haiku",
206         target_os = "redox"
207     ))]
208     pub fn set_cloexec(&self) -> io::Result<()> {
209         unsafe {
210             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
211             let new = previous | libc::FD_CLOEXEC;
212             if new != previous {
213                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
214             }
215             Ok(())
216         }
217     }
218
219     #[cfg(target_os = "linux")]
220     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
221         unsafe {
222             let v = nonblocking as c_int;
223             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
224             Ok(())
225         }
226     }
227
228     #[cfg(not(target_os = "linux"))]
229     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
230         unsafe {
231             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
232             let new = if nonblocking {
233                 previous | libc::O_NONBLOCK
234             } else {
235                 previous & !libc::O_NONBLOCK
236             };
237             if new != previous {
238                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
239             }
240             Ok(())
241         }
242     }
243
244     pub fn duplicate(&self) -> io::Result<FileDesc> {
245         // We want to atomically duplicate this file descriptor and set the
246         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
247         // is a POSIX flag that was added to Linux in 2.6.24.
248         let fd = cvt(unsafe { libc::fcntl(self.raw(), libc::F_DUPFD_CLOEXEC, 0) })?;
249         Ok(FileDesc::new(fd))
250     }
251 }
252
253 impl<'a> Read for &'a FileDesc {
254     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
255         (**self).read(buf)
256     }
257
258     #[inline]
259     unsafe fn initializer(&self) -> Initializer {
260         Initializer::nop()
261     }
262 }
263
264 impl AsInner<c_int> for FileDesc {
265     fn as_inner(&self) -> &c_int {
266         &self.fd
267     }
268 }
269
270 impl Drop for FileDesc {
271     fn drop(&mut self) {
272         // Note that errors are ignored when closing a file descriptor. The
273         // reason for this is that if an error occurs we don't actually know if
274         // the file descriptor was closed or not, and if we retried (for
275         // something like EINTR), we might close another valid file descriptor
276         // opened after we closed ours.
277         let _ = unsafe { libc::close(self.fd) };
278     }
279 }
280
281 #[cfg(test)]
282 mod tests {
283     use super::{FileDesc, IoSlice};
284
285     #[test]
286     fn limit_vector_count() {
287         let stdout = FileDesc { fd: 1 };
288         let bufs = (0..1500).map(|_| IoSlice::new(&[])).collect::<Vec<_>>();
289
290         assert!(stdout.write_vectored(&bufs).is_ok());
291     }
292 }