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 target_os = "l4re",
149 // Unikraft's `signal` implementation is currently broken:
150 // https://github.com/unikraft/lib-musl/issues/57
151 target_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!
160 mod sigpipe {
161 pub const DEFAULT: u8 = 0;
162 pub const INHERIT: u8 = 1;
163 pub const SIG_IGN: u8 = 2;
164 pub const SIG_DFL: u8 = 3;
165 }
166
167 let (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 _ => unreachable!(),
173 };
174 if on_broken_pipe_used {
175 ON_BROKEN_PIPE_USED.store(true, crate::sync::atomic::Ordering::Relaxed);
176 }
177 if let Some(handler) = handler {
178 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
179 #[cfg(target_os = "hurd")]
180 {
181 rtassert!(signal(libc::SIGLOST, handler) != libc::SIG_ERR);
182 }
183 }
184 }
185 }
186}
187
188// 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> =
198 crate::sync::atomic::AtomicBool::new(false);
199
200#[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 {
210 ON_BROKEN_PIPE_USED.load(crate::sync::atomic::Ordering::Relaxed)
211}
212
213// 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() {}
218
219#[allow(unused_imports)]
220pub use libc::signal;
221
222#[doc(hidden)]
223pub trait IsMinusOne {
224 fn is_minus_one(&self) -> bool;
225}
226
227macro_rules! impl_is_minus_one {
228 ($($t:ident)*) => ($(impl IsMinusOne for $t {
229 fn is_minus_one(&self) -> bool {
230 *self == -1
231 }
232 })*)
233}
234
235impl_is_minus_one! { i8 i16 i32 i64 isize }
236
237/// 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> {
240 if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) }
241}
242
243/// `-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
246 T: IsMinusOne,
247 F: FnMut() -> T,
248{
249 loop {
250 match cvt(f()) {
251 Err(ref e) if e.is_interrupted() => {}
252 other => return other,
253 }
254 }
255}
256
257#[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<()> {
260 if error == 0 { Ok(()) } else { Err(io::Error::from_raw_os_error(error)) }
261}
262
263// 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() -> ! {
300 unsafe { libc::abort() }
301}
302
303cfg_select! {
304 target_os = "android" => {
305 #[link(name = "dl", kind = "static", modifiers = "-bundle",
306 cfg(target_feature = "crt-static"))]
307 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
308 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
309 unsafe extern "C" {}
310 }
311 target_os = "freebsd" => {
312 #[link(name = "execinfo")]
313 #[link(name = "pthread")]
314 unsafe extern "C" {}
315 }
316 target_os = "netbsd" => {
317 #[link(name = "execinfo")]
318 #[link(name = "pthread")]
319 #[link(name = "rt")]
320 unsafe extern "C" {}
321 }
322 any(target_os = "dragonfly", target_os = "openbsd", target_os = "cygwin") => {
323 #[link(name = "pthread")]
324 unsafe extern "C" {}
325 }
326 target_os = "solaris" => {
327 #[link(name = "socket")]
328 #[link(name = "posix4")]
329 #[link(name = "pthread")]
330 #[link(name = "resolv")]
331 unsafe extern "C" {}
332 }
333 target_os = "illumos" => {
334 #[link(name = "socket")]
335 #[link(name = "posix4")]
336 #[link(name = "pthread")]
337 #[link(name = "resolv")]
338 #[link(name = "nsl")]
339 // Use libumem for the (malloc-compatible) allocator
340 #[link(name = "umem")]
341 unsafe extern "C" {}
342 }
343 target_vendor = "apple" => {
344 // Link to `libSystem.dylib`.
345 //
346 // Don't get confused by the presence of `System.framework`,
347 // it is a deprecated wrapper over the dynamic library.
348 #[link(name = "System")]
349 unsafe extern "C" {}
350 }
351 target_os = "fuchsia" => {
352 #[link(name = "zircon")]
353 #[link(name = "fdio")]
354 unsafe extern "C" {}
355 }
356 all(target_os = "linux", target_env = "uclibc") => {
357 #[link(name = "dl")]
358 unsafe extern "C" {}
359 }
360 target_os = "vita" => {
361 #[link(name = "pthread", kind = "static", modifiers = "-bundle")]
362 unsafe extern "C" {}
363 }
364 _ => {}
365}
366
367#[cfg(any(
368 target_os = "espidf",
369 target_os = "horizon",
370 target_os = "vita",
371 target_os = "nuttx",
372 target_os = "l4re",
373))]
374pub fn unsupported<T>() -> crate::io::Result<T> {
375 Err(unsupported_err())
376}
377
378#[cfg(any(
379 target_os = "espidf",
380 target_os = "horizon",
381 target_os = "vita",
382 target_os = "nuttx",
383 target_os = "l4re",
384))]
385pub fn unsupported_err() -> crate::io::Error {
386 io::Error::UNSUPPORTED_PLATFORM
387}