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