Skip to main content

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