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