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