]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[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 use sys_common::io::read_to_end_uninitialized;
21
22 #[derive(Debug)]
23 pub struct FileDesc {
24     fd: c_int,
25 }
26
27 fn max_len() -> usize {
28     // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
29     // with the man page quoting that if the count of bytes to read is
30     // greater than `SSIZE_MAX` the result is "unspecified".
31     //
32     // On macOS, however, apparently the 64-bit libc is either buggy or
33     // intentionally showing odd behavior by rejecting any read with a size
34     // larger than or equal to INT_MAX. To handle both of these the read
35     // size is capped on both platforms.
36     if cfg!(target_os = "macos") {
37         <c_int>::max_value() as usize - 1
38     } else {
39         <ssize_t>::max_value() as usize
40     }
41 }
42
43 impl FileDesc {
44     pub fn new(fd: c_int) -> FileDesc {
45         FileDesc { fd: fd }
46     }
47
48     pub fn raw(&self) -> c_int { self.fd }
49
50     /// Extracts the actual filedescriptor without closing it.
51     pub fn into_raw(self) -> c_int {
52         let fd = self.fd;
53         mem::forget(self);
54         fd
55     }
56
57     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
58         let ret = cvt(unsafe {
59             libc::read(self.fd,
60                        buf.as_mut_ptr() as *mut c_void,
61                        cmp::min(buf.len(), max_len()))
62         })?;
63         Ok(ret as usize)
64     }
65
66     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
67         let mut me = self;
68         (&mut me).read_to_end(buf)
69     }
70
71     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
72         #[cfg(target_os = "android")]
73         use super::android::cvt_pread64;
74
75         #[cfg(not(target_os = "android"))]
76         unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
77             -> io::Result<isize>
78         {
79             #[cfg(any(target_os = "linux", target_os = "emscripten"))]
80             use libc::pread64;
81             #[cfg(not(any(target_os = "linux", target_os = "emscripten")))]
82             use libc::pread as pread64;
83             cvt(pread64(fd, buf, count, offset))
84         }
85
86         unsafe {
87             cvt_pread64(self.fd,
88                         buf.as_mut_ptr() as *mut c_void,
89                         cmp::min(buf.len(), max_len()),
90                         offset as i64)
91                 .map(|n| n as usize)
92         }
93     }
94
95     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
96         let ret = cvt(unsafe {
97             libc::write(self.fd,
98                         buf.as_ptr() as *const c_void,
99                         cmp::min(buf.len(), max_len()))
100         })?;
101         Ok(ret as usize)
102     }
103
104     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
105         #[cfg(target_os = "android")]
106         use super::android::cvt_pwrite64;
107
108         #[cfg(not(target_os = "android"))]
109         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
110             -> io::Result<isize>
111         {
112             #[cfg(any(target_os = "linux", target_os = "emscripten"))]
113             use libc::pwrite64;
114             #[cfg(not(any(target_os = "linux", target_os = "emscripten")))]
115             use libc::pwrite as pwrite64;
116             cvt(pwrite64(fd, buf, count, offset))
117         }
118
119         unsafe {
120             cvt_pwrite64(self.fd,
121                          buf.as_ptr() as *const c_void,
122                          cmp::min(buf.len(), max_len()),
123                          offset as i64)
124                 .map(|n| n as usize)
125         }
126     }
127
128     #[cfg(not(any(target_env = "newlib",
129                   target_os = "solaris",
130                   target_os = "emscripten",
131                   target_os = "fuchsia",
132                   target_os = "haiku")))]
133     pub fn set_cloexec(&self) -> io::Result<()> {
134         unsafe {
135             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
136             Ok(())
137         }
138     }
139     #[cfg(any(target_env = "newlib",
140               target_os = "solaris",
141               target_os = "emscripten",
142               target_os = "fuchsia",
143               target_os = "haiku"))]
144     pub fn set_cloexec(&self) -> io::Result<()> {
145         unsafe {
146             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
147             let new = previous | libc::FD_CLOEXEC;
148             if new != previous {
149                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
150             }
151             Ok(())
152         }
153     }
154
155     #[cfg(target_os = "linux")]
156     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
157         unsafe {
158             let v = nonblocking as c_int;
159             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
160             Ok(())
161         }
162     }
163
164     #[cfg(not(target_os = "linux"))]
165     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
166         unsafe {
167             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
168             let new = if nonblocking {
169                 previous | libc::O_NONBLOCK
170             } else {
171                 previous & !libc::O_NONBLOCK
172             };
173             if new != previous {
174                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
175             }
176             Ok(())
177         }
178     }
179
180     pub fn duplicate(&self) -> io::Result<FileDesc> {
181         // We want to atomically duplicate this file descriptor and set the
182         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
183         // flag, however, isn't supported on older Linux kernels (earlier than
184         // 2.6.24).
185         //
186         // To detect this and ensure that CLOEXEC is still set, we
187         // follow a strategy similar to musl [1] where if passing
188         // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
189         // supported (the third parameter, 0, is always valid), so we stop
190         // trying that.
191         //
192         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
193         // resolve so we at least compile this.
194         //
195         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
196         #[cfg(any(target_os = "android", target_os = "haiku"))]
197         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
198         #[cfg(not(any(target_os = "android", target_os="haiku")))]
199         use libc::F_DUPFD_CLOEXEC;
200
201         let make_filedesc = |fd| {
202             let fd = FileDesc::new(fd);
203             fd.set_cloexec()?;
204             Ok(fd)
205         };
206         static TRY_CLOEXEC: AtomicBool =
207             AtomicBool::new(!cfg!(target_os = "android"));
208         let fd = self.raw();
209         if TRY_CLOEXEC.load(Ordering::Relaxed) {
210             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
211                 // We *still* call the `set_cloexec` method as apparently some
212                 // linux kernel at some point stopped setting CLOEXEC even
213                 // though it reported doing so on F_DUPFD_CLOEXEC.
214                 Ok(fd) => {
215                     return Ok(if cfg!(target_os = "linux") {
216                         make_filedesc(fd)?
217                     } else {
218                         FileDesc::new(fd)
219                     })
220                 }
221                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
222                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
223                 }
224                 Err(e) => return Err(e),
225             }
226         }
227         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
228     }
229 }
230
231 impl<'a> Read for &'a FileDesc {
232     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
233         (**self).read(buf)
234     }
235
236     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
237         unsafe { read_to_end_uninitialized(self, buf) }
238     }
239 }
240
241 impl AsInner<c_int> for FileDesc {
242     fn as_inner(&self) -> &c_int { &self.fd }
243 }
244
245 impl Drop for FileDesc {
246     fn drop(&mut self) {
247         // Note that errors are ignored when closing a file descriptor. The
248         // reason for this is that if an error occurs we don't actually know if
249         // the file descriptor was closed or not, and if we retried (for
250         // something like EINTR), we might close another valid file descriptor
251         // (opened after we closed ours.
252         let _ = unsafe { libc::close(self.fd) };
253     }
254 }