]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mod.rs
Reuse `unix::cmath`
[rust.git] / library / std / src / sys / unix / mod.rs
1 #![allow(missing_docs, nonstandard_style)]
2
3 use crate::io::ErrorKind;
4
5 pub use self::rand::hashmap_random_keys;
6 pub use libc::strlen;
7
8 #[macro_use]
9 pub mod weak;
10
11 pub mod alloc;
12 pub mod android;
13 pub mod args;
14 #[path = "../unix/cmath.rs"]
15 pub mod cmath;
16 pub mod condvar;
17 pub mod env;
18 pub mod ext;
19 pub mod fd;
20 pub mod fs;
21 pub mod futex;
22 pub mod io;
23 #[cfg(any(target_os = "linux", target_os = "android"))]
24 pub mod kernel_copy;
25 #[cfg(target_os = "l4re")]
26 mod l4re;
27 pub mod memchr;
28 pub mod mutex;
29 #[cfg(not(target_os = "l4re"))]
30 pub mod net;
31 #[cfg(target_os = "l4re")]
32 pub use self::l4re::net;
33 pub mod os;
34 pub mod path;
35 pub mod pipe;
36 pub mod process;
37 pub mod rand;
38 pub mod rwlock;
39 pub mod stack_overflow;
40 pub mod stdio;
41 pub mod thread;
42 pub mod thread_local_dtor;
43 pub mod thread_local_key;
44 pub mod time;
45
46 pub use crate::sys_common::os_str_bytes as os_str;
47
48 #[cfg(not(test))]
49 pub fn init() {
50     // The standard streams might be closed on application startup. To prevent
51     // std::io::{stdin, stdout,stderr} objects from using other unrelated file
52     // resources opened later, we reopen standards streams when they are closed.
53     unsafe {
54         sanitize_standard_fds();
55     }
56
57     // By default, some platforms will send a *signal* when an EPIPE error
58     // would otherwise be delivered. This runtime doesn't install a SIGPIPE
59     // handler, causing it to kill the program, which isn't exactly what we
60     // want!
61     //
62     // Hence, we set SIGPIPE to ignore when the program starts up in order
63     // to prevent this problem.
64     unsafe {
65         reset_sigpipe();
66     }
67
68     cfg_if::cfg_if! {
69         if #[cfg(miri)] {
70             // The standard fds are always available in Miri.
71             unsafe fn sanitize_standard_fds() {}
72         } else if #[cfg(not(any(
73             target_os = "emscripten",
74             target_os = "fuchsia",
75             target_os = "vxworks",
76             // The poll on Darwin doesn't set POLLNVAL for closed fds.
77             target_os = "macos",
78             target_os = "ios",
79             target_os = "redox",
80         )))] {
81             // In the case when all file descriptors are open, the poll has been
82             // observed to perform better than fcntl (on GNU/Linux).
83             unsafe fn sanitize_standard_fds() {
84                 use crate::sys::os::errno;
85                 let pfds: &mut [_] = &mut [
86                     libc::pollfd { fd: 0, events: 0, revents: 0 },
87                     libc::pollfd { fd: 1, events: 0, revents: 0 },
88                     libc::pollfd { fd: 2, events: 0, revents: 0 },
89                 ];
90                 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
91                     if errno() == libc::EINTR {
92                         continue;
93                     }
94                     libc::abort();
95                 }
96                 for pfd in pfds {
97                     if pfd.revents & libc::POLLNVAL == 0 {
98                         continue;
99                     }
100                     if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
101                         // If the stream is closed but we failed to reopen it, abort the
102                         // process. Otherwise we wouldn't preserve the safety of
103                         // operations on the corresponding Rust object Stdin, Stdout, or
104                         // Stderr.
105                         libc::abort();
106                     }
107                 }
108             }
109         } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
110             unsafe fn sanitize_standard_fds() {
111                 use crate::sys::os::errno;
112                 for fd in 0..3 {
113                     if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
114                         if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
115                             libc::abort();
116                         }
117                     }
118                 }
119             }
120         } else {
121             unsafe fn sanitize_standard_fds() {}
122         }
123     }
124
125     #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
126     unsafe fn reset_sigpipe() {
127         assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
128     }
129     #[cfg(any(target_os = "emscripten", target_os = "fuchsia"))]
130     unsafe fn reset_sigpipe() {}
131 }
132
133 #[cfg(target_os = "android")]
134 pub use crate::sys::android::signal;
135 #[cfg(not(target_os = "android"))]
136 pub use libc::signal;
137
138 pub fn decode_error_kind(errno: i32) -> ErrorKind {
139     match errno as libc::c_int {
140         libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
141         libc::ECONNRESET => ErrorKind::ConnectionReset,
142         libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
143         libc::EPIPE => ErrorKind::BrokenPipe,
144         libc::ENOTCONN => ErrorKind::NotConnected,
145         libc::ECONNABORTED => ErrorKind::ConnectionAborted,
146         libc::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
147         libc::EADDRINUSE => ErrorKind::AddrInUse,
148         libc::ENOENT => ErrorKind::NotFound,
149         libc::EINTR => ErrorKind::Interrupted,
150         libc::EINVAL => ErrorKind::InvalidInput,
151         libc::ETIMEDOUT => ErrorKind::TimedOut,
152         libc::EEXIST => ErrorKind::AlreadyExists,
153         libc::ENOSYS => ErrorKind::Unsupported,
154
155         // These two constants can have the same value on some systems,
156         // but different values on others, so we can't use a match
157         // clause
158         x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock,
159
160         _ => ErrorKind::Other,
161     }
162 }
163
164 #[doc(hidden)]
165 pub trait IsMinusOne {
166     fn is_minus_one(&self) -> bool;
167 }
168
169 macro_rules! impl_is_minus_one {
170     ($($t:ident)*) => ($(impl IsMinusOne for $t {
171         fn is_minus_one(&self) -> bool {
172             *self == -1
173         }
174     })*)
175 }
176
177 impl_is_minus_one! { i8 i16 i32 i64 isize }
178
179 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
180     if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
181 }
182
183 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
184 where
185     T: IsMinusOne,
186     F: FnMut() -> T,
187 {
188     loop {
189         match cvt(f()) {
190             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
191             other => return other,
192         }
193     }
194 }
195
196 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
197     if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
198 }
199
200 // On Unix-like platforms, libc::abort will unregister signal handlers
201 // including the SIGABRT handler, preventing the abort from being blocked, and
202 // fclose streams, with the side effect of flushing them so libc buffered
203 // output will be printed.  Additionally the shell will generally print a more
204 // understandable error message like "Abort trap" rather than "Illegal
205 // instruction" that intrinsics::abort would cause, as intrinsics::abort is
206 // implemented as an illegal instruction.
207 pub fn abort_internal() -> ! {
208     unsafe { libc::abort() }
209 }
210
211 cfg_if::cfg_if! {
212     if #[cfg(target_os = "android")] {
213         #[link(name = "dl")]
214         #[link(name = "log")]
215         #[link(name = "gcc")]
216         extern "C" {}
217     } else if #[cfg(target_os = "freebsd")] {
218         #[link(name = "execinfo")]
219         #[link(name = "pthread")]
220         extern "C" {}
221     } else if #[cfg(target_os = "netbsd")] {
222         #[link(name = "pthread")]
223         #[link(name = "rt")]
224         extern "C" {}
225     } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
226         #[link(name = "pthread")]
227         extern "C" {}
228     } else if #[cfg(target_os = "solaris")] {
229         #[link(name = "socket")]
230         #[link(name = "posix4")]
231         #[link(name = "pthread")]
232         #[link(name = "resolv")]
233         extern "C" {}
234     } else if #[cfg(target_os = "illumos")] {
235         #[link(name = "socket")]
236         #[link(name = "posix4")]
237         #[link(name = "pthread")]
238         #[link(name = "resolv")]
239         #[link(name = "nsl")]
240         // Use libumem for the (malloc-compatible) allocator
241         #[link(name = "umem")]
242         extern "C" {}
243     } else if #[cfg(target_os = "macos")] {
244         #[link(name = "System")]
245         // res_init and friends require -lresolv on macOS/iOS.
246         // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
247         #[link(name = "resolv")]
248         extern "C" {}
249     } else if #[cfg(target_os = "ios")] {
250         #[link(name = "System")]
251         #[link(name = "objc")]
252         #[link(name = "Security", kind = "framework")]
253         #[link(name = "Foundation", kind = "framework")]
254         #[link(name = "resolv")]
255         extern "C" {}
256     } else if #[cfg(target_os = "fuchsia")] {
257         #[link(name = "zircon")]
258         #[link(name = "fdio")]
259         extern "C" {}
260     }
261 }