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