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