]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Update the libc submodule
[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 libc::pread64;
79             cvt(pread64(fd, buf, count, offset as i32))
80         }
81
82         #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
83         unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
84             -> io::Result<isize>
85         {
86             #[cfg(target_os = "linux")]
87             use libc::pread64;
88             #[cfg(not(target_os = "linux"))]
89             use libc::pread as pread64;
90             cvt(pread64(fd, buf, count, offset))
91         }
92
93         unsafe {
94             cvt_pread64(self.fd,
95                         buf.as_mut_ptr() as *mut c_void,
96                         cmp::min(buf.len(), max_len()),
97                         offset as i64)
98                 .map(|n| n as usize)
99         }
100     }
101
102     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
103         let ret = cvt(unsafe {
104             libc::write(self.fd,
105                         buf.as_ptr() as *const c_void,
106                         cmp::min(buf.len(), max_len()))
107         })?;
108         Ok(ret as usize)
109     }
110
111     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
112         #[cfg(target_os = "android")]
113         use super::android::cvt_pwrite64;
114
115         #[cfg(target_os = "emscripten")]
116         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
117             -> io::Result<isize>
118         {
119             use libc::pwrite64;
120             cvt(pwrite64(fd, buf, count, offset as i32))
121         }
122
123         #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
124         unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
125             -> io::Result<isize>
126         {
127             #[cfg(target_os = "linux")]
128             use libc::pwrite64;
129             #[cfg(not(target_os = "linux"))]
130             use libc::pwrite as pwrite64;
131             cvt(pwrite64(fd, buf, count, offset))
132         }
133
134         unsafe {
135             cvt_pwrite64(self.fd,
136                          buf.as_ptr() as *const c_void,
137                          cmp::min(buf.len(), max_len()),
138                          offset as i64)
139                 .map(|n| n as usize)
140         }
141     }
142
143     #[cfg(not(any(target_env = "newlib",
144                   target_os = "solaris",
145                   target_os = "emscripten",
146                   target_os = "fuchsia",
147                   target_os = "haiku")))]
148     pub fn set_cloexec(&self) -> io::Result<()> {
149         unsafe {
150             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
151             Ok(())
152         }
153     }
154     #[cfg(any(target_env = "newlib",
155               target_os = "solaris",
156               target_os = "emscripten",
157               target_os = "fuchsia",
158               target_os = "haiku"))]
159     pub fn set_cloexec(&self) -> io::Result<()> {
160         unsafe {
161             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
162             let new = previous | libc::FD_CLOEXEC;
163             if new != previous {
164                 cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
165             }
166             Ok(())
167         }
168     }
169
170     #[cfg(target_os = "linux")]
171     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
172         unsafe {
173             let v = nonblocking as c_int;
174             cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
175             Ok(())
176         }
177     }
178
179     #[cfg(not(target_os = "linux"))]
180     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
181         unsafe {
182             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
183             let new = if nonblocking {
184                 previous | libc::O_NONBLOCK
185             } else {
186                 previous & !libc::O_NONBLOCK
187             };
188             if new != previous {
189                 cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
190             }
191             Ok(())
192         }
193     }
194
195     pub fn duplicate(&self) -> io::Result<FileDesc> {
196         // We want to atomically duplicate this file descriptor and set the
197         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
198         // flag, however, isn't supported on older Linux kernels (earlier than
199         // 2.6.24).
200         //
201         // To detect this and ensure that CLOEXEC is still set, we
202         // follow a strategy similar to musl [1] where if passing
203         // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
204         // supported (the third parameter, 0, is always valid), so we stop
205         // trying that.
206         //
207         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
208         // resolve so we at least compile this.
209         //
210         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
211         #[cfg(any(target_os = "android", target_os = "haiku"))]
212         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
213         #[cfg(not(any(target_os = "android", target_os="haiku")))]
214         use libc::F_DUPFD_CLOEXEC;
215
216         let make_filedesc = |fd| {
217             let fd = FileDesc::new(fd);
218             fd.set_cloexec()?;
219             Ok(fd)
220         };
221         static TRY_CLOEXEC: AtomicBool =
222             AtomicBool::new(!cfg!(target_os = "android"));
223         let fd = self.raw();
224         if TRY_CLOEXEC.load(Ordering::Relaxed) {
225             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
226                 // We *still* call the `set_cloexec` method as apparently some
227                 // linux kernel at some point stopped setting CLOEXEC even
228                 // though it reported doing so on F_DUPFD_CLOEXEC.
229                 Ok(fd) => {
230                     return Ok(if cfg!(target_os = "linux") {
231                         make_filedesc(fd)?
232                     } else {
233                         FileDesc::new(fd)
234                     })
235                 }
236                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
237                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
238                 }
239                 Err(e) => return Err(e),
240             }
241         }
242         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
243     }
244 }
245
246 impl<'a> Read for &'a FileDesc {
247     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
248         (**self).read(buf)
249     }
250 }
251
252 impl AsInner<c_int> for FileDesc {
253     fn as_inner(&self) -> &c_int { &self.fd }
254 }
255
256 impl Drop for FileDesc {
257     fn drop(&mut self) {
258         // Note that errors are ignored when closing a file descriptor. The
259         // reason for this is that if an error occurs we don't actually know if
260         // the file descriptor was closed or not, and if we retried (for
261         // something like EINTR), we might close another valid file descriptor
262         // (opened after we closed ours.
263         let _ = unsafe { libc::close(self.fd) };
264     }
265 }