]> git.proxmox.com Git - rustc.git/blob - library/std/src/sys/unix/mod.rs
2ba6c8d830ede552890c37898353615bf2a69dc8
[rustc.git] / library / std / src / sys / unix / mod.rs
1 #![allow(missing_docs, nonstandard_style)]
2
3 use crate::io::ErrorKind;
4
5 pub use self::rand::hashmap_random_keys;
6 pub use libc::strlen;
7
8 #[cfg(not(target_os = "espidf"))]
9 #[macro_use]
10 pub mod weak;
11
12 pub mod alloc;
13 pub mod android;
14 pub mod args;
15 #[path = "../unix/cmath.rs"]
16 pub mod cmath;
17 pub mod condvar;
18 pub mod env;
19 pub mod fd;
20 pub mod fs;
21 pub mod futex;
22 pub mod io;
23 #[cfg(any(target_os = "linux", target_os = "android"))]
24 pub mod kernel_copy;
25 #[cfg(target_os = "l4re")]
26 mod l4re;
27 pub mod memchr;
28 pub mod mutex;
29 #[cfg(not(target_os = "l4re"))]
30 pub mod net;
31 #[cfg(target_os = "l4re")]
32 pub use self::l4re::net;
33 pub mod os;
34 pub mod os_str;
35 pub mod path;
36 pub mod pipe;
37 pub mod process;
38 pub mod rand;
39 pub mod rwlock;
40 pub mod stack_overflow;
41 pub mod stdio;
42 pub mod thread;
43 pub mod thread_local_dtor;
44 pub mod thread_local_key;
45 pub mod time;
46
47 #[cfg(target_os = "espidf")]
48 pub fn init(argc: isize, argv: *const *const u8) {}
49
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();
58
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
62 // want!
63 //
64 // Hence, we set SIGPIPE to ignore when the program starts up in order
65 // to prevent this problem.
66 reset_sigpipe();
67
68 stack_overflow::init();
69 args::init(argc, argv);
70
71 unsafe fn sanitize_standard_fds() {
72 #[cfg(not(miri))]
73 // The standard fds are always available in Miri.
74 cfg_if::cfg_if! {
75 if #[cfg(not(any(
76 target_os = "emscripten",
77 target_os = "fuchsia",
78 target_os = "vxworks",
79 // The poll on Darwin doesn't set POLLNVAL for closed fds.
80 target_os = "macos",
81 target_os = "ios",
82 target_os = "redox",
83 )))] {
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 },
89 ];
90 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
91 if errno() == libc::EINTR {
92 continue;
93 }
94 libc::abort();
95 }
96 for pfd in pfds {
97 if pfd.revents & libc::POLLNVAL == 0 {
98 continue;
99 }
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
104 // Stderr.
105 libc::abort();
106 }
107 }
108 } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
109 use crate::sys::os::errno;
110 for fd in 0..3 {
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 {
113 libc::abort();
114 }
115 }
116 }
117 }
118 }
119 }
120
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);
124 }
125 }
126
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();
131 }
132
133 #[cfg(target_os = "android")]
134 pub use crate::sys::android::signal;
135 #[cfg(not(target_os = "android"))]
136 pub use libc::signal;
137
138 pub fn decode_error_kind(errno: i32) -> ErrorKind {
139 use 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 => FilenameTooLong,
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,
175
176 libc::EACCES | libc::EPERM => PermissionDenied,
177
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
180 // clause
181 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
182
183 _ => Uncategorized,
184 }
185 }
186
187 #[doc(hidden)]
188 pub trait IsMinusOne {
189 fn is_minus_one(&self) -> bool;
190 }
191
192 macro_rules! impl_is_minus_one {
193 ($($t:ident)*) => ($(impl IsMinusOne for $t {
194 fn is_minus_one(&self) -> bool {
195 *self == -1
196 }
197 })*)
198 }
199
200 impl_is_minus_one! { i8 i16 i32 i64 isize }
201
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) }
204 }
205
206 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
207 where
208 T: IsMinusOne,
209 F: FnMut() -> T,
210 {
211 loop {
212 match cvt(f()) {
213 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
214 other => return other,
215 }
216 }
217 }
218
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)) }
221 }
222
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).
226 //
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.
229 //
230 // See the public documentation for `intrinsics::abort()` and `process::abort()`
231 // for further discussion.
232 //
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.
236 //
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.
239 //
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:
243 //
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.
248 //
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().
253 //
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() }
260 }
261
262 cfg_if::cfg_if! {
263 if #[cfg(target_os = "android")] {
264 #[link(name = "dl")]
265 #[link(name = "log")]
266 extern "C" {}
267 } else if #[cfg(target_os = "freebsd")] {
268 #[link(name = "execinfo")]
269 #[link(name = "pthread")]
270 extern "C" {}
271 } else if #[cfg(target_os = "netbsd")] {
272 #[link(name = "pthread")]
273 #[link(name = "rt")]
274 extern "C" {}
275 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
276 #[link(name = "pthread")]
277 extern "C" {}
278 } else if #[cfg(target_os = "solaris")] {
279 #[link(name = "socket")]
280 #[link(name = "posix4")]
281 #[link(name = "pthread")]
282 #[link(name = "resolv")]
283 extern "C" {}
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")]
292 extern "C" {}
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")]
298 extern "C" {}
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")]
305 extern "C" {}
306 } else if #[cfg(target_os = "fuchsia")] {
307 #[link(name = "zircon")]
308 #[link(name = "fdio")]
309 extern "C" {}
310 } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
311 #[link(name = "dl")]
312 extern "C" {}
313 }
314 }
315
316 #[cfg(target_os = "espidf")]
317 mod unsupported {
318 use crate::io;
319
320 pub fn unsupported<T>() -> io::Result<T> {
321 Err(unsupported_err())
322 }
323
324 pub fn unsupported_err() -> io::Error {
325 io::Error::new_const(
326 io::ErrorKind::Unsupported,
327 &"operation not supported on this platform",
328 )
329 }
330 }