1 #![allow(missing_docs, nonstandard_style)]
4 use crate::io::ErrorKind;
6 pub use self::rand::hashmap_random_keys;
8 #[cfg(not(target_os = "espidf"))]
15 #[path = "../unix/cmath.rs"]
22 #[cfg(any(target_os = "linux", target_os = "android"))]
24 #[cfg(target_os = "l4re")]
28 #[cfg(not(target_os = "l4re"))]
30 #[cfg(target_os = "l4re")]
31 pub use self::l4re::net;
38 pub mod stack_overflow;
41 pub mod thread_local_dtor;
42 pub mod thread_local_key;
43 pub mod thread_parker;
46 #[cfg(target_os = "espidf")]
47 pub fn init(argc: isize, argv: *const *const u8, _sigpipe: u8) {}
49 #[cfg(not(target_os = "espidf"))]
50 // SAFETY: must be called only once during runtime initialization.
51 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
52 // See `fn init()` in `library/std/src/rt.rs` for docs on `sigpipe`.
53 pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
54 // The standard streams might be closed on application startup. To prevent
55 // std::io::{stdin, stdout,stderr} objects from using other unrelated file
56 // resources opened later, we reopen standards streams when they are closed.
57 sanitize_standard_fds();
59 // By default, some platforms will send a *signal* when an EPIPE error
60 // would otherwise be delivered. This runtime doesn't install a SIGPIPE
61 // handler, causing it to kill the program, which isn't exactly what we
64 // Hence, we set SIGPIPE to ignore when the program starts up in order
65 // to prevent this problem. Add `#[unix_sigpipe = "..."]` above `fn main()` to
66 // alter this behavior.
67 reset_sigpipe(sigpipe);
69 stack_overflow::init();
70 args::init(argc, argv);
72 // Normally, `thread::spawn` will call `Thread::set_name` but since this thread
73 // already exists, we have to call it ourselves. We only do this on macos
74 // because some unix-like operating systems such as Linux share process-id and
75 // thread-id for the main thread and so renaming the main thread will rename the
76 // process and we only want to enable this on platforms we've tested.
77 if cfg!(target_os = "macos") {
78 thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
81 unsafe fn sanitize_standard_fds() {
82 // fast path with a single syscall for systems with poll()
85 target_os = "emscripten",
86 target_os = "fuchsia",
87 target_os = "vxworks",
88 // The poll on Darwin doesn't set POLLNVAL for closed fds.
91 target_os = "watchos",
94 target_os = "horizon",
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 },
104 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
106 libc::EINTR => continue,
107 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
108 // RLIMIT_NOFILE or temporary allocation failures
109 // may be preventing use of poll(), fall back to fcntl
116 if pfd.revents & libc::POLLNVAL == 0 {
119 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
120 // If the stream is closed but we failed to reopen it, abort the
121 // process. Otherwise we wouldn't preserve the safety of
122 // operations on the corresponding Rust object Stdin, Stdout, or
130 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
132 // The standard fds are always available in Miri.
134 target_os = "emscripten",
135 target_os = "fuchsia",
136 target_os = "vxworks",
138 target_os = "horizon",
141 use crate::sys::os::errno;
143 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
144 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
145 // If the stream is closed but we failed to reopen it, abort the
146 // process. Otherwise we wouldn't preserve the safety of
147 // operations on the corresponding Rust object Stdin, Stdout, or
156 unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
157 #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia", target_os = "horizon")))]
159 // We don't want to add this as a public type to libstd, nor do we
160 // want to `include!` a file from the compiler (which would break
161 // Miri and xargo for example), so we choose to duplicate these
162 // constants from `compiler/rustc_session/src/config/sigpipe.rs`.
163 // See the other file for docs. NOTE: Make sure to keep them in
166 pub const DEFAULT: u8 = 0;
167 pub const INHERIT: u8 = 1;
168 pub const SIG_IGN: u8 = 2;
169 pub const SIG_DFL: u8 = 3;
172 let (sigpipe_attr_specified, handler) = match sigpipe {
173 sigpipe::DEFAULT => (false, Some(libc::SIG_IGN)),
174 sigpipe::INHERIT => (true, None),
175 sigpipe::SIG_IGN => (true, Some(libc::SIG_IGN)),
176 sigpipe::SIG_DFL => (true, Some(libc::SIG_DFL)),
179 // The bootstrap compiler doesn't know about sigpipe::DEFAULT, and always passes in
180 // SIG_IGN. This causes some tests to fail because they expect SIGPIPE to be reset to
181 // default on process spawning (which doesn't happen if #[unix_sigpipe] is specified).
182 // Since we can't differentiate between the cases here, treat SIG_IGN as DEFAULT
184 if sigpipe_attr_specified && !(cfg!(bootstrap) && sigpipe == sigpipe::SIG_IGN) {
185 UNIX_SIGPIPE_ATTR_SPECIFIED.store(true, crate::sync::atomic::Ordering::Relaxed);
187 if let Some(handler) = handler {
188 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
194 // This is set (up to once) in reset_sigpipe.
196 target_os = "espidf",
197 target_os = "emscripten",
198 target_os = "fuchsia",
199 target_os = "horizon"
201 static UNIX_SIGPIPE_ATTR_SPECIFIED: crate::sync::atomic::AtomicBool =
202 crate::sync::atomic::AtomicBool::new(false);
205 target_os = "espidf",
206 target_os = "emscripten",
207 target_os = "fuchsia",
208 target_os = "horizon"
210 pub(crate) fn unix_sigpipe_attr_specified() -> bool {
211 UNIX_SIGPIPE_ATTR_SPECIFIED.load(crate::sync::atomic::Ordering::Relaxed)
214 // SAFETY: must be called only once during runtime cleanup.
215 // NOTE: this is not guaranteed to run, for example when the program aborts.
216 pub unsafe fn cleanup() {
217 stack_overflow::cleanup();
220 #[cfg(target_os = "android")]
221 pub use crate::sys::android::signal;
222 #[cfg(not(target_os = "android"))]
223 pub use libc::signal;
225 pub fn decode_error_kind(errno: i32) -> ErrorKind {
227 match errno as libc::c_int {
228 libc::E2BIG => ArgumentListTooLong,
229 libc::EADDRINUSE => AddrInUse,
230 libc::EADDRNOTAVAIL => AddrNotAvailable,
231 libc::EBUSY => ResourceBusy,
232 libc::ECONNABORTED => ConnectionAborted,
233 libc::ECONNREFUSED => ConnectionRefused,
234 libc::ECONNRESET => ConnectionReset,
235 libc::EDEADLK => Deadlock,
236 libc::EDQUOT => FilesystemQuotaExceeded,
237 libc::EEXIST => AlreadyExists,
238 libc::EFBIG => FileTooLarge,
239 libc::EHOSTUNREACH => HostUnreachable,
240 libc::EINTR => Interrupted,
241 libc::EINVAL => InvalidInput,
242 libc::EISDIR => IsADirectory,
243 libc::ELOOP => FilesystemLoop,
244 libc::ENOENT => NotFound,
245 libc::ENOMEM => OutOfMemory,
246 libc::ENOSPC => StorageFull,
247 libc::ENOSYS => Unsupported,
248 libc::EMLINK => TooManyLinks,
249 libc::ENAMETOOLONG => InvalidFilename,
250 libc::ENETDOWN => NetworkDown,
251 libc::ENETUNREACH => NetworkUnreachable,
252 libc::ENOTCONN => NotConnected,
253 libc::ENOTDIR => NotADirectory,
254 libc::ENOTEMPTY => DirectoryNotEmpty,
255 libc::EPIPE => BrokenPipe,
256 libc::EROFS => ReadOnlyFilesystem,
257 libc::ESPIPE => NotSeekable,
258 libc::ESTALE => StaleNetworkFileHandle,
259 libc::ETIMEDOUT => TimedOut,
260 libc::ETXTBSY => ExecutableFileBusy,
261 libc::EXDEV => CrossesDevices,
263 libc::EACCES | libc::EPERM => PermissionDenied,
265 // These two constants can have the same value on some systems,
266 // but different values on others, so we can't use a match
268 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
275 pub trait IsMinusOne {
276 fn is_minus_one(&self) -> bool;
279 macro_rules! impl_is_minus_one {
280 ($($t:ident)*) => ($(impl IsMinusOne for $t {
281 fn is_minus_one(&self) -> bool {
287 impl_is_minus_one! { i8 i16 i32 i64 isize }
289 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
290 if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
293 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
300 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
301 other => return other,
306 #[allow(dead_code)] // Not used on all platforms.
307 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
308 if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
311 // libc::abort() will run the SIGABRT handler. That's fine because anyone who
312 // installs a SIGABRT handler already has to expect it to run in Very Bad
313 // situations (eg, malloc crashing).
315 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
316 // SIGABRT handler and raises it again, and then starts to get creative.
318 // See the public documentation for `intrinsics::abort()` and `process::abort()`
319 // for further discussion.
321 // There is confusion about whether libc::abort() flushes stdio streams.
322 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
323 // so flushing streams is at least extremely hard, if not entirely impossible.
325 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
326 // do so. In 1003.1-2004 this was fixed.
328 // glibc's implementation did the flush, unsafely, before glibc commit
329 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
330 // Weimer. According to glibc's NEWS:
332 // The abort function terminates the process immediately, without flushing
333 // stdio streams. Previous glibc versions used to flush streams, resulting
334 // in deadlocks and further data corruption. This change also affects
335 // process aborts as the result of assertion failures.
337 // This is an accurate description of the problem. The only solution for
338 // program with nontrivial use of C stdio is a fixed libc - one which does not
339 // try to flush in abort - since even libc-internal errors, and assertion
340 // failures generated from C, will go via abort().
342 // On systems with old, buggy, libcs, the impact can be severe for a
343 // multithreaded C program. It is much less severe for Rust, because Rust
344 // stdlib doesn't use libc stdio buffering. In a typical Rust program, which
345 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
346 pub fn abort_internal() -> ! {
347 unsafe { libc::abort() }
351 if #[cfg(target_os = "android")] {
352 #[link(name = "dl", kind = "static", modifiers = "-bundle",
353 cfg(target_feature = "crt-static"))]
354 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
355 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
357 } else if #[cfg(target_os = "freebsd")] {
358 #[link(name = "execinfo")]
359 #[link(name = "pthread")]
361 } else if #[cfg(target_os = "netbsd")] {
362 #[link(name = "pthread")]
365 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
366 #[link(name = "pthread")]
368 } else if #[cfg(target_os = "solaris")] {
369 #[link(name = "socket")]
370 #[link(name = "posix4")]
371 #[link(name = "pthread")]
372 #[link(name = "resolv")]
374 } else if #[cfg(target_os = "illumos")] {
375 #[link(name = "socket")]
376 #[link(name = "posix4")]
377 #[link(name = "pthread")]
378 #[link(name = "resolv")]
379 #[link(name = "nsl")]
380 // Use libumem for the (malloc-compatible) allocator
381 #[link(name = "umem")]
383 } else if #[cfg(target_os = "macos")] {
384 #[link(name = "System")]
385 // res_init and friends require -lresolv on macOS/iOS.
386 // See #41582 and https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
387 #[link(name = "resolv")]
389 } else if #[cfg(any(target_os = "ios", target_os = "watchos"))] {
390 #[link(name = "System")]
391 #[link(name = "objc")]
392 #[link(name = "Security", kind = "framework")]
393 #[link(name = "Foundation", kind = "framework")]
394 #[link(name = "resolv")]
396 } else if #[cfg(target_os = "fuchsia")] {
397 #[link(name = "zircon")]
398 #[link(name = "fdio")]
400 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
406 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
410 pub fn unsupported<T>() -> io::Result<T> {
411 Err(unsupported_err())
414 pub fn unsupported_err() -> io::Error {
415 io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)