]> git.proxmox.com Git - rustc.git/blob - library/std/src/sys/unix/mod.rs
9e553ec7682b1a3b82a98f8636232ddcb35501fd
[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 #[macro_use]
9 pub mod weak;
10
11 pub mod alloc;
12 pub mod android;
13 pub mod args;
14 #[path = "../unix/cmath.rs"]
15 pub mod cmath;
16 pub mod condvar;
17 pub mod env;
18 pub mod fd;
19 pub mod fs;
20 pub mod futex;
21 pub mod io;
22 #[cfg(any(target_os = "linux", target_os = "android"))]
23 pub mod kernel_copy;
24 #[cfg(target_os = "l4re")]
25 mod l4re;
26 pub mod memchr;
27 pub mod mutex;
28 #[cfg(not(target_os = "l4re"))]
29 pub mod net;
30 #[cfg(target_os = "l4re")]
31 pub use self::l4re::net;
32 pub mod os;
33 pub mod path;
34 pub mod pipe;
35 pub mod process;
36 pub mod rand;
37 pub mod rwlock;
38 pub mod stack_overflow;
39 pub mod stdio;
40 pub mod thread;
41 pub mod thread_local_dtor;
42 pub mod thread_local_key;
43 pub mod time;
44
45 pub use crate::sys_common::os_str_bytes as os_str;
46
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();
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.
62 reset_sigpipe();
63
64 stack_overflow::init();
65 args::init(argc, argv);
66
67 unsafe fn sanitize_standard_fds() {
68 #[cfg(not(miri))]
69 // The standard fds are always available in Miri.
70 cfg_if::cfg_if! {
71 if #[cfg(not(any(
72 target_os = "emscripten",
73 target_os = "fuchsia",
74 target_os = "vxworks",
75 // The poll on Darwin doesn't set POLLNVAL for closed fds.
76 target_os = "macos",
77 target_os = "ios",
78 target_os = "redox",
79 )))] {
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 },
85 ];
86 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
87 if errno() == libc::EINTR {
88 continue;
89 }
90 libc::abort();
91 }
92 for pfd in pfds {
93 if pfd.revents & libc::POLLNVAL == 0 {
94 continue;
95 }
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
100 // Stderr.
101 libc::abort();
102 }
103 }
104 } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
105 use crate::sys::os::errno;
106 for fd in 0..3 {
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 {
109 libc::abort();
110 }
111 }
112 }
113 }
114 }
115 }
116
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);
120 }
121 }
122
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();
127 }
128
129 #[cfg(target_os = "android")]
130 pub use crate::sys::android::signal;
131 #[cfg(not(target_os = "android"))]
132 pub use libc::signal;
133
134 pub fn decode_error_kind(errno: i32) -> ErrorKind {
135 use 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,
171
172 libc::EACCES | libc::EPERM => PermissionDenied,
173
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
176 // clause
177 x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
178
179 _ => Uncategorized,
180 }
181 }
182
183 #[doc(hidden)]
184 pub trait IsMinusOne {
185 fn is_minus_one(&self) -> bool;
186 }
187
188 macro_rules! impl_is_minus_one {
189 ($($t:ident)*) => ($(impl IsMinusOne for $t {
190 fn is_minus_one(&self) -> bool {
191 *self == -1
192 }
193 })*)
194 }
195
196 impl_is_minus_one! { i8 i16 i32 i64 isize }
197
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) }
200 }
201
202 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
203 where
204 T: IsMinusOne,
205 F: FnMut() -> T,
206 {
207 loop {
208 match cvt(f()) {
209 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
210 other => return other,
211 }
212 }
213 }
214
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)) }
217 }
218
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).
222 //
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.
225 //
226 // See the public documentation for `intrinsics::abort()` and `process::abort()`
227 // for further discussion.
228 //
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.
232 //
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.
235 //
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:
239 //
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.
244 //
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().
249 //
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() }
256 }
257
258 cfg_if::cfg_if! {
259 if #[cfg(target_os = "android")] {
260 #[link(name = "dl")]
261 #[link(name = "log")]
262 extern "C" {}
263 } else if #[cfg(target_os = "freebsd")] {
264 #[link(name = "execinfo")]
265 #[link(name = "pthread")]
266 extern "C" {}
267 } else if #[cfg(target_os = "netbsd")] {
268 #[link(name = "pthread")]
269 #[link(name = "rt")]
270 extern "C" {}
271 } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
272 #[link(name = "pthread")]
273 extern "C" {}
274 } else if #[cfg(target_os = "solaris")] {
275 #[link(name = "socket")]
276 #[link(name = "posix4")]
277 #[link(name = "pthread")]
278 #[link(name = "resolv")]
279 extern "C" {}
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")]
288 extern "C" {}
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")]
294 extern "C" {}
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")]
301 extern "C" {}
302 } else if #[cfg(target_os = "fuchsia")] {
303 #[link(name = "zircon")]
304 #[link(name = "fdio")]
305 extern "C" {}
306 }
307 }