]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Rollup merge of #64799 - Aaron1011:fix/double-panic, r=Mark-Simulacrum
[rust.git] / src / libstd / sys / unix / fd.rs
1 #![unstable(reason = "not public", issue = "0", feature = "fd")]
2
3 use crate::cmp;
4 use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut};
5 use crate::mem;
6 use crate::sync::atomic::{AtomicBool, Ordering};
7 use crate::sys::cvt;
8 use crate::sys_common::AsInner;
9
10 use libc::{c_int, c_void, ssize_t};
11
12 #[derive(Debug)]
13 pub struct FileDesc {
14     fd: c_int,
15 }
16
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".
21     //
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
28     } else {
29         <ssize_t>::max_value() as usize
30     }
31 }
32
33 impl FileDesc {
34     pub fn new(fd: c_int) -> FileDesc {
35         FileDesc { fd }
36     }
37
38     pub fn raw(&self) -> c_int { self.fd }
39
40     /// Extracts the actual file descriptor without closing it.
41     pub fn into_raw(self) -> c_int {
42         let fd = self.fd;
43         mem::forget(self);
44         fd
45     }
46
47     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
48         let ret = cvt(unsafe {
49             libc::read(self.fd,
50                        buf.as_mut_ptr() as *mut c_void,
51                        cmp::min(buf.len(), max_len()))
52         })?;
53         Ok(ret as usize)
54     }
55
56     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
57         let ret = cvt(unsafe {
58             libc::readv(self.fd,
59                         bufs.as_ptr() as *const libc::iovec,
60                         cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
61         })?;
62         Ok(ret as usize)
63     }
64
65     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
66         let mut me = self;
67         (&mut me).read_to_end(buf)
68     }
69
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;
73
74         #[cfg(target_os = "emscripten")]
75         unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
76             -> io::Result<isize>
77         {
78             use crate::convert::TryInto;
79             use libc::pread64;
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))
83             } else {
84                 Err(io::Error::new(io::ErrorKind::InvalidInput,
85                                    "cannot pread >2GB"))
86             }
87         }
88
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)
91             -> io::Result<isize>
92         {
93             #[cfg(target_os = "linux")]
94             use libc::pread64;
95             #[cfg(not(target_os = "linux"))]
96             use libc::pread as pread64;
97             cvt(pread64(fd, buf, count, offset))
98         }
99
100         unsafe {
101             cvt_pread64(self.fd,
102                         buf.as_mut_ptr() as *mut c_void,
103                         cmp::min(buf.len(), max_len()),
104                         offset as i64)
105                 .map(|n| n as usize)
106         }
107     }
108
109     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
110         let ret = cvt(unsafe {
111             libc::write(self.fd,
112                         buf.as_ptr() as *const c_void,
113                         cmp::min(buf.len(), max_len()))
114         })?;
115         Ok(ret as usize)
116     }
117
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)
123         })?;
124         Ok(ret as usize)
125     }
126
127     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
128         #[cfg(target_os = "android")]
129         use super::android::cvt_pwrite64;
130
131         #[cfg(target_os = "emscripten")]
132         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
133             -> io::Result<isize>
134         {
135             use crate::convert::TryInto;
136             use libc::pwrite64;
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))
140             } else {
141                 Err(io::Error::new(io::ErrorKind::InvalidInput,
142                                    "cannot pwrite >2GB"))
143             }
144         }
145
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)
148             -> io::Result<isize>
149         {
150             #[cfg(target_os = "linux")]
151             use libc::pwrite64;
152             #[cfg(not(target_os = "linux"))]
153             use libc::pwrite as pwrite64;
154             cvt(pwrite64(fd, buf, count, offset))
155         }
156
157         unsafe {
158             cvt_pwrite64(self.fd,
159                          buf.as_ptr() as *const c_void,
160                          cmp::min(buf.len(), max_len()),
161                          offset as i64)
162                 .map(|n| n as usize)
163         }
164     }
165
166     #[cfg(target_os = "linux")]
167     pub fn get_cloexec(&self) -> io::Result<bool> {
168         unsafe {
169             Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0)
170         }
171     }
172
173     #[cfg(not(any(target_env = "newlib",
174                   target_os = "solaris",
175                   target_os = "emscripten",
176                   target_os = "fuchsia",
177                   target_os = "l4re",
178                   target_os = "linux",
179                   target_os = "haiku",
180                   target_os = "redox")))]
181     pub fn set_cloexec(&self) -> io::Result<()> {
182         unsafe {
183             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
184             Ok(())
185         }
186     }
187     #[cfg(any(target_env = "newlib",
188               target_os = "solaris",
189               target_os = "emscripten",
190               target_os = "fuchsia",
191               target_os = "l4re",
192               target_os = "linux",
193               target_os = "haiku",
194               target_os = "redox"))]
195     pub fn set_cloexec(&self) -> io::Result<()> {
196         unsafe {
197             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
198             let new = previous | libc::FD_CLOEXEC;
199             if new != previous {
200                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
201             }
202             Ok(())
203         }
204     }
205
206     #[cfg(target_os = "linux")]
207     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
208         unsafe {
209             let v = nonblocking as c_int;
210             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
211             Ok(())
212         }
213     }
214
215     #[cfg(not(target_os = "linux"))]
216     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
217         unsafe {
218             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
219             let new = if nonblocking {
220                 previous | libc::O_NONBLOCK
221             } else {
222                 previous & !libc::O_NONBLOCK
223             };
224             if new != previous {
225                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
226             }
227             Ok(())
228         }
229     }
230
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
235         // 2.6.24).
236         //
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
241         // trying that.
242         //
243         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
244         // resolve so we at least compile this.
245         //
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;
251
252         let make_filedesc = |fd| {
253             let fd = FileDesc::new(fd);
254             fd.set_cloexec()?;
255             Ok(fd)
256         };
257         static TRY_CLOEXEC: AtomicBool =
258             AtomicBool::new(!cfg!(target_os = "android"));
259         let fd = self.raw();
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.
265                 Ok(fd) => {
266                     return Ok(if cfg!(target_os = "linux") {
267                         make_filedesc(fd)?
268                     } else {
269                         FileDesc::new(fd)
270                     })
271                 }
272                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
273                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
274                 }
275                 Err(e) => return Err(e),
276             }
277         }
278         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
279     }
280 }
281
282 impl<'a> Read for &'a FileDesc {
283     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
284         (**self).read(buf)
285     }
286
287     #[inline]
288     unsafe fn initializer(&self) -> Initializer {
289         Initializer::nop()
290     }
291 }
292
293 impl AsInner<c_int> for FileDesc {
294     fn as_inner(&self) -> &c_int { &self.fd }
295 }
296
297 impl Drop for FileDesc {
298     fn drop(&mut self) {
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) };
305     }
306 }