]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fd.rs
Implement reading and writing atomically at certain offsets
[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 io::{self, Read};
14 use libc::{self, c_int, c_void};
15 use mem;
16 use sync::atomic::{AtomicBool, Ordering};
17 use sys::cvt;
18 use sys_common::AsInner;
19 use sys_common::io::read_to_end_uninitialized;
20
21 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
22 use libc::{pread64, pwrite64, off64_t};
23 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
24 use libc::{pread as pread64, pwrite as pwrite64, off_t as off64_t};
25
26 pub struct FileDesc {
27     fd: c_int,
28 }
29
30 impl FileDesc {
31     pub fn new(fd: c_int) -> FileDesc {
32         FileDesc { fd: fd }
33     }
34
35     pub fn raw(&self) -> c_int { self.fd }
36
37     /// Extracts the actual filedescriptor without closing it.
38     pub fn into_raw(self) -> c_int {
39         let fd = self.fd;
40         mem::forget(self);
41         fd
42     }
43
44     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
45         let ret = cvt(unsafe {
46             libc::read(self.fd,
47                        buf.as_mut_ptr() as *mut c_void,
48                        buf.len())
49         })?;
50         Ok(ret as usize)
51     }
52
53     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
54         let mut me = self;
55         (&mut me).read_to_end(buf)
56     }
57
58     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
59         let ret = cvt(unsafe {
60             pread64(self.fd,
61                     buf.as_mut_ptr() as *mut c_void,
62                     buf.len(),
63                     offset as off64_t)
64         })?;
65         Ok(ret as usize)
66     }
67
68     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
69         let ret = cvt(unsafe {
70             libc::write(self.fd,
71                         buf.as_ptr() as *const c_void,
72                         buf.len())
73         })?;
74         Ok(ret as usize)
75     }
76
77     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
78         let ret = cvt(unsafe {
79             pwrite64(self.fd,
80                      buf.as_ptr() as *const c_void,
81                      buf.len(),
82                      offset as off64_t)
83         })?;
84         Ok(ret as usize)
85     }
86
87     #[cfg(not(any(target_env = "newlib",
88                   target_os = "solaris",
89                   target_os = "emscripten",
90                   target_os = "haiku")))]
91     pub fn set_cloexec(&self) -> io::Result<()> {
92         unsafe {
93             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
94             Ok(())
95         }
96     }
97     #[cfg(any(target_env = "newlib",
98               target_os = "solaris",
99               target_os = "emscripten",
100               target_os = "haiku"))]
101     pub fn set_cloexec(&self) -> io::Result<()> {
102         unsafe {
103             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
104             cvt(libc::fcntl(self.fd, libc::F_SETFD, previous | libc::FD_CLOEXEC))?;
105             Ok(())
106         }
107     }
108
109     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
110         unsafe {
111             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
112             let new = if nonblocking {
113                 previous | libc::O_NONBLOCK
114             } else {
115                 previous & !libc::O_NONBLOCK
116             };
117             cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
118             Ok(())
119         }
120     }
121
122     pub fn duplicate(&self) -> io::Result<FileDesc> {
123         // We want to atomically duplicate this file descriptor and set the
124         // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
125         // flag, however, isn't supported on older Linux kernels (earlier than
126         // 2.6.24).
127         //
128         // To detect this and ensure that CLOEXEC is still set, we
129         // follow a strategy similar to musl [1] where if passing
130         // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
131         // supported (the third parameter, 0, is always valid), so we stop
132         // trying that.
133         //
134         // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
135         // resolve so we at least compile this.
136         //
137         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
138         #[cfg(any(target_os = "android", target_os = "haiku"))]
139         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
140         #[cfg(not(any(target_os = "android", target_os="haiku")))]
141         use libc::F_DUPFD_CLOEXEC;
142
143         let make_filedesc = |fd| {
144             let fd = FileDesc::new(fd);
145             fd.set_cloexec()?;
146             Ok(fd)
147         };
148         static TRY_CLOEXEC: AtomicBool =
149             AtomicBool::new(!cfg!(target_os = "android"));
150         let fd = self.raw();
151         if TRY_CLOEXEC.load(Ordering::Relaxed) {
152             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
153                 // We *still* call the `set_cloexec` method as apparently some
154                 // linux kernel at some point stopped setting CLOEXEC even
155                 // though it reported doing so on F_DUPFD_CLOEXEC.
156                 Ok(fd) => {
157                     return Ok(if cfg!(target_os = "linux") {
158                         make_filedesc(fd)?
159                     } else {
160                         FileDesc::new(fd)
161                     })
162                 }
163                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
164                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
165                 }
166                 Err(e) => return Err(e),
167             }
168         }
169         cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
170     }
171 }
172
173 impl<'a> Read for &'a FileDesc {
174     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
175         (**self).read(buf)
176     }
177
178     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
179         unsafe { read_to_end_uninitialized(self, buf) }
180     }
181 }
182
183 impl AsInner<c_int> for FileDesc {
184     fn as_inner(&self) -> &c_int { &self.fd }
185 }
186
187 impl Drop for FileDesc {
188     fn drop(&mut self) {
189         // Note that errors are ignored when closing a file descriptor. The
190         // reason for this is that if an error occurs we don't actually know if
191         // the file descriptor was closed or not, and if we retried (for
192         // something like EINTR), we might close another valid file descriptor
193         // (opened after we closed ours.
194         let _ = unsafe { libc::close(self.fd) };
195     }
196 }