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