std/sys/pal/unix/mod.rs
1#![allow(missing_docs, nonstandard_style)]
2
3use crate::io;
4
5#[cfg(target_os = "fuchsia")]
6pub mod fuchsia;
7pub mod futex;
8#[cfg(target_os = "linux")]
9pub mod linux;
10pub mod os;
11pub mod stack_overflow;
12pub mod sync;
13pub mod thread_parking;
14pub mod time;
15pub mod weak;
16
17#[cfg(target_os = "espidf")]
18pub fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {}
19
20#[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.
29 sanitize_standard_fds();
30
31 // 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.
39 reset_sigpipe(sigpipe);
40
41 stack_overflow::init();
42 #[cfg(not(target_os = "vita"))]
43 crate::sys::args::init(argc, argv);
44
45 // 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.
50 if cfg!(target_vendor = "apple") {
51 crate::sys::thread::set_name(c"main");
52 }
53
54 unsafe fn sanitize_standard_fds() {
55 #[allow(dead_code, unused_variables, unused_mut)]
56 let mut opened_devnull = -1;
57 #[allow(dead_code, unused_variables, unused_mut)]
58 let mut open_devnull = || {
59 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
60 use libc::open;
61 #[cfg(all(target_os = "linux", target_env = "gnu"))]
62 use libc::open64 as open;
63
64 if opened_devnull != -1 {
65 if libc::dup(opened_devnull) != -1 {
66 return;
67 }
68 }
69 opened_devnull = open(c"/dev/null".as_ptr(), libc::O_RDWR, 0);
70 if 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.
75 libc::abort();
76 }
77 };
78
79 // fast path with a single syscall for systems with poll()
80 #[cfg(not(any(
81 miri,
82 target_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.
91 target_vendor = "apple",
92 )))]
93 'poll: {
94 use crate::sys::io::errno;
95 let 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 ];
100
101 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
102 match errno() {
103 libc::EINTR => continue,
104 #[cfg(target_vendor = "unikraft")]
105 libc::ENOSYS => {
106 // Not all configurations of Unikraft enable `LIBPOSIX_EVENT`.
107 break '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
112 break 'poll;
113 }
114 _ => libc::abort(),
115 }
116 }
117 for pfd in pfds {
118 if pfd.revents & libc::POLLNVAL == 0 {
119 continue;
120 }
121 open_devnull();
122 }
123 return;
124 }
125
126 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
127 #[cfg(not(any(
128 // The standard fds are always available in Miri.
129 miri,
130 target_os = "emscripten",
131 target_os = "fuchsia",
132 target_os = "vxworks",
133 target_os = "l4re",
134 target_os = "horizon",
135 target_os = "vita",
136 )))]
137 {
138 use crate::sys::io::errno;
139 for fd in 0..3 {
140 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
141 open_devnull();
142 }
143 }
144 }
145 }
146
147 unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
148 #[cfg(not(any(
149 target_os = "emscripten",
150 target_os = "fuchsia",
151 target_os = "horizon",
152 target_os = "vxworks",
153 target_os = "vita",
154 // Unikraft's `signal` implementation is currently broken:
155 // https://github.com/unikraft/lib-musl/issues/57
156 target_vendor = "unikraft",
157 )))]
158 {
159 // We don't want to add this as a public type to std, nor do we
160 // want to `include!` a file from the compiler (which would break
161 // Miri and xargo for example), so we choose to duplicate these
162 // constants from `compiler/rustc_session/src/config/sigpipe.rs`.
163 // See the other file for docs. NOTE: Make sure to keep them in
164 // sync!
165 mod sigpipe {
166 pub const DEFAULT: u8 = 0;
167 pub const INHERIT: u8 = 1;
168 pub const SIG_IGN: u8 = 2;
169 pub const SIG_DFL: u8 = 3;
170 }
171
172 let (on_broken_pipe_used, handler) = match sigpipe {
173 sigpipe::DEFAULT => (false, Some(libc::SIG_IGN)),
174 sigpipe::INHERIT => (true, None),
175 sigpipe::SIG_IGN => (true, Some(libc::SIG_IGN)),
176 sigpipe::SIG_DFL => (true, Some(libc::SIG_DFL)),
177 _ => unreachable!(),
178 };
179 if on_broken_pipe_used {
180 ON_BROKEN_PIPE_USED.store(true, crate::sync::atomic::Ordering::Relaxed);
181 }
182 if let Some(handler) = handler {
183 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
184 #[cfg(target_os = "hurd")]
185 {
186 rtassert!(signal(libc::SIGLOST, handler) != libc::SIG_ERR);
187 }
188 }
189 }
190 }
191}
192
193// This is set (up to once) in reset_sigpipe.
194#[cfg(not(any(
195 target_os = "espidf",
196 target_os = "emscripten",
197 target_os = "fuchsia",
198 target_os = "horizon",
199 target_os = "vxworks",
200 target_os = "vita",
201)))]
202static ON_BROKEN_PIPE_USED: crate::sync::atomic::Atomic<bool> =
203 crate::sync::atomic::AtomicBool::new(false);
204
205#[cfg(not(any(
206 target_os = "espidf",
207 target_os = "emscripten",
208 target_os = "fuchsia",
209 target_os = "horizon",
210 target_os = "vxworks",
211 target_os = "vita",
212 target_os = "nuttx",
213)))]
214pub(crate) fn on_broken_pipe_used() -> bool {
215 ON_BROKEN_PIPE_USED.load(crate::sync::atomic::Ordering::Relaxed)
216}
217
218// SAFETY: must be called only once during runtime cleanup.
219// NOTE: this is not guaranteed to run, for example when the program aborts.
220pub unsafe fn cleanup() {
221 stack_overflow::cleanup();
222}
223
224#[allow(unused_imports)]
225pub use libc::signal;
226
227#[doc(hidden)]
228pub trait IsMinusOne {
229 fn is_minus_one(&self) -> bool;
230}
231
232macro_rules! impl_is_minus_one {
233 ($($t:ident)*) => ($(impl IsMinusOne for $t {
234 fn is_minus_one(&self) -> bool {
235 *self == -1
236 }
237 })*)
238}
239
240impl_is_minus_one! { i8 i16 i32 i64 isize }
241
242/// Converts native return values to Result using the *-1 means error is in `errno`* convention.
243/// Non-error values are `Ok`-wrapped.
244pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
245 if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) }
246}
247
248/// `-1` → look at `errno` → retry on `EINTR`. Otherwise `Ok()`-wrap the closure return value.
249pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
250where
251 T: IsMinusOne,
252 F: FnMut() -> T,
253{
254 loop {
255 match cvt(f()) {
256 Err(ref e) if e.is_interrupted() => {}
257 other => return other,
258 }
259 }
260}
261
262#[allow(dead_code)] // Not used on all platforms.
263/// Zero means `Ok()`, all other values are treated as raw OS errors. Does not look at `errno`.
264pub fn cvt_nz(error: libc::c_int) -> io::Result<()> {
265 if error == 0 { Ok(()) } else { Err(io::Error::from_raw_os_error(error)) }
266}
267
268// libc::abort() will run the SIGABRT handler. That's fine because anyone who
269// installs a SIGABRT handler already has to expect it to run in Very Bad
270// situations (eg, malloc crashing).
271//
272// Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
273// SIGABRT handler and raises it again, and then starts to get creative.
274//
275// See the public documentation for `intrinsics::abort()` and `process::abort()`
276// for further discussion.
277//
278// There is confusion about whether libc::abort() flushes stdio streams.
279// libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
280// so flushing streams is at least extremely hard, if not entirely impossible.
281//
282// However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
283// do so. In 1003.1-2004 this was fixed.
284//
285// glibc's implementation did the flush, unsafely, before glibc commit
286// 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]` by Florian
287// Weimer. According to glibc's NEWS:
288//
289// The abort function terminates the process immediately, without flushing
290// stdio streams. Previous glibc versions used to flush streams, resulting
291// in deadlocks and further data corruption. This change also affects
292// process aborts as the result of assertion failures.
293//
294// This is an accurate description of the problem. The only solution for
295// program with nontrivial use of C stdio is a fixed libc - one which does not
296// try to flush in abort - since even libc-internal errors, and assertion
297// failures generated from C, will go via abort().
298//
299// On systems with old, buggy, libcs, the impact can be severe for a
300// multithreaded C program. It is much less severe for Rust, because Rust
301// stdlib doesn't use libc stdio buffering. In a typical Rust program, which
302// does not use C stdio, even a buggy libc::abort() is, in fact, safe.
303#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
304pub fn abort_internal() -> ! {
305 unsafe { libc::abort() }
306}
307
308cfg_select! {
309 target_os = "android" => {
310 #[link(name = "dl", kind = "static", modifiers = "-bundle",
311 cfg(target_feature = "crt-static"))]
312 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
313 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
314 unsafe extern "C" {}
315 }
316 target_os = "freebsd" => {
317 #[link(name = "execinfo")]
318 #[link(name = "pthread")]
319 unsafe extern "C" {}
320 }
321 target_os = "netbsd" => {
322 #[link(name = "execinfo")]
323 #[link(name = "pthread")]
324 #[link(name = "rt")]
325 unsafe extern "C" {}
326 }
327 any(target_os = "dragonfly", target_os = "openbsd", target_os = "cygwin") => {
328 #[link(name = "pthread")]
329 unsafe extern "C" {}
330 }
331 target_os = "solaris" => {
332 #[link(name = "socket")]
333 #[link(name = "posix4")]
334 #[link(name = "pthread")]
335 #[link(name = "resolv")]
336 unsafe extern "C" {}
337 }
338 target_os = "illumos" => {
339 #[link(name = "socket")]
340 #[link(name = "posix4")]
341 #[link(name = "pthread")]
342 #[link(name = "resolv")]
343 #[link(name = "nsl")]
344 // Use libumem for the (malloc-compatible) allocator
345 #[link(name = "umem")]
346 unsafe extern "C" {}
347 }
348 target_vendor = "apple" => {
349 // Link to `libSystem.dylib`.
350 //
351 // Don't get confused by the presence of `System.framework`,
352 // it is a deprecated wrapper over the dynamic library.
353 #[link(name = "System")]
354 unsafe extern "C" {}
355 }
356 target_os = "fuchsia" => {
357 #[link(name = "zircon")]
358 #[link(name = "fdio")]
359 unsafe extern "C" {}
360 }
361 all(target_os = "linux", target_env = "uclibc") => {
362 #[link(name = "dl")]
363 unsafe extern "C" {}
364 }
365 target_os = "vita" => {
366 #[link(name = "pthread", kind = "static", modifiers = "-bundle")]
367 unsafe extern "C" {}
368 }
369 _ => {}
370}
371
372#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita", target_os = "nuttx"))]
373pub mod unsupported {
374 use crate::io;
375
376 pub fn unsupported<T>() -> io::Result<T> {
377 Err(unsupported_err())
378 }
379
380 pub fn unsupported_err() -> io::Error {
381 io::Error::UNSUPPORTED_PLATFORM
382 }
383}