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) {}
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 pub unsafe fn init(argc: isize, argv: *const *const u8) {
53 // The standard streams might be closed on application startup. To prevent
54 // std::io::{stdin, stdout,stderr} objects from using other unrelated file
55 // resources opened later, we reopen standards streams when they are closed.
56 sanitize_standard_fds();
58 // By default, some platforms will send a *signal* when an EPIPE error
59 // would otherwise be delivered. This runtime doesn't install a SIGPIPE
60 // handler, causing it to kill the program, which isn't exactly what we
63 // Hence, we set SIGPIPE to ignore when the program starts up in order
64 // to prevent this problem.
67 stack_overflow::init();
68 args::init(argc, argv);
70 // Normally, `thread::spawn` will call `Thread::set_name` but since this thread
71 // already exists, we have to call it ourselves. We only do this on macos
72 // because some unix-like operating systems such as Linux share process-id and
73 // thread-id for the main thread and so renaming the main thread will rename the
74 // process and we only want to enable this on platforms we've tested.
75 if cfg!(target_os = "macos") {
76 thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
79 unsafe fn sanitize_standard_fds() {
80 // fast path with a single syscall for systems with poll()
83 target_os = "emscripten",
84 target_os = "fuchsia",
85 target_os = "vxworks",
86 // The poll on Darwin doesn't set POLLNVAL for closed fds.
89 target_os = "watchos",
92 target_os = "horizon",
95 use crate::sys::os::errno;
96 let pfds: &mut [_] = &mut [
97 libc::pollfd { fd: 0, events: 0, revents: 0 },
98 libc::pollfd { fd: 1, events: 0, revents: 0 },
99 libc::pollfd { fd: 2, events: 0, revents: 0 },
102 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
104 libc::EINTR => continue,
105 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
106 // RLIMIT_NOFILE or temporary allocation failures
107 // may be preventing use of poll(), fall back to fcntl
114 if pfd.revents & libc::POLLNVAL == 0 {
117 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
118 // If the stream is closed but we failed to reopen it, abort the
119 // process. Otherwise we wouldn't preserve the safety of
120 // operations on the corresponding Rust object Stdin, Stdout, or
128 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
130 // The standard fds are always available in Miri.
132 target_os = "emscripten",
133 target_os = "fuchsia",
134 target_os = "vxworks",
136 target_os = "horizon",
139 use crate::sys::os::errno;
141 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
142 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
143 // If the stream is closed but we failed to reopen it, abort the
144 // process. Otherwise we wouldn't preserve the safety of
145 // operations on the corresponding Rust object Stdin, Stdout, or
154 unsafe fn reset_sigpipe() {
155 #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia", target_os = "horizon")))]
156 rtassert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
160 // SAFETY: must be called only once during runtime cleanup.
161 // NOTE: this is not guaranteed to run, for example when the program aborts.
162 pub unsafe fn cleanup() {
163 stack_overflow::cleanup();
166 #[cfg(target_os = "android")]
167 pub use crate::sys::android::signal;
168 #[cfg(not(target_os = "android"))]
169 pub use libc::signal;
171 pub fn decode_error_kind(errno: i32) -> ErrorKind {
173 match errno as libc::c_int {
174 libc::E2BIG => ArgumentListTooLong,
175 libc::EADDRINUSE => AddrInUse,
176 libc::EADDRNOTAVAIL => AddrNotAvailable,
177 libc::EBUSY => ResourceBusy,
178 libc::ECONNABORTED => ConnectionAborted,
179 libc::ECONNREFUSED => ConnectionRefused,
180 libc::ECONNRESET => ConnectionReset,
181 libc::EDEADLK => Deadlock,
182 libc::EDQUOT => FilesystemQuotaExceeded,
183 libc::EEXIST => AlreadyExists,
184 libc::EFBIG => FileTooLarge,
185 libc::EHOSTUNREACH => HostUnreachable,
186 libc::EINTR => Interrupted,
187 libc::EINVAL => InvalidInput,
188 libc::EISDIR => IsADirectory,
189 libc::ELOOP => FilesystemLoop,
190 libc::ENOENT => NotFound,
191 libc::ENOMEM => OutOfMemory,
192 libc::ENOSPC => StorageFull,
193 libc::ENOSYS => Unsupported,
194 libc::EMLINK => TooManyLinks,
195 libc::ENAMETOOLONG => InvalidFilename,
196 libc::ENETDOWN => NetworkDown,
197 libc::ENETUNREACH => NetworkUnreachable,
198 libc::ENOTCONN => NotConnected,
199 libc::ENOTDIR => NotADirectory,
200 libc::ENOTEMPTY => DirectoryNotEmpty,
201 libc::EPIPE => BrokenPipe,
202 libc::EROFS => ReadOnlyFilesystem,
203 libc::ESPIPE => NotSeekable,
204 libc::ESTALE => StaleNetworkFileHandle,
205 libc::ETIMEDOUT => TimedOut,
206 libc::ETXTBSY => ExecutableFileBusy,
207 libc::EXDEV => CrossesDevices,
209 libc::EACCES | libc::EPERM => PermissionDenied,
211 // These two constants can have the same value on some systems,
212 // but different values on others, so we can't use a match
214 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
221 pub trait IsMinusOne {
222 fn is_minus_one(&self) -> bool;
225 macro_rules! impl_is_minus_one {
226 ($($t:ident)*) => ($(impl IsMinusOne for $t {
227 fn is_minus_one(&self) -> bool {
233 impl_is_minus_one! { i8 i16 i32 i64 isize }
235 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
236 if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
239 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
246 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
247 other => return other,
252 #[allow(dead_code)] // Not used on all platforms.
253 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
254 if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
257 // libc::abort() will run the SIGABRT handler. That's fine because anyone who
258 // installs a SIGABRT handler already has to expect it to run in Very Bad
259 // situations (eg, malloc crashing).
261 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
262 // SIGABRT handler and raises it again, and then starts to get creative.
264 // See the public documentation for `intrinsics::abort()` and `process::abort()`
265 // for further discussion.
267 // There is confusion about whether libc::abort() flushes stdio streams.
268 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
269 // so flushing streams is at least extremely hard, if not entirely impossible.
271 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
272 // do so. In 1003.1-2004 this was fixed.
274 // glibc's implementation did the flush, unsafely, before glibc commit
275 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
276 // Weimer. According to glibc's NEWS:
278 // The abort function terminates the process immediately, without flushing
279 // stdio streams. Previous glibc versions used to flush streams, resulting
280 // in deadlocks and further data corruption. This change also affects
281 // process aborts as the result of assertion failures.
283 // This is an accurate description of the problem. The only solution for
284 // program with nontrivial use of C stdio is a fixed libc - one which does not
285 // try to flush in abort - since even libc-internal errors, and assertion
286 // failures generated from C, will go via abort().
288 // On systems with old, buggy, libcs, the impact can be severe for a
289 // multithreaded C program. It is much less severe for Rust, because Rust
290 // stdlib doesn't use libc stdio buffering. In a typical Rust program, which
291 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
292 pub fn abort_internal() -> ! {
293 unsafe { libc::abort() }
297 if #[cfg(target_os = "android")] {
298 #[link(name = "dl", kind = "static", modifiers = "-bundle",
299 cfg(target_feature = "crt-static"))]
300 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
301 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
303 } else if #[cfg(target_os = "freebsd")] {
304 #[link(name = "execinfo")]
305 #[link(name = "pthread")]
307 } else if #[cfg(target_os = "netbsd")] {
308 #[link(name = "pthread")]
311 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
312 #[link(name = "pthread")]
314 } else if #[cfg(target_os = "solaris")] {
315 #[link(name = "socket")]
316 #[link(name = "posix4")]
317 #[link(name = "pthread")]
318 #[link(name = "resolv")]
320 } else if #[cfg(target_os = "illumos")] {
321 #[link(name = "socket")]
322 #[link(name = "posix4")]
323 #[link(name = "pthread")]
324 #[link(name = "resolv")]
325 #[link(name = "nsl")]
326 // Use libumem for the (malloc-compatible) allocator
327 #[link(name = "umem")]
329 } else if #[cfg(target_os = "macos")] {
330 #[link(name = "System")]
331 // res_init and friends require -lresolv on macOS/iOS.
332 // See #41582 and https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
333 #[link(name = "resolv")]
335 } else if #[cfg(any(target_os = "ios", target_os = "watchos"))] {
336 #[link(name = "System")]
337 #[link(name = "objc")]
338 #[link(name = "Security", kind = "framework")]
339 #[link(name = "Foundation", kind = "framework")]
340 #[link(name = "resolv")]
342 } else if #[cfg(target_os = "fuchsia")] {
343 #[link(name = "zircon")]
344 #[link(name = "fdio")]
346 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
352 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
356 pub fn unsupported<T>() -> io::Result<T> {
357 Err(unsupported_err())
360 pub fn unsupported_err() -> io::Error {
361 io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)