1 #![allow(missing_docs, nonstandard_style)]
3 use crate::io::ErrorKind;
5 pub use self::rand::hashmap_random_keys;
8 #[cfg(not(target_os = "espidf"))]
15 #[path = "../unix/cmath.rs"]
23 #[cfg(any(target_os = "linux", target_os = "android"))]
25 #[cfg(target_os = "l4re")]
29 #[cfg(not(target_os = "l4re"))]
31 #[cfg(target_os = "l4re")]
32 pub use self::l4re::net;
40 pub mod stack_overflow;
43 pub mod thread_local_dtor;
44 pub mod thread_local_key;
47 #[cfg(target_os = "espidf")]
48 pub fn init(argc: isize, argv: *const *const u8) {}
50 #[cfg(not(target_os = "espidf"))]
51 // SAFETY: must be called only once during runtime initialization.
52 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
53 pub unsafe fn init(argc: isize, argv: *const *const 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.
68 stack_overflow::init();
69 args::init(argc, argv);
71 unsafe fn sanitize_standard_fds() {
73 // The standard fds are always available in Miri.
76 target_os = "emscripten",
77 target_os = "fuchsia",
78 target_os = "vxworks",
79 // The poll on Darwin doesn't set POLLNVAL for closed fds.
84 use crate::sys::os::errno;
85 let pfds: &mut [_] = &mut [
86 libc::pollfd { fd: 0, events: 0, revents: 0 },
87 libc::pollfd { fd: 1, events: 0, revents: 0 },
88 libc::pollfd { fd: 2, events: 0, revents: 0 },
90 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
91 if errno() == libc::EINTR {
97 if pfd.revents & libc::POLLNVAL == 0 {
100 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
101 // If the stream is closed but we failed to reopen it, abort the
102 // process. Otherwise we wouldn't preserve the safety of
103 // operations on the corresponding Rust object Stdin, Stdout, or
108 } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
109 use crate::sys::os::errno;
111 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
112 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
121 unsafe fn reset_sigpipe() {
122 #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
123 rtassert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
127 // SAFETY: must be called only once during runtime cleanup.
128 // NOTE: this is not guaranteed to run, for example when the program aborts.
129 pub unsafe fn cleanup() {
130 stack_overflow::cleanup();
133 #[cfg(target_os = "android")]
134 pub use crate::sys::android::signal;
135 #[cfg(not(target_os = "android"))]
136 pub use libc::signal;
138 pub fn decode_error_kind(errno: i32) -> ErrorKind {
140 match errno as libc::c_int {
141 libc::E2BIG => ArgumentListTooLong,
142 libc::EADDRINUSE => AddrInUse,
143 libc::EADDRNOTAVAIL => AddrNotAvailable,
144 libc::EBUSY => ResourceBusy,
145 libc::ECONNABORTED => ConnectionAborted,
146 libc::ECONNREFUSED => ConnectionRefused,
147 libc::ECONNRESET => ConnectionReset,
148 libc::EDEADLK => Deadlock,
149 libc::EDQUOT => FilesystemQuotaExceeded,
150 libc::EEXIST => AlreadyExists,
151 libc::EFBIG => FileTooLarge,
152 libc::EHOSTUNREACH => HostUnreachable,
153 libc::EINTR => Interrupted,
154 libc::EINVAL => InvalidInput,
155 libc::EISDIR => IsADirectory,
156 libc::ELOOP => FilesystemLoop,
157 libc::ENOENT => NotFound,
158 libc::ENOMEM => OutOfMemory,
159 libc::ENOSPC => StorageFull,
160 libc::ENOSYS => Unsupported,
161 libc::EMLINK => TooManyLinks,
162 libc::ENAMETOOLONG => InvalidFilename,
163 libc::ENETDOWN => NetworkDown,
164 libc::ENETUNREACH => NetworkUnreachable,
165 libc::ENOTCONN => NotConnected,
166 libc::ENOTDIR => NotADirectory,
167 libc::ENOTEMPTY => DirectoryNotEmpty,
168 libc::EPIPE => BrokenPipe,
169 libc::EROFS => ReadOnlyFilesystem,
170 libc::ESPIPE => NotSeekable,
171 libc::ESTALE => StaleNetworkFileHandle,
172 libc::ETIMEDOUT => TimedOut,
173 libc::ETXTBSY => ExecutableFileBusy,
174 libc::EXDEV => CrossesDevices,
176 libc::EACCES | libc::EPERM => PermissionDenied,
178 // These two constants can have the same value on some systems,
179 // but different values on others, so we can't use a match
181 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
188 pub trait IsMinusOne {
189 fn is_minus_one(&self) -> bool;
192 macro_rules! impl_is_minus_one {
193 ($($t:ident)*) => ($(impl IsMinusOne for $t {
194 fn is_minus_one(&self) -> bool {
200 impl_is_minus_one! { i8 i16 i32 i64 isize }
202 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
203 if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
206 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
213 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
214 other => return other,
219 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
220 if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
223 // libc::abort() will run the SIGABRT handler. That's fine because anyone who
224 // installs a SIGABRT handler already has to expect it to run in Very Bad
225 // situations (eg, malloc crashing).
227 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
228 // SIGABRT handler and raises it again, and then starts to get creative.
230 // See the public documentation for `intrinsics::abort()` and `process::abort()`
231 // for further discussion.
233 // There is confusion about whether libc::abort() flushes stdio streams.
234 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
235 // so flushing streams is at least extremely hard, if not entirely impossible.
237 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
238 // do so. In 1003.1-2004 this was fixed.
240 // glibc's implementation did the flush, unsafely, before glibc commit
241 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
242 // Weimer. According to glibc's NEWS:
244 // The abort function terminates the process immediately, without flushing
245 // stdio streams. Previous glibc versions used to flush streams, resulting
246 // in deadlocks and further data corruption. This change also affects
247 // process aborts as the result of assertion failures.
249 // This is an accurate description of the problem. The only solution for
250 // program with nontrivial use of C stdio is a fixed libc - one which does not
251 // try to flush in abort - since even libc-internal errors, and assertion
252 // failures generated from C, will go via abort().
254 // On systems with old, buggy, libcs, the impact can be severe for a
255 // multithreaded C program. It is much less severe for Rust, because Rust
256 // stdlib doesn't use libc stdio buffering. In a typical Rust program, which
257 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
258 pub fn abort_internal() -> ! {
259 unsafe { libc::abort() }
263 if #[cfg(target_os = "android")] {
265 #[link(name = "log")]
267 } else if #[cfg(target_os = "freebsd")] {
268 #[link(name = "execinfo")]
269 #[link(name = "pthread")]
271 } else if #[cfg(target_os = "netbsd")] {
272 #[link(name = "pthread")]
275 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
276 #[link(name = "pthread")]
278 } else if #[cfg(target_os = "solaris")] {
279 #[link(name = "socket")]
280 #[link(name = "posix4")]
281 #[link(name = "pthread")]
282 #[link(name = "resolv")]
284 } else if #[cfg(target_os = "illumos")] {
285 #[link(name = "socket")]
286 #[link(name = "posix4")]
287 #[link(name = "pthread")]
288 #[link(name = "resolv")]
289 #[link(name = "nsl")]
290 // Use libumem for the (malloc-compatible) allocator
291 #[link(name = "umem")]
293 } else if #[cfg(target_os = "macos")] {
294 #[link(name = "System")]
295 // res_init and friends require -lresolv on macOS/iOS.
296 // See #41582 and https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
297 #[link(name = "resolv")]
299 } else if #[cfg(target_os = "ios")] {
300 #[link(name = "System")]
301 #[link(name = "objc")]
302 #[link(name = "Security", kind = "framework")]
303 #[link(name = "Foundation", kind = "framework")]
304 #[link(name = "resolv")]
306 } else if #[cfg(target_os = "fuchsia")] {
307 #[link(name = "zircon")]
308 #[link(name = "fdio")]
310 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
316 #[cfg(target_os = "espidf")]
320 pub fn unsupported<T>() -> io::Result<T> {
321 Err(unsupported_err())
324 pub fn unsupported_err() -> io::Error {
325 io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)