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