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_parking;
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 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
99 use libc::open as open64;
100 #[cfg(all(target_os = "linux", target_env = "gnu"))]
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 },
108 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
110 libc::EINTR => continue,
111 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
112 // RLIMIT_NOFILE or temporary allocation failures
113 // may be preventing use of poll(), fall back to fcntl
120 if pfd.revents & libc::POLLNVAL == 0 {
123 if open64("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
124 // If the stream is closed but we failed to reopen it, abort the
125 // process. Otherwise we wouldn't preserve the safety of
126 // operations on the corresponding Rust object Stdin, Stdout, or
134 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
136 // The standard fds are always available in Miri.
138 target_os = "emscripten",
139 target_os = "fuchsia",
140 target_os = "vxworks",
142 target_os = "horizon",
145 use crate::sys::os::errno;
146 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
147 use libc::open as open64;
148 #[cfg(all(target_os = "linux", target_env = "gnu"))]
151 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
152 if open64("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
153 // If the stream is closed but we failed to reopen it, abort the
154 // process. Otherwise we wouldn't preserve the safety of
155 // operations on the corresponding Rust object Stdin, Stdout, or
164 unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
165 #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia", target_os = "horizon")))]
167 // We don't want to add this as a public type to std, nor do we
168 // want to `include!` a file from the compiler (which would break
169 // Miri and xargo for example), so we choose to duplicate these
170 // constants from `compiler/rustc_session/src/config/sigpipe.rs`.
171 // See the other file for docs. NOTE: Make sure to keep them in
174 pub const DEFAULT: u8 = 0;
175 pub const INHERIT: u8 = 1;
176 pub const SIG_IGN: u8 = 2;
177 pub const SIG_DFL: u8 = 3;
180 let (sigpipe_attr_specified, handler) = match sigpipe {
181 sigpipe::DEFAULT => (false, Some(libc::SIG_IGN)),
182 sigpipe::INHERIT => (true, None),
183 sigpipe::SIG_IGN => (true, Some(libc::SIG_IGN)),
184 sigpipe::SIG_DFL => (true, Some(libc::SIG_DFL)),
187 if sigpipe_attr_specified {
188 UNIX_SIGPIPE_ATTR_SPECIFIED.store(true, crate::sync::atomic::Ordering::Relaxed);
190 if let Some(handler) = handler {
191 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
197 // This is set (up to once) in reset_sigpipe.
199 target_os = "espidf",
200 target_os = "emscripten",
201 target_os = "fuchsia",
202 target_os = "horizon"
204 static UNIX_SIGPIPE_ATTR_SPECIFIED: crate::sync::atomic::AtomicBool =
205 crate::sync::atomic::AtomicBool::new(false);
208 target_os = "espidf",
209 target_os = "emscripten",
210 target_os = "fuchsia",
211 target_os = "horizon"
213 pub(crate) fn unix_sigpipe_attr_specified() -> bool {
214 UNIX_SIGPIPE_ATTR_SPECIFIED.load(crate::sync::atomic::Ordering::Relaxed)
217 // SAFETY: must be called only once during runtime cleanup.
218 // NOTE: this is not guaranteed to run, for example when the program aborts.
219 pub unsafe fn cleanup() {
220 stack_overflow::cleanup();
223 #[cfg(target_os = "android")]
224 pub use crate::sys::android::signal;
225 #[cfg(not(target_os = "android"))]
226 pub use libc::signal;
228 pub fn decode_error_kind(errno: i32) -> ErrorKind {
230 match errno as libc::c_int {
231 libc::E2BIG => ArgumentListTooLong,
232 libc::EADDRINUSE => AddrInUse,
233 libc::EADDRNOTAVAIL => AddrNotAvailable,
234 libc::EBUSY => ResourceBusy,
235 libc::ECONNABORTED => ConnectionAborted,
236 libc::ECONNREFUSED => ConnectionRefused,
237 libc::ECONNRESET => ConnectionReset,
238 libc::EDEADLK => Deadlock,
239 libc::EDQUOT => FilesystemQuotaExceeded,
240 libc::EEXIST => AlreadyExists,
241 libc::EFBIG => FileTooLarge,
242 libc::EHOSTUNREACH => HostUnreachable,
243 libc::EINTR => Interrupted,
244 libc::EINVAL => InvalidInput,
245 libc::EISDIR => IsADirectory,
246 libc::ELOOP => FilesystemLoop,
247 libc::ENOENT => NotFound,
248 libc::ENOMEM => OutOfMemory,
249 libc::ENOSPC => StorageFull,
250 libc::ENOSYS => Unsupported,
251 libc::EMLINK => TooManyLinks,
252 libc::ENAMETOOLONG => InvalidFilename,
253 libc::ENETDOWN => NetworkDown,
254 libc::ENETUNREACH => NetworkUnreachable,
255 libc::ENOTCONN => NotConnected,
256 libc::ENOTDIR => NotADirectory,
257 libc::ENOTEMPTY => DirectoryNotEmpty,
258 libc::EPIPE => BrokenPipe,
259 libc::EROFS => ReadOnlyFilesystem,
260 libc::ESPIPE => NotSeekable,
261 libc::ESTALE => StaleNetworkFileHandle,
262 libc::ETIMEDOUT => TimedOut,
263 libc::ETXTBSY => ExecutableFileBusy,
264 libc::EXDEV => CrossesDevices,
266 libc::EACCES | libc::EPERM => PermissionDenied,
268 // These two constants can have the same value on some systems,
269 // but different values on others, so we can't use a match
271 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
278 pub trait IsMinusOne {
279 fn is_minus_one(&self) -> bool;
282 macro_rules! impl_is_minus_one {
283 ($($t:ident)*) => ($(impl IsMinusOne for $t {
284 fn is_minus_one(&self) -> bool {
290 impl_is_minus_one! { i8 i16 i32 i64 isize }
292 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
293 if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
296 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
303 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
304 other => return other,
309 #[allow(dead_code)] // Not used on all platforms.
310 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
311 if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
314 // libc::abort() will run the SIGABRT handler. That's fine because anyone who
315 // installs a SIGABRT handler already has to expect it to run in Very Bad
316 // situations (eg, malloc crashing).
318 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
319 // SIGABRT handler and raises it again, and then starts to get creative.
321 // See the public documentation for `intrinsics::abort()` and `process::abort()`
322 // for further discussion.
324 // There is confusion about whether libc::abort() flushes stdio streams.
325 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
326 // so flushing streams is at least extremely hard, if not entirely impossible.
328 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
329 // do so. In 1003.1-2004 this was fixed.
331 // glibc's implementation did the flush, unsafely, before glibc commit
332 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
333 // Weimer. According to glibc's NEWS:
335 // The abort function terminates the process immediately, without flushing
336 // stdio streams. Previous glibc versions used to flush streams, resulting
337 // in deadlocks and further data corruption. This change also affects
338 // process aborts as the result of assertion failures.
340 // This is an accurate description of the problem. The only solution for
341 // program with nontrivial use of C stdio is a fixed libc - one which does not
342 // try to flush in abort - since even libc-internal errors, and assertion
343 // failures generated from C, will go via abort().
345 // On systems with old, buggy, libcs, the impact can be severe for a
346 // multithreaded C program. It is much less severe for Rust, because Rust
347 // stdlib doesn't use libc stdio buffering. In a typical Rust program, which
348 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
349 pub fn abort_internal() -> ! {
350 unsafe { libc::abort() }
354 if #[cfg(target_os = "android")] {
355 #[link(name = "dl", kind = "static", modifiers = "-bundle",
356 cfg(target_feature = "crt-static"))]
357 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
358 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
360 } else if #[cfg(target_os = "freebsd")] {
361 #[link(name = "execinfo")]
362 #[link(name = "pthread")]
364 } else if #[cfg(target_os = "netbsd")] {
365 #[link(name = "pthread")]
368 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
369 #[link(name = "pthread")]
371 } else if #[cfg(target_os = "solaris")] {
372 #[link(name = "socket")]
373 #[link(name = "posix4")]
374 #[link(name = "pthread")]
375 #[link(name = "resolv")]
377 } else if #[cfg(target_os = "illumos")] {
378 #[link(name = "socket")]
379 #[link(name = "posix4")]
380 #[link(name = "pthread")]
381 #[link(name = "resolv")]
382 #[link(name = "nsl")]
383 // Use libumem for the (malloc-compatible) allocator
384 #[link(name = "umem")]
386 } else if #[cfg(target_os = "macos")] {
387 #[link(name = "System")]
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")]
395 } else if #[cfg(target_os = "fuchsia")] {
396 #[link(name = "zircon")]
397 #[link(name = "fdio")]
399 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
405 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
409 pub fn unsupported<T>() -> io::Result<T> {
410 Err(unsupported_err())
413 pub fn unsupported_err() -> io::Error {
414 io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)