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
92 let mut pfds: [libc::pollfd; 3] = crate::mem::zeroed();
93 pfds[0].fd = 0;
94 pfds[0].events = 0;
95 pfds[1].fd = 1;
96 pfds[1].events = 0;
97 pfds[2].fd = 2;
98 pfds[2].events = 0;
99
100 while libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, 0) == -1 {
101 match errno() {
102 libc::EINTR => continue,
103 #[cfg(target_vendor = "unikraft")]
104 libc::ENOSYS => {
105 // Not all configurations of Unikraft enable `LIBPOSIX_EVENT`.
106 break 'poll;
107 }
108 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
109 // RLIMIT_NOFILE or temporary allocation failures
110 // may be preventing use of poll(), fall back to fcntl
111 break 'poll;
112 }
113 _ => libc::abort(),
114 }
115 }
116 for pfd in pfds {
117 if pfd.revents & libc::POLLNVAL == 0 {
118 continue;
119 }
120 open_devnull();
121 }
122 return;
123 }
124
125 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
126 #[cfg(not(any(
127 target_os = "emscripten",
128 target_os = "fuchsia",
129 target_os = "vxworks",
130 target_os = "l4re",
131 target_os = "horizon",
132 target_os = "vita",
133 )))]
134 {
135 use crate::sys::io::errno;
136 for fd in 0..3 {
137 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
138 open_devnull();
139 }
140 }
141 }
142 }
143
144 unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
145 #[cfg(not(any(
146 target_os = "emscripten",
147 target_os = "fuchsia",
148 target_os = "horizon",
149 target_os = "vxworks",
150 target_os = "vita",
151 target_os = "l4re",
152 // Unikraft's `signal` implementation is currently broken:
153 // https://github.com/unikraft/lib-musl/issues/57
154 target_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!
163 mod sigpipe {
164 pub const DEFAULT: u8 = 0;
165 pub const INHERIT: u8 = 1;
166 pub const SIG_IGN: u8 = 2;
167 pub const SIG_DFL: u8 = 3;
168 }
169
170 let (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 _ => unreachable!(),
176 };
177 if on_broken_pipe_used {
178 ON_BROKEN_PIPE_USED.store(true, crate::sync::atomic::Ordering::Relaxed);
179 }
180 if let Some(handler) = handler {
181 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
182 #[cfg(target_os = "hurd")]
183 {
184 rtassert!(signal(libc::SIGLOST, handler) != libc::SIG_ERR);
185 }
186 }
187 }
188 }
189}
190
191// 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 target_os = "l4re",
200)))]
201static ON_BROKEN_PIPE_USED: crate::sync::atomic::Atomic<bool> =
202 crate::sync::atomic::AtomicBool::new(false);
203
204#[cfg(not(any(
205 target_os = "espidf",
206 target_os = "emscripten",
207 target_os = "fuchsia",
208 target_os = "horizon",
209 target_os = "vxworks",
210 target_os = "vita",
211 target_os = "nuttx",
212 target_os = "l4re",
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, and
220// is not guaranteed to run on the main thread (#161018 was caused by that
221// mistaken assumption).
222pub unsafe fn cleanup() {}
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_immediate()` and
276// `process::abort()` 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(
311 name = "dl",
312 kind = "static",
313 modifiers = "-bundle",
314 cfg(target_feature = "crt-static")
315 )]
316 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
317 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
318 unsafe extern "C" {}
319 }
320 target_os = "freebsd" => {
321 #[link(name = "execinfo")]
322 #[link(name = "pthread")]
323 unsafe extern "C" {}
324 }
325 target_os = "netbsd" => {
326 #[link(name = "execinfo")]
327 #[link(name = "pthread")]
328 #[link(name = "rt")]
329 unsafe extern "C" {}
330 }
331 any(target_os = "dragonfly", target_os = "openbsd", target_os = "cygwin") => {
332 #[link(name = "pthread")]
333 unsafe extern "C" {}
334 }
335 target_os = "solaris" => {
336 #[link(name = "socket")]
337 #[link(name = "posix4")]
338 #[link(name = "pthread")]
339 #[link(name = "resolv")]
340 unsafe extern "C" {}
341 }
342 target_os = "illumos" => {
343 #[link(name = "socket")]
344 #[link(name = "posix4")]
345 #[link(name = "pthread")]
346 #[link(name = "resolv")]
347 #[link(name = "nsl")]
348 // Use libumem for the (malloc-compatible) allocator
349 #[link(name = "umem")]
350 unsafe extern "C" {}
351 }
352 target_vendor = "apple" => {
353 // Link to `libSystem.dylib`.
354 //
355 // Don't get confused by the presence of `System.framework`,
356 // it is a deprecated wrapper over the dynamic library.
357 #[link(name = "System")]
358 unsafe extern "C" {}
359 }
360 target_os = "fuchsia" => {
361 #[link(name = "zircon")]
362 #[link(name = "fdio")]
363 unsafe extern "C" {}
364 }
365 all(target_os = "linux", target_env = "uclibc") => {
366 #[link(name = "dl")]
367 unsafe extern "C" {}
368 }
369 target_os = "vita" => {
370 #[link(name = "pthread", kind = "static", modifiers = "-bundle")]
371 unsafe extern "C" {}
372 }
373 _ => {}
374}
375
376#[cfg(any(
377 target_os = "espidf",
378 target_os = "horizon",
379 target_os = "vita",
380 target_os = "nuttx",
381 target_os = "l4re",
382))]
383pub fn unsupported<T>() -> crate::io::Result<T> {
384 Err(unsupported_err())
385}
386
387#[cfg(any(
388 target_os = "espidf",
389 target_os = "horizon",
390 target_os = "vita",
391 target_os = "nuttx",
392 target_os = "l4re",
393))]
394pub fn unsupported_err() -> crate::io::Error {
395 io::Error::UNSUPPORTED_PLATFORM
396}