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