]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Auto merge of #53830 - davidtwco:issue-53228, r=nikomatsakis
[rust.git] / src / libstd / sys / unix / fd.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![unstable(reason = "not public", issue = "0", feature = "fd")]
12
13 use cmp;
14 use io::{self, Read};
15 use libc::{self, c_int, c_void, ssize_t};
16 use mem;
17 use sync::atomic::{AtomicBool, Ordering};
18 use sys::cvt;
19 use sys_common::AsInner;
20
21 #[derive(Debug)]
22 pub struct FileDesc {
23     fd: c_int,
24 }
25
26 fn max_len() -> usize {
27     // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
28     // with the man page quoting that if the count of bytes to read is
29     // greater than `SSIZE_MAX` the result is "unspecified".
30     //
31     // On macOS, however, apparently the 64-bit libc is either buggy or
32     // intentionally showing odd behavior by rejecting any read with a size
33     // larger than or equal to INT_MAX. To handle both of these the read
34     // size is capped on both platforms.
35     if cfg!(target_os = "macos") {
36         <c_int>::max_value() as usize - 1
37     } else {
38         <ssize_t>::max_value() as usize
39     }
40 }
41
42 impl FileDesc {
43     pub fn new(fd: c_int) -> FileDesc {
44         FileDesc { fd: fd }
45     }
46
47     pub fn raw(&self) -> c_int { self.fd }
48
49     /// Extracts the actual filedescriptor without closing it.
50     pub fn into_raw(self) -> c_int {
51         let fd = self.fd;
52         mem::forget(self);
53         fd
54     }
55
56     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
57         let ret = cvt(unsafe {
58             libc::read(self.fd,
59                        buf.as_mut_ptr() as *mut c_void,
60                        cmp::min(buf.len(), max_len()))
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 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_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
119         #[cfg(target_os = "android")]
120         use super::android::cvt_pwrite64;
121
122         #[cfg(target_os = "emscripten")]
123         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
124             -> io::Result<isize>
125         {
126             use convert::TryInto;
127             use libc::pwrite64;
128             // pwrite64 on emscripten actually takes a 32 bit offset
129             if let Ok(o) = offset.try_into() {
130                 cvt(pwrite64(fd, buf, count, o))
131             } else {
132                 Err(io::Error::new(io::ErrorKind::InvalidInput,
133                                    "cannot pwrite >2GB"))
134             }
135         }
136
137         #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
138         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
139             -> io::Result<isize>
140         {
141             #[cfg(target_os = "linux")]
142             use libc::pwrite64;
143             #[cfg(not(target_os = "linux"))]
144             use libc::pwrite as pwrite64;
145             cvt(pwrite64(fd, buf, count, offset))
146         }
147
148         unsafe {
149             cvt_pwrite64(self.fd,
150                          buf.as_ptr() as *const c_void,
151                          cmp::min(buf.len(), max_len()),
152                          offset as i64)
153                 .map(|n| n as usize)
154         }
155     }
156
157     #[cfg(target_os = "linux")]
158     pub fn get_cloexec(&self) -> io::Result<bool> {
159         unsafe {
160             Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0)
161         }
162     }
163
164     #[cfg(not(any(target_env = "newlib",
165                   target_os = "solaris",
166                   target_os = "emscripten",
167                   target_os = "fuchsia",
168                   target_os = "l4re",
169                   target_os = "haiku")))]
170     pub fn set_cloexec(&self) -> io::Result<()> {
171         unsafe {
172             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
173             Ok(())
174         }
175     }
176     #[cfg(any(target_env = "newlib",
177               target_os = "solaris",
178               target_os = "emscripten",
179               target_os = "fuchsia",
180               target_os = "l4re",
181               target_os = "haiku"))]
182     pub fn set_cloexec(&self) -> io::Result<()> {
183         unsafe {
184             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
185             let new = previous | libc::FD_CLOEXEC;
186             if new != previous {
187                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
188             }
189             Ok(())
190         }
191     }
192
193     #[cfg(target_os = "linux")]
194     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
195         unsafe {
196             let v = nonblocking as c_int;
197             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
198             Ok(())
199         }
200     }
201
202     #[cfg(not(target_os = "linux"))]
203     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
204         unsafe {
205             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
206             let new = if nonblocking {
207                 previous | libc::O_NONBLOCK
208             } else {
209                 previous & !libc::O_NONBLOCK
210             };
211             if new != previous {
212                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
213             }
214             Ok(())
215         }
216     }
217
218     pub fn duplicate(&self) -> io::Result<FileDesc> {
219         // We want to atomically duplicate this file descriptor and set the
220         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
221         // flag, however, isn't supported on older Linux kernels (earlier than
222         // 2.6.24).
223         //
224         // To detect this and ensure that CLOEXEC is still set, we
225         // follow a strategy similar to musl [1] where if passing
226         // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
227         // supported (the third parameter, 0, is always valid), so we stop
228         // trying that.
229         //
230         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
231         // resolve so we at least compile this.
232         //
233         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
234         #[cfg(any(target_os = "android", target_os = "haiku"))]
235         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
236         #[cfg(not(any(target_os = "android", target_os="haiku")))]
237         use libc::F_DUPFD_CLOEXEC;
238
239         let make_filedesc = |fd| {
240             let fd = FileDesc::new(fd);
241             fd.set_cloexec()?;
242             Ok(fd)
243         };
244         static TRY_CLOEXEC: AtomicBool =
245             AtomicBool::new(!cfg!(target_os = "android"));
246         let fd = self.raw();
247         if TRY_CLOEXEC.load(Ordering::Relaxed) {
248             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
249                 // We *still* call the `set_cloexec` method as apparently some
250                 // linux kernel at some point stopped setting CLOEXEC even
251                 // though it reported doing so on F_DUPFD_CLOEXEC.
252                 Ok(fd) => {
253                     return Ok(if cfg!(target_os = "linux") {
254                         make_filedesc(fd)?
255                     } else {
256                         FileDesc::new(fd)
257                     })
258                 }
259                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
260                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
261                 }
262                 Err(e) => return Err(e),
263             }
264         }
265         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
266     }
267 }
268
269 impl<'a> Read for &'a FileDesc {
270     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
271         (**self).read(buf)
272     }
273 }
274
275 impl AsInner<c_int> for FileDesc {
276     fn as_inner(&self) -> &c_int { &self.fd }
277 }
278
279 impl Drop for FileDesc {
280     fn drop(&mut self) {
281         // Note that errors are ignored when closing a file descriptor. The
282         // reason for this is that if an error occurs we don't actually know if
283         // the file descriptor was closed or not, and if we retried (for
284         // something like EINTR), we might close another valid file descriptor
285         // opened after we closed ours.
286         let _ = unsafe { libc::close(self.fd) };
287     }
288 }