1 #![allow(missing_docs, nonstandard_style)]
3 use crate::io
::ErrorKind
;
5 pub use self::rand
::hashmap_random_keys
;
14 #[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
;
45 pub use crate::sys_common
::os_str_bytes
as os_str
;
47 // SAFETY: must be called only once during runtime initialization.
48 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
49 pub unsafe fn init(argc
: isize, argv
: *const *const u8) {
50 // The standard streams might be closed on application startup. To prevent
51 // std::io::{stdin, stdout,stderr} objects from using other unrelated file
52 // resources opened later, we reopen standards streams when they are closed.
53 sanitize_standard_fds();
55 // By default, some platforms will send a *signal* when an EPIPE error
56 // would otherwise be delivered. This runtime doesn't install a SIGPIPE
57 // handler, causing it to kill the program, which isn't exactly what we
60 // Hence, we set SIGPIPE to ignore when the program starts up in order
61 // to prevent this problem.
64 stack_overflow
::init();
65 args
::init(argc
, argv
);
67 unsafe fn sanitize_standard_fds() {
69 // The standard fds are always available in Miri.
72 target_os
= "emscripten",
73 target_os
= "fuchsia",
74 target_os
= "vxworks",
75 // The poll on Darwin doesn't set POLLNVAL for closed fds.
80 use crate::sys
::os
::errno
;
81 let pfds
: &mut [_
] = &mut [
82 libc
::pollfd { fd: 0, events: 0, revents: 0 }
,
83 libc
::pollfd { fd: 1, events: 0, revents: 0 }
,
84 libc
::pollfd { fd: 2, events: 0, revents: 0 }
,
86 while libc
::poll(pfds
.as_mut_ptr(), 3, 0) == -1 {
87 if errno() == libc
::EINTR
{
93 if pfd
.revents
& libc
::POLLNVAL
== 0 {
96 if libc
::open("/dev/null\0".as_ptr().cast(), libc
::O_RDWR
, 0) == -1 {
97 // If the stream is closed but we failed to reopen it, abort the
98 // process. Otherwise we wouldn't preserve the safety of
99 // operations on the corresponding Rust object Stdin, Stdout, or
104 } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
105 use crate::sys
::os
::errno
;
107 if libc
::fcntl(fd
, libc
::F_GETFD
) == -1 && errno() == libc
::EBADF
{
108 if libc
::open("/dev/null\0".as_ptr().cast(), libc
::O_RDWR
, 0) == -1 {
117 unsafe fn reset_sigpipe() {
118 #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
119 assert
!(signal(libc
::SIGPIPE
, libc
::SIG_IGN
) != libc
::SIG_ERR
);
123 // SAFETY: must be called only once during runtime cleanup.
124 // NOTE: this is not guaranteed to run, for example when the program aborts.
125 pub unsafe fn cleanup() {
126 stack_overflow
::cleanup();
129 #[cfg(target_os = "android")]
130 pub use crate::sys
::android
::signal
;
131 #[cfg(not(target_os = "android"))]
132 pub use libc
::signal
;
134 pub fn decode_error_kind(errno
: i32) -> ErrorKind
{
136 match errno
as libc
::c_int
{
137 libc
::E2BIG
=> ArgumentListTooLong
,
138 libc
::EADDRINUSE
=> AddrInUse
,
139 libc
::EADDRNOTAVAIL
=> AddrNotAvailable
,
140 libc
::EBUSY
=> ResourceBusy
,
141 libc
::ECONNABORTED
=> ConnectionAborted
,
142 libc
::ECONNREFUSED
=> ConnectionRefused
,
143 libc
::ECONNRESET
=> ConnectionReset
,
144 libc
::EDEADLK
=> Deadlock
,
145 libc
::EDQUOT
=> FilesystemQuotaExceeded
,
146 libc
::EEXIST
=> AlreadyExists
,
147 libc
::EFBIG
=> FileTooLarge
,
148 libc
::EHOSTUNREACH
=> HostUnreachable
,
149 libc
::EINTR
=> Interrupted
,
150 libc
::EINVAL
=> InvalidInput
,
151 libc
::EISDIR
=> IsADirectory
,
152 libc
::ELOOP
=> FilesystemLoop
,
153 libc
::ENOENT
=> NotFound
,
154 libc
::ENOMEM
=> OutOfMemory
,
155 libc
::ENOSPC
=> StorageFull
,
156 libc
::ENOSYS
=> Unsupported
,
157 libc
::EMLINK
=> TooManyLinks
,
158 libc
::ENAMETOOLONG
=> FilenameTooLong
,
159 libc
::ENETDOWN
=> NetworkDown
,
160 libc
::ENETUNREACH
=> NetworkUnreachable
,
161 libc
::ENOTCONN
=> NotConnected
,
162 libc
::ENOTDIR
=> NotADirectory
,
163 libc
::ENOTEMPTY
=> DirectoryNotEmpty
,
164 libc
::EPIPE
=> BrokenPipe
,
165 libc
::EROFS
=> ReadOnlyFilesystem
,
166 libc
::ESPIPE
=> NotSeekable
,
167 libc
::ESTALE
=> StaleNetworkFileHandle
,
168 libc
::ETIMEDOUT
=> TimedOut
,
169 libc
::ETXTBSY
=> ExecutableFileBusy
,
170 libc
::EXDEV
=> CrossesDevices
,
172 libc
::EACCES
| libc
::EPERM
=> PermissionDenied
,
174 // These two constants can have the same value on some systems,
175 // but different values on others, so we can't use a match
177 x
if x
== libc
::EAGAIN
|| x
== libc
::EWOULDBLOCK
=> WouldBlock
,
184 pub trait IsMinusOne
{
185 fn is_minus_one(&self) -> bool
;
188 macro_rules
! impl_is_minus_one
{
189 ($
($t
:ident
)*) => ($
(impl IsMinusOne
for $t
{
190 fn is_minus_one(&self) -> bool
{
196 impl_is_minus_one
! { i8 i16 i32 i64 isize }
198 pub fn cvt
<T
: IsMinusOne
>(t
: T
) -> crate::io
::Result
<T
> {
199 if t
.is_minus_one() { Err(crate::io::Error::last_os_error()) }
else { Ok(t) }
202 pub fn cvt_r
<T
, F
>(mut f
: F
) -> crate::io
::Result
<T
>
209 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> {}
210 other
=> return other
,
215 pub fn cvt_nz(error
: libc
::c_int
) -> crate::io
::Result
<()> {
216 if error
== 0 { Ok(()) }
else { Err(crate::io::Error::from_raw_os_error(error)) }
219 // libc::abort() will run the SIGABRT handler. That's fine because anyone who
220 // installs a SIGABRT handler already has to expect it to run in Very Bad
221 // situations (eg, malloc crashing).
223 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
224 // SIGABRT handler and raises it again, and then starts to get creative.
226 // See the public documentation for `intrinsics::abort()` and `process::abort()`
227 // for further discussion.
229 // There is confusion about whether libc::abort() flushes stdio streams.
230 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
231 // so flushing streams is at least extremely hard, if not entirely impossible.
233 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
234 // do so. In 1003.1-2004 this was fixed.
236 // glibc's implementation did the flush, unsafely, before glibc commit
237 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
238 // Weimer. According to glibc's NEWS:
240 // The abort function terminates the process immediately, without flushing
241 // stdio streams. Previous glibc versions used to flush streams, resulting
242 // in deadlocks and further data corruption. This change also affects
243 // process aborts as the result of assertion failures.
245 // This is an accurate description of the problem. The only solution for
246 // program with nontrivial use of C stdio is a fixed libc - one which does not
247 // try to flush in abort - since even libc-internal errors, and assertion
248 // failures generated from C, will go via abort().
250 // On systems with old, buggy, libcs, the impact can be severe for a
251 // multithreaded C program. It is much less severe for Rust, because Rust
252 // stdlib doesn't use libc stdio buffering. In a typical Rust program, which
253 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
254 pub fn abort_internal() -> ! {
255 unsafe { libc::abort() }
259 if #[cfg(target_os = "android")] {
261 #[link(name = "log")]
263 } else if #[cfg(target_os = "freebsd")] {
264 #[link(name = "execinfo")]
265 #[link(name = "pthread")]
267 } else if #[cfg(target_os = "netbsd")] {
268 #[link(name = "pthread")]
271 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
272 #[link(name = "pthread")]
274 } else if #[cfg(target_os = "solaris")] {
275 #[link(name = "socket")]
276 #[link(name = "posix4")]
277 #[link(name = "pthread")]
278 #[link(name = "resolv")]
280 } else if #[cfg(target_os = "illumos")] {
281 #[link(name = "socket")]
282 #[link(name = "posix4")]
283 #[link(name = "pthread")]
284 #[link(name = "resolv")]
285 #[link(name = "nsl")]
286 // Use libumem for the (malloc-compatible) allocator
287 #[link(name = "umem")]
289 } else if #[cfg(target_os = "macos")] {
290 #[link(name = "System")]
291 // res_init and friends require -lresolv on macOS/iOS.
292 // See #41582 and https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
293 #[link(name = "resolv")]
295 } else if #[cfg(target_os = "ios")] {
296 #[link(name = "System")]
297 #[link(name = "objc")]
298 #[link(name = "Security", kind = "framework")]
299 #[link(name = "Foundation", kind = "framework")]
300 #[link(name = "resolv")]
302 } else if #[cfg(target_os = "fuchsia")] {
303 #[link(name = "zircon")]
304 #[link(name = "fdio")]