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