std/sys/pal/unix/
mod.rs

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