1#![allow(missing_docs, nonstandard_style)]
23use crate::io;
45pub mod conf;
6#[cfg(target_os = "fuchsia")]
7pub mod fuchsia;
8pub mod futex;
9pub mod stack_overflow;
10pub mod sync;
11pub mod thread_parking;
12pub mod time;
13pub mod weak;
1415#[cfg(target_os = "espidf")]
16pub fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {}
1718#[cfg(not(target_os = "espidf"))]
19#[cfg_attr(target_os = "vita", allow(unused_variables))]
20// SAFETY: must be called only once during runtime initialization.
21// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
22// See `fn init()` in `library/std/src/rt.rs` for docs on `sigpipe`.
23pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
24// The standard streams might be closed on application startup. To prevent
25 // std::io::{stdin, stdout,stderr} objects from using other unrelated file
26 // resources opened later, we reopen standards streams when they are closed.
27sanitize_standard_fds();
2829// By default, some platforms will send a *signal* when an EPIPE error
30 // would otherwise be delivered. This runtime doesn't install a SIGPIPE
31 // handler, causing it to kill the program, which isn't exactly what we
32 // want!
33 //
34 // Hence, we set SIGPIPE to ignore when the program starts up in order
35 // to prevent this problem. Use `-Zon-broken-pipe=...` to alter this
36 // behavior.
37reset_sigpipe(sigpipe);
3839 stack_overflow::init();
40#[cfg(not(target_os = "vita"))]
41crate::sys::args::init(argc, argv);
4243// Normally, `thread::spawn` will call `Thread::set_name` but since this thread
44 // already exists, we have to call it ourselves. We only do this on Apple targets
45 // because some unix-like operating systems such as Linux share process-id and
46 // thread-id for the main thread and so renaming the main thread will rename the
47 // process and we only want to enable this on platforms we've tested.
48if falsecfg!(target_vendor = "apple") {
49crate::sys::thread::set_name(c"main");
50 }
5152unsafe fn sanitize_standard_fds() {
53#[allow(dead_code, unused_variables, unused_mut)]
54let mut opened_devnull = -1;
55#[allow(dead_code, unused_variables, unused_mut)]
56let mut open_devnull = || {
57#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
58use libc::open;
59#[cfg(all(target_os = "linux", target_env = "gnu"))]
60use libc::open64as open;
6162if opened_devnull != -1 {
63if libc::dup(opened_devnull) != -1 {
64return;
65 }
66 }
67opened_devnull = open(c"/dev/null".as_ptr(), libc::O_RDWR, 0);
68if opened_devnull == -1 {
69// If the stream is closed but we failed to reopen it, abort the
70 // process. Otherwise we wouldn't preserve the safety of
71 // operations on the corresponding Rust object Stdin, Stdout, or
72 // Stderr.
73libc::abort();
74 }
75 };
7677// fast path with a single syscall for systems with poll()
78#[cfg(not(any(
79 miri, // no `poll`
80target_os = "emscripten",
81 target_os = "fuchsia",
82 target_os = "vxworks",
83 target_os = "redox",
84 target_os = "l4re",
85 target_os = "horizon",
86 target_os = "vita",
87 target_os = "rtems",
88// The poll on Darwin doesn't set POLLNVAL for closed fds.
89target_vendor = "apple",
90 )))]
91'poll: {
92use crate::sys::io::errno;
93let pfds: &mut [_] = &mut [
94 libc::pollfd { fd: 0, events: 0, revents: 0 },
95 libc::pollfd { fd: 1, events: 0, revents: 0 },
96 libc::pollfd { fd: 2, events: 0, revents: 0 },
97 ];
9899while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
100match errno() {
101 libc::EINTR => continue,
102#[cfg(target_vendor = "unikraft")]
103libc::ENOSYS => {
104// Not all configurations of Unikraft enable `LIBPOSIX_EVENT`.
105break 'poll;
106 }
107 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
108// RLIMIT_NOFILE or temporary allocation failures
109 // may be preventing use of poll(), fall back to fcntl
110break 'poll;
111 }
112_ => libc::abort(),
113 }
114 }
115for pfd in pfds {
116if pfd.revents & libc::POLLNVAL == 0 {
117continue;
118 }
119 open_devnull();
120 }
121return;
122 }
123124// fallback in case poll isn't available or limited by RLIMIT_NOFILE
125#[cfg(not(any(
126 target_os = "emscripten",
127 target_os = "fuchsia",
128 target_os = "vxworks",
129 target_os = "l4re",
130 target_os = "horizon",
131 target_os = "vita",
132 )))]
133{
134use crate::sys::io::errno;
135for fd in 0..3 {
136if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
137 open_devnull();
138 }
139 }
140 }
141 }
142143unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
144#[cfg(not(any(
145 target_os = "emscripten",
146 target_os = "fuchsia",
147 target_os = "horizon",
148 target_os = "vxworks",
149 target_os = "vita",
150// Unikraft's `signal` implementation is currently broken:
151 // https://github.com/unikraft/lib-musl/issues/57
152target_vendor = "unikraft",
153 )))]
154{
155// We don't want to add this as a public type to std, nor do we
156 // want to `include!` a file from the compiler (which would break
157 // Miri and xargo for example), so we choose to duplicate these
158 // constants from `compiler/rustc_session/src/config/sigpipe.rs`.
159 // See the other file for docs. NOTE: Make sure to keep them in
160 // sync!
161mod sigpipe {
162pub const DEFAULT: u8 = 0;
163pub const INHERIT: u8 = 1;
164pub const SIG_IGN: u8 = 2;
165pub const SIG_DFL: u8 = 3;
166 }
167168let (on_broken_pipe_used, handler) = match sigpipe {
169 sigpipe::DEFAULT => (false, Some(libc::SIG_IGN)),
170 sigpipe::INHERIT => (true, None),
171 sigpipe::SIG_IGN => (true, Some(libc::SIG_IGN)),
172 sigpipe::SIG_DFL => (true, Some(libc::SIG_DFL)),
173_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
174 };
175if on_broken_pipe_used {
176ON_BROKEN_PIPE_USED.store(true, crate::sync::atomic::Ordering::Relaxed);
177 }
178if let Some(handler) = handler {
179if !(signal(libc::SIGPIPE, handler) != libc::SIG_ERR) {
{
if let Some(mut out) = crate::sys::stdio::panic_output() {
let _ =
crate::io::Write::write_fmt(&mut out,
format_args!("fatal runtime error: {0}, aborting\n",
format_args!("assertion failed: signal(libc::SIGPIPE, handler) != libc::SIG_ERR")));
};
crate::process::abort();
};
};rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
180#[cfg(target_os = "hurd")]
181{
182rtassert!(signal(libc::SIGLOST, handler) != libc::SIG_ERR);
183 }
184 }
185 }
186 }
187}
188189// This is set (up to once) in reset_sigpipe.
190#[cfg(not(any(
191 target_os = "espidf",
192 target_os = "emscripten",
193 target_os = "fuchsia",
194 target_os = "horizon",
195 target_os = "vxworks",
196 target_os = "vita",
197)))]
198static ON_BROKEN_PIPE_USED: crate::sync::atomic::Atomic<bool> =
199crate::sync::atomic::AtomicBool::new(false);
200201#[cfg(not(any(
202 target_os = "espidf",
203 target_os = "emscripten",
204 target_os = "fuchsia",
205 target_os = "horizon",
206 target_os = "vxworks",
207 target_os = "vita",
208 target_os = "nuttx",
209)))]
210pub(crate) fn on_broken_pipe_used() -> bool {
211ON_BROKEN_PIPE_USED.load(crate::sync::atomic::Ordering::Relaxed)
212}
213214// SAFETY: must be called only once during runtime cleanup.
215// NOTE: this is not guaranteed to run, for example when the program aborts.
216pub unsafe fn cleanup() {
217 stack_overflow::cleanup();
218}
219220#[allow(unused_imports)]
221pub use libc::signal;
222223#[doc(hidden)]
224pub trait IsMinusOne {
225fn is_minus_one(&self) -> bool;
226}
227228macro_rules!impl_is_minus_one {
229 ($($t:ident)*) => ($(impl IsMinusOne for $t {
230fn is_minus_one(&self) -> bool {
231*self == -1
232}
233 })*)
234}
235236impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}impl_is_minus_one! { i8 i16 i32 i64 isize }237238/// Converts native return values to Result using the *-1 means error is in `errno`* convention.
239/// Non-error values are `Ok`-wrapped.
240pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
241if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) }
242}
243244/// `-1` → look at `errno` → retry on `EINTR`. Otherwise `Ok()`-wrap the closure return value.
245pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
246where
247T: IsMinusOne,
248 F: FnMut() -> T,
249{
250loop {
251match cvt(f()) {
252Err(ref e) if e.is_interrupted() => {}
253 other => return other,
254 }
255 }
256}
257258#[allow(dead_code)] // Not used on all platforms.
259/// Zero means `Ok()`, all other values are treated as raw OS errors. Does not look at `errno`.
260pub fn cvt_nz(error: libc::c_int) -> io::Result<()> {
261if error == 0 { Ok(()) } else { Err(io::Error::from_raw_os_error(error)) }
262}
263264// libc::abort() will run the SIGABRT handler. That's fine because anyone who
265// installs a SIGABRT handler already has to expect it to run in Very Bad
266// situations (eg, malloc crashing).
267//
268// Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
269// SIGABRT handler and raises it again, and then starts to get creative.
270//
271// See the public documentation for `intrinsics::abort()` and `process::abort()`
272// for further discussion.
273//
274// There is confusion about whether libc::abort() flushes stdio streams.
275// libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
276// so flushing streams is at least extremely hard, if not entirely impossible.
277//
278// However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
279// do so. In 1003.1-2004 this was fixed.
280//
281// glibc's implementation did the flush, unsafely, before glibc commit
282// 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]` by Florian
283// Weimer. According to glibc's NEWS:
284//
285// The abort function terminates the process immediately, without flushing
286// stdio streams. Previous glibc versions used to flush streams, resulting
287// in deadlocks and further data corruption. This change also affects
288// process aborts as the result of assertion failures.
289//
290// This is an accurate description of the problem. The only solution for
291// program with nontrivial use of C stdio is a fixed libc - one which does not
292// try to flush in abort - since even libc-internal errors, and assertion
293// failures generated from C, will go via abort().
294//
295// On systems with old, buggy, libcs, the impact can be severe for a
296// multithreaded C program. It is much less severe for Rust, because Rust
297// stdlib doesn't use libc stdio buffering. In a typical Rust program, which
298// does not use C stdio, even a buggy libc::abort() is, in fact, safe.
299#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
300pub fn abort_internal() -> ! {
301unsafe { libc::abort() }
302}
303304cfg_select! {
305 target_os = "android" => {
306#[link(name = "dl", kind = "static", modifiers = "-bundle",
307 cfg(target_feature = "crt-static"))]
308 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
309 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
310unsafe extern "C" {}
311 }
312 target_os = "freebsd" => {
313#[link(name = "execinfo")]
314 #[link(name = "pthread")]
315unsafe extern "C" {}
316 }
317 target_os = "netbsd" => {
318#[link(name = "execinfo")]
319 #[link(name = "pthread")]
320 #[link(name = "rt")]
321unsafe extern "C" {}
322 }
323 any(target_os = "dragonfly", target_os = "openbsd", target_os = "cygwin") => {
324#[link(name = "pthread")]
325unsafe extern "C" {}
326 }
327 target_os = "solaris" => {
328#[link(name = "socket")]
329 #[link(name = "posix4")]
330 #[link(name = "pthread")]
331 #[link(name = "resolv")]
332unsafe extern "C" {}
333 }
334 target_os = "illumos" => {
335#[link(name = "socket")]
336 #[link(name = "posix4")]
337 #[link(name = "pthread")]
338 #[link(name = "resolv")]
339 #[link(name = "nsl")]
340// Use libumem for the (malloc-compatible) allocator
341#[link(name = "umem")]
342unsafe extern "C" {}
343 }
344 target_vendor = "apple" => {
345// Link to `libSystem.dylib`.
346 //
347 // Don't get confused by the presence of `System.framework`,
348 // it is a deprecated wrapper over the dynamic library.
349#[link(name = "System")]
350unsafe extern "C" {}
351 }
352 target_os = "fuchsia" => {
353#[link(name = "zircon")]
354 #[link(name = "fdio")]
355unsafe extern "C" {}
356 }
357 all(target_os = "linux", target_env = "uclibc") => {
358#[link(name = "dl")]
359unsafe extern "C" {}
360 }
361 target_os = "vita" => {
362#[link(name = "pthread", kind = "static", modifiers = "-bundle")]
363unsafe extern "C" {}
364 }
365_ => {}
366}
367368#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita", target_os = "nuttx"))]
369pub mod unsupported {
370use crate::io;
371372pub fn unsupported<T>() -> io::Result<T> {
373Err(unsupported_err())
374 }
375376pub fn unsupported_err() -> io::Error {
377 io::Error::UNSUPPORTED_PLATFORM
378 }
379}