]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Rollup merge of #60429 - estebank:pub-path, r=michaelwoerister
[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 = "haiku")))]
179     pub fn set_cloexec(&self) -> io::Result<()> {
180         unsafe {
181             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
182             Ok(())
183         }
184     }
185     #[cfg(any(target_env = "newlib",
186               target_os = "solaris",
187               target_os = "emscripten",
188               target_os = "fuchsia",
189               target_os = "l4re",
190               target_os = "haiku"))]
191     pub fn set_cloexec(&self) -> io::Result<()> {
192         unsafe {
193             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
194             let new = previous | libc::FD_CLOEXEC;
195             if new != previous {
196                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
197             }
198             Ok(())
199         }
200     }
201
202     #[cfg(target_os = "linux")]
203     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
204         unsafe {
205             let v = nonblocking as c_int;
206             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
207             Ok(())
208         }
209     }
210
211     #[cfg(not(target_os = "linux"))]
212     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
213         unsafe {
214             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
215             let new = if nonblocking {
216                 previous | libc::O_NONBLOCK
217             } else {
218                 previous & !libc::O_NONBLOCK
219             };
220             if new != previous {
221                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
222             }
223             Ok(())
224         }
225     }
226
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
231         // 2.6.24).
232         //
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
237         // trying that.
238         //
239         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
240         // resolve so we at least compile this.
241         //
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;
247
248         let make_filedesc = |fd| {
249             let fd = FileDesc::new(fd);
250             fd.set_cloexec()?;
251             Ok(fd)
252         };
253         static TRY_CLOEXEC: AtomicBool =
254             AtomicBool::new(!cfg!(target_os = "android"));
255         let fd = self.raw();
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.
261                 Ok(fd) => {
262                     return Ok(if cfg!(target_os = "linux") {
263                         make_filedesc(fd)?
264                     } else {
265                         FileDesc::new(fd)
266                     })
267                 }
268                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
269                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
270                 }
271                 Err(e) => return Err(e),
272             }
273         }
274         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
275     }
276 }
277
278 impl<'a> Read for &'a FileDesc {
279     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
280         (**self).read(buf)
281     }
282
283     #[inline]
284     unsafe fn initializer(&self) -> Initializer {
285         Initializer::nop()
286     }
287 }
288
289 impl AsInner<c_int> for FileDesc {
290     fn as_inner(&self) -> &c_int { &self.fd }
291 }
292
293 impl Drop for FileDesc {
294     fn drop(&mut self) {
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) };
301     }
302 }