1#![allow(missing_docs, nonstandard_style)]
2
3use crate::io::ErrorKind;
4
5pub use self::rand::hashmap_random_keys;
6
7#[cfg(not(target_os = "espidf"))]
8#[macro_use]
9pub mod weak;
10
11pub mod alloc;
12pub mod android;
13pub mod args;
14pub mod env;
15pub mod fd;
16pub mod fs;
17pub mod futex;
18pub mod io;
19#[cfg(any(target_os = "linux", target_os = "android"))]
20pub mod kernel_copy;
21#[cfg(target_os = "l4re")]
22mod l4re;
23#[cfg(not(target_os = "l4re"))]
24pub mod net;
25#[cfg(target_os = "l4re")]
26pub use self::l4re::net;
27pub mod os;
28pub mod pipe;
29pub mod process;
30pub mod rand;
31pub mod stack_overflow;
32pub mod stdio;
33pub mod thread;
34pub mod thread_local_dtor;
35pub mod thread_local_key;
36pub mod thread_parking;
37pub mod time;
38
39#[cfg(target_os = "espidf")]
40pub fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {}
41
42#[cfg(not(target_os = "espidf"))]
43// SAFETY: must be called only once during runtime initialization.
44// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
45// See `fn init()` in `library/std/src/rt.rs` for docs on `sigpipe`.
46pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
47 // The standard streams might be closed on application startup. To prevent
48 // std::io::{stdin, stdout,stderr} objects from using other unrelated file
49 // resources opened later, we reopen standards streams when they are closed.
50 sanitize_standard_fds();
51
52 // By default, some platforms will send a *signal* when an EPIPE error
53 // would otherwise be delivered. This runtime doesn't install a SIGPIPE
54 // handler, causing it to kill the program, which isn't exactly what we
55 // want!
56 //
57 // Hence, we set SIGPIPE to ignore when the program starts up in order
58 // to prevent this problem. Add `#[unix_sigpipe = "..."]` above `fn main()` to
59 // alter this behavior.
60 reset_sigpipe(sigpipe);
61
62 stack_overflow::init();
63 args::init(argc, argv);
64
65 // Normally, `thread::spawn` will call `Thread::set_name` but since this thread
66 // already exists, we have to call it ourselves. We only do this on macos
67 // because some unix-like operating systems such as Linux share process-id and
68 // thread-id for the main thread and so renaming the main thread will rename the
69 // process and we only want to enable this on platforms we've tested.
70 if cfg!(target_os = "macos") {
71 thread::Thread::set_name(&c"main");
72 }
73
74 unsafe fn sanitize_standard_fds() {
75 // fast path with a single syscall for systems with poll()
76 #[cfg(not(any(
77 miri,
78 target_os = "emscripten",
79 target_os = "fuchsia",
80 target_os = "vxworks",
81 // The poll on Darwin doesn't set POLLNVAL for closed fds.
82 target_os = "macos",
83 target_os = "ios",
84 target_os = "tvos",
85 target_os = "watchos",
86 target_os = "visionos",
87 target_os = "redox",
88 target_os = "l4re",
89 target_os = "horizon",
90 target_os = "vita",
91 )))]
92 'poll: {
93 use crate::sys::os::errno;
94 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
95 use libc::open as open64;
96 #[cfg(all(target_os = "linux", target_env = "gnu"))]
97 use libc::open64;
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 },
102 ];
103
104 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
105 match errno() {
106 libc::EINTR => continue,
107 #[cfg(target_vendor = "unikraft")]
108 libc::ENOSYS => {
109 // Not all configurations of Unikraft enable `LIBPOSIX_EVENT`.
110 break 'poll;
111 }
112 libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
113 // RLIMIT_NOFILE or temporary allocation failures
114 // may be preventing use of poll(), fall back to fcntl
115 break 'poll;
116 }
117 _ => libc::abort(),
118 }
119 }
120 for pfd in pfds {
121 if pfd.revents & libc::POLLNVAL == 0 {
122 continue;
123 }
124 if open64(c"/dev/null".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
125 // If the stream is closed but we failed to reopen it, abort the
126 // process. Otherwise we wouldn't preserve the safety of
127 // operations on the corresponding Rust object Stdin, Stdout, or
128 // Stderr.
129 libc::abort();
130 }
131 }
132 return;
133 }
134
135 // fallback in case poll isn't available or limited by RLIMIT_NOFILE
136 #[cfg(not(any(
137 // The standard fds are always available in Miri.
138 miri,
139 target_os = "emscripten",
140 target_os = "fuchsia",
141 target_os = "vxworks",
142 target_os = "l4re",
143 target_os = "horizon",
144 target_os = "vita",
145 )))]
146 {
147 use crate::sys::os::errno;
148 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
149 use libc::open as open64;
150 #[cfg(all(target_os = "linux", target_env = "gnu"))]
151 use libc::open64;
152 for fd in 0..3 {
153 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
154 if open64(c"/dev/null".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
155 // If the stream is closed but we failed to reopen it, abort the
156 // process. Otherwise we wouldn't preserve the safety of
157 // operations on the corresponding Rust object Stdin, Stdout, or
158 // Stderr.
159 libc::abort();
160 }
161 }
162 }
163 }
164 }
165
166 unsafe fn reset_sigpipe(#[allow(unused_variables)] sigpipe: u8) {
167 #[cfg(not(any(
168 target_os = "emscripten",
169 target_os = "fuchsia",
170 target_os = "horizon",
171 // Unikraft's `signal` implementation is currently broken:
172 // https://github.com/unikraft/lib-musl/issues/57
173 target_vendor = "unikraft",
174 )))]
175 {
176 // We don't want to add this as a public type to std, nor do we
177 // want to `include!` a file from the compiler (which would break
178 // Miri and xargo for example), so we choose to duplicate these
179 // constants from `compiler/rustc_session/src/config/sigpipe.rs`.
180 // See the other file for docs. NOTE: Make sure to keep them in
181 // sync!
182 mod sigpipe {
183 pub const DEFAULT: u8 = 0;
184 pub const INHERIT: u8 = 1;
185 pub const SIG_IGN: u8 = 2;
186 pub const SIG_DFL: u8 = 3;
187 }
188
189 let (sigpipe_attr_specified, handler) = match sigpipe {
190 sigpipe::DEFAULT => (false, Some(libc::SIG_IGN)),
191 sigpipe::INHERIT => (true, None),
192 sigpipe::SIG_IGN => (true, Some(libc::SIG_IGN)),
193 sigpipe::SIG_DFL => (true, Some(libc::SIG_DFL)),
194 _ => unreachable!(),
195 };
196 if sigpipe_attr_specified {
197 UNIX_SIGPIPE_ATTR_SPECIFIED.store(true, crate::sync::atomic::Ordering::Relaxed);
198 }
199 if let Some(handler) = handler {
200 rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR);
201 #[cfg(target_os = "hurd")]
202 {
203 rtassert!(signal(libc::SIGLOST, handler) != libc::SIG_ERR);
204 }
205 }
206 }
207 }
208}
209
210// This is set (up to once) in reset_sigpipe.
211#[cfg(not(any(
212 target_os = "espidf",
213 target_os = "emscripten",
214 target_os = "fuchsia",
215 target_os = "horizon",
216)))]
217static UNIX_SIGPIPE_ATTR_SPECIFIED: crate::sync::atomic::AtomicBool =
218 crate::sync::atomic::AtomicBool::new(false);
219
220#[cfg(not(any(
221 target_os = "espidf",
222 target_os = "emscripten",
223 target_os = "fuchsia",
224 target_os = "horizon",
225)))]
226pub(crate) fn unix_sigpipe_attr_specified() -> bool {
227 UNIX_SIGPIPE_ATTR_SPECIFIED.load(order:crate::sync::atomic::Ordering::Relaxed)
228}
229
230// SAFETY: must be called only once during runtime cleanup.
231// NOTE: this is not guaranteed to run, for example when the program aborts.
232pub unsafe fn cleanup() {
233 stack_overflow::cleanup();
234}
235
236#[cfg(target_os = "android")]
237pub use crate::sys::android::signal;
238#[allow(unused_imports)]
239#[cfg(not(target_os = "android"))]
240pub use libc::signal;
241
242#[inline]
243pub(crate) fn is_interrupted(errno: i32) -> bool {
244 errno == libc::EINTR
245}
246
247pub fn decode_error_kind(errno: i32) -> ErrorKind {
248 use ErrorKind::*;
249 match errno as libc::c_int {
250 libc::E2BIG => ArgumentListTooLong,
251 libc::EADDRINUSE => AddrInUse,
252 libc::EADDRNOTAVAIL => AddrNotAvailable,
253 libc::EBUSY => ResourceBusy,
254 libc::ECONNABORTED => ConnectionAborted,
255 libc::ECONNREFUSED => ConnectionRefused,
256 libc::ECONNRESET => ConnectionReset,
257 libc::EDEADLK => Deadlock,
258 libc::EDQUOT => FilesystemQuotaExceeded,
259 libc::EEXIST => AlreadyExists,
260 libc::EFBIG => FileTooLarge,
261 libc::EHOSTUNREACH => HostUnreachable,
262 libc::EINTR => Interrupted,
263 libc::EINVAL => InvalidInput,
264 libc::EISDIR => IsADirectory,
265 libc::ELOOP => FilesystemLoop,
266 libc::ENOENT => NotFound,
267 libc::ENOMEM => OutOfMemory,
268 libc::ENOSPC => StorageFull,
269 libc::ENOSYS => Unsupported,
270 libc::EMLINK => TooManyLinks,
271 libc::ENAMETOOLONG => InvalidFilename,
272 libc::ENETDOWN => NetworkDown,
273 libc::ENETUNREACH => NetworkUnreachable,
274 libc::ENOTCONN => NotConnected,
275 libc::ENOTDIR => NotADirectory,
276 #[cfg(not(target_os = "aix"))]
277 libc::ENOTEMPTY => DirectoryNotEmpty,
278 libc::EPIPE => BrokenPipe,
279 libc::EROFS => ReadOnlyFilesystem,
280 libc::ESPIPE => NotSeekable,
281 libc::ESTALE => StaleNetworkFileHandle,
282 libc::ETIMEDOUT => TimedOut,
283 libc::ETXTBSY => ExecutableFileBusy,
284 libc::EXDEV => CrossesDevices,
285
286 libc::EACCES | libc::EPERM => PermissionDenied,
287
288 // These two constants can have the same value on some systems,
289 // but different values on others, so we can't use a match
290 // clause
291 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
292
293 _ => Uncategorized,
294 }
295}
296
297#[doc(hidden)]
298pub trait IsMinusOne {
299 fn is_minus_one(&self) -> bool;
300}
301
302macro_rules! impl_is_minus_one {
303 ($($t:ident)*) => ($(impl IsMinusOne for $t {
304 fn is_minus_one(&self) -> bool {
305 *self == -1
306 }
307 })*)
308}
309
310impl_is_minus_one! { i8 i16 i32 i64 isize }
311
312pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
313 if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
314}
315
316pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
317where
318 T: IsMinusOne,
319 F: FnMut() -> T,
320{
321 loop {
322 match cvt(f()) {
323 Err(ref e: &Error) if e.is_interrupted() => {}
324 other: Result => return other,
325 }
326 }
327}
328
329#[allow(dead_code)] // Not used on all platforms.
330pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
331 if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(code:error)) }
332}
333
334// libc::abort() will run the SIGABRT handler. That's fine because anyone who
335// installs a SIGABRT handler already has to expect it to run in Very Bad
336// situations (eg, malloc crashing).
337//
338// Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
339// SIGABRT handler and raises it again, and then starts to get creative.
340//
341// See the public documentation for `intrinsics::abort()` and `process::abort()`
342// for further discussion.
343//
344// There is confusion about whether libc::abort() flushes stdio streams.
345// libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
346// so flushing streams is at least extremely hard, if not entirely impossible.
347//
348// However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
349// do so. In 1003.1-2004 this was fixed.
350//
351// glibc's implementation did the flush, unsafely, before glibc commit
352// 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]` by Florian
353// Weimer. According to glibc's NEWS:
354//
355// The abort function terminates the process immediately, without flushing
356// stdio streams. Previous glibc versions used to flush streams, resulting
357// in deadlocks and further data corruption. This change also affects
358// process aborts as the result of assertion failures.
359//
360// This is an accurate description of the problem. The only solution for
361// program with nontrivial use of C stdio is a fixed libc - one which does not
362// try to flush in abort - since even libc-internal errors, and assertion
363// failures generated from C, will go via abort().
364//
365// On systems with old, buggy, libcs, the impact can be severe for a
366// multithreaded C program. It is much less severe for Rust, because Rust
367// stdlib doesn't use libc stdio buffering. In a typical Rust program, which
368// does not use C stdio, even a buggy libc::abort() is, in fact, safe.
369pub fn abort_internal() -> ! {
370 unsafe { libc::abort() }
371}
372
373cfg_if::cfg_if! {
374 if #[cfg(target_os = "android")] {
375 #[link(name = "dl", kind = "static", modifiers = "-bundle",
376 cfg(target_feature = "crt-static"))]
377 #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
378 #[link(name = "log", cfg(not(target_feature = "crt-static")))]
379 extern "C" {}
380 } else if #[cfg(target_os = "freebsd")] {
381 #[link(name = "execinfo")]
382 #[link(name = "pthread")]
383 extern "C" {}
384 } else if #[cfg(target_os = "netbsd")] {
385 #[link(name = "pthread")]
386 #[link(name = "rt")]
387 extern "C" {}
388 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
389 #[link(name = "pthread")]
390 extern "C" {}
391 } else if #[cfg(target_os = "solaris")] {
392 #[link(name = "socket")]
393 #[link(name = "posix4")]
394 #[link(name = "pthread")]
395 #[link(name = "resolv")]
396 extern "C" {}
397 } else if #[cfg(target_os = "illumos")] {
398 #[link(name = "socket")]
399 #[link(name = "posix4")]
400 #[link(name = "pthread")]
401 #[link(name = "resolv")]
402 #[link(name = "nsl")]
403 // Use libumem for the (malloc-compatible) allocator
404 #[link(name = "umem")]
405 extern "C" {}
406 } else if #[cfg(target_os = "macos")] {
407 #[link(name = "System")]
408 extern "C" {}
409 } else if #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] {
410 #[link(name = "System")]
411 #[link(name = "objc")]
412 #[link(name = "Foundation", kind = "framework")]
413 extern "C" {}
414 } else if #[cfg(target_os = "fuchsia")] {
415 #[link(name = "zircon")]
416 #[link(name = "fdio")]
417 extern "C" {}
418 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
419 #[link(name = "dl")]
420 extern "C" {}
421 } else if #[cfg(target_os = "vita")] {
422 #[link(name = "pthread", kind = "static", modifiers = "-bundle")]
423 extern "C" {}
424 }
425}
426
427#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
428mod unsupported {
429 use crate::io;
430
431 pub fn unsupported<T>() -> io::Result<T> {
432 Err(unsupported_err())
433 }
434
435 pub fn unsupported_err() -> io::Error {
436 io::Error::UNSUPPORTED_PLATFORM
437 }
438}
439