std/sys/pal/unix/
mod.rs

1#![allow(missing_docs, nonstandard_style)]
2
3use crate::io::ErrorKind;
4
5#[cfg(target_os = "fuchsia")]
6pub mod fuchsia;
7pub mod futex;
8#[cfg(target_os = "linux")]
9pub mod linux;
10pub mod os;
11pub mod pipe;
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::os::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::os::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 (sigpipe_attr_specified, 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 sigpipe_attr_specified {
181                ON_BROKEN_PIPE_FLAG_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_FLAG_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_flag_used() -> bool {
216    ON_BROKEN_PIPE_FLAG_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#[inline]
229pub(crate) fn is_interrupted(errno: i32) -> bool {
230    errno == libc::EINTR
231}
232
233pub fn decode_error_kind(errno: i32) -> ErrorKind {
234    use ErrorKind::*;
235    match errno as libc::c_int {
236        libc::E2BIG => ArgumentListTooLong,
237        libc::EADDRINUSE => AddrInUse,
238        libc::EADDRNOTAVAIL => AddrNotAvailable,
239        libc::EBUSY => ResourceBusy,
240        libc::ECONNABORTED => ConnectionAborted,
241        libc::ECONNREFUSED => ConnectionRefused,
242        libc::ECONNRESET => ConnectionReset,
243        libc::EDEADLK => Deadlock,
244        libc::EDQUOT => QuotaExceeded,
245        libc::EEXIST => AlreadyExists,
246        libc::EFBIG => FileTooLarge,
247        libc::EHOSTUNREACH => HostUnreachable,
248        libc::EINTR => Interrupted,
249        libc::EINVAL => InvalidInput,
250        libc::EISDIR => IsADirectory,
251        libc::ELOOP => FilesystemLoop,
252        libc::ENOENT => NotFound,
253        libc::ENOMEM => OutOfMemory,
254        libc::ENOSPC => StorageFull,
255        libc::ENOSYS => Unsupported,
256        libc::EMLINK => TooManyLinks,
257        libc::ENAMETOOLONG => InvalidFilename,
258        libc::ENETDOWN => NetworkDown,
259        libc::ENETUNREACH => NetworkUnreachable,
260        libc::ENOTCONN => NotConnected,
261        libc::ENOTDIR => NotADirectory,
262        #[cfg(not(target_os = "aix"))]
263        libc::ENOTEMPTY => DirectoryNotEmpty,
264        libc::EPIPE => BrokenPipe,
265        libc::EROFS => ReadOnlyFilesystem,
266        libc::ESPIPE => NotSeekable,
267        libc::ESTALE => StaleNetworkFileHandle,
268        libc::ETIMEDOUT => TimedOut,
269        libc::ETXTBSY => ExecutableFileBusy,
270        libc::EXDEV => CrossesDevices,
271        libc::EINPROGRESS => InProgress,
272        libc::EOPNOTSUPP => Unsupported,
273
274        libc::EACCES | libc::EPERM => PermissionDenied,
275
276        // These two constants can have the same value on some systems,
277        // but different values on others, so we can't use a match
278        // clause
279        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
280
281        _ => Uncategorized,
282    }
283}
284
285#[doc(hidden)]
286pub trait IsMinusOne {
287    fn is_minus_one(&self) -> bool;
288}
289
290macro_rules! impl_is_minus_one {
291    ($($t:ident)*) => ($(impl IsMinusOne for $t {
292        fn is_minus_one(&self) -> bool {
293            *self == -1
294        }
295    })*)
296}
297
298impl_is_minus_one! { i8 i16 i32 i64 isize }
299
300/// Converts native return values to Result using the *-1 means error is in `errno`*  convention.
301/// Non-error values are `Ok`-wrapped.
302pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
303    if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
304}
305
306/// `-1` → look at `errno` → retry on `EINTR`. Otherwise `Ok()`-wrap the closure return value.
307pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
308where
309    T: IsMinusOne,
310    F: FnMut() -> T,
311{
312    loop {
313        match cvt(f()) {
314            Err(ref e) if e.is_interrupted() => {}
315            other => return other,
316        }
317    }
318}
319
320#[allow(dead_code)] // Not used on all platforms.
321/// Zero means `Ok()`, all other values are treated as raw OS errors. Does not look at `errno`.
322pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
323    if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
324}
325
326// libc::abort() will run the SIGABRT handler.  That's fine because anyone who
327// installs a SIGABRT handler already has to expect it to run in Very Bad
328// situations (eg, malloc crashing).
329//
330// Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
331// SIGABRT handler and raises it again, and then starts to get creative.
332//
333// See the public documentation for `intrinsics::abort()` and `process::abort()`
334// for further discussion.
335//
336// There is confusion about whether libc::abort() flushes stdio streams.
337// libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
338// so flushing streams is at least extremely hard, if not entirely impossible.
339//
340// However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
341// do so.  In 1003.1-2004 this was fixed.
342//
343// glibc's implementation did the flush, unsafely, before glibc commit
344// 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]` by Florian
345// Weimer.  According to glibc's NEWS:
346//
347//    The abort function terminates the process immediately, without flushing
348//    stdio streams.  Previous glibc versions used to flush streams, resulting
349//    in deadlocks and further data corruption.  This change also affects
350//    process aborts as the result of assertion failures.
351//
352// This is an accurate description of the problem.  The only solution for
353// program with nontrivial use of C stdio is a fixed libc - one which does not
354// try to flush in abort - since even libc-internal errors, and assertion
355// failures generated from C, will go via abort().
356//
357// On systems with old, buggy, libcs, the impact can be severe for a
358// multithreaded C program.  It is much less severe for Rust, because Rust
359// stdlib doesn't use libc stdio buffering.  In a typical Rust program, which
360// does not use C stdio, even a buggy libc::abort() is, in fact, safe.
361#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
362pub fn abort_internal() -> ! {
363    unsafe { libc::abort() }
364}
365
366cfg_select! {
367    target_os = "android" => {
368        #[link(name = "dl", kind = "static", modifiers = "-bundle",
369            cfg(target_feature = "crt-static"))]
370        #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
371        #[link(name = "log", cfg(not(target_feature = "crt-static")))]
372        unsafe extern "C" {}
373    }
374    target_os = "freebsd" => {
375        #[link(name = "execinfo")]
376        #[link(name = "pthread")]
377        unsafe extern "C" {}
378    }
379    target_os = "netbsd" => {
380        #[link(name = "execinfo")]
381        #[link(name = "pthread")]
382        #[link(name = "rt")]
383        unsafe extern "C" {}
384    }
385    any(target_os = "dragonfly", target_os = "openbsd", target_os = "cygwin") => {
386        #[link(name = "pthread")]
387        unsafe extern "C" {}
388    }
389    target_os = "solaris" => {
390        #[link(name = "socket")]
391        #[link(name = "posix4")]
392        #[link(name = "pthread")]
393        #[link(name = "resolv")]
394        unsafe extern "C" {}
395    }
396    target_os = "illumos" => {
397        #[link(name = "socket")]
398        #[link(name = "posix4")]
399        #[link(name = "pthread")]
400        #[link(name = "resolv")]
401        #[link(name = "nsl")]
402        // Use libumem for the (malloc-compatible) allocator
403        #[link(name = "umem")]
404        unsafe extern "C" {}
405    }
406    target_vendor = "apple" => {
407        // Link to `libSystem.dylib`.
408        //
409        // Don't get confused by the presence of `System.framework`,
410        // it is a deprecated wrapper over the dynamic library.
411        #[link(name = "System")]
412        unsafe extern "C" {}
413    }
414    target_os = "fuchsia" => {
415        #[link(name = "zircon")]
416        #[link(name = "fdio")]
417        unsafe extern "C" {}
418    }
419    all(target_os = "linux", target_env = "uclibc") => {
420        #[link(name = "dl")]
421        unsafe extern "C" {}
422    }
423    target_os = "vita" => {
424        #[link(name = "pthread", kind = "static", modifiers = "-bundle")]
425        unsafe extern "C" {}
426    }
427    _ => {}
428}
429
430#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita", target_os = "nuttx"))]
431pub mod unsupported {
432    use crate::io;
433
434    pub fn unsupported<T>() -> io::Result<T> {
435        Err(unsupported_err())
436    }
437
438    pub fn unsupported_err() -> io::Error {
439        io::Error::UNSUPPORTED_PLATFORM
440    }
441}