]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mod.rs
Rollup merge of #101072 - tmandry:llvm-is-vanilla, r=Mark-Simulacrum
[rust.git] / library / std / src / sys / unix / mod.rs
1 #![allow(missing_docs, nonstandard_style)]
2
3 use crate::ffi::CStr;
4 use crate::io::ErrorKind;
5
6 pub use self::rand::hashmap_random_keys;
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 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 locks;
27 pub mod memchr;
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 os_str;
34 pub mod path;
35 pub mod pipe;
36 pub mod process;
37 pub mod rand;
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 thread_parker;
44 pub mod time;
45
46 #[cfg(target_os = "espidf")]
47 pub fn init(argc: isize, argv: *const *const u8) {}
48
49 #[cfg(not(target_os = "espidf"))]
50 // SAFETY: must be called only once during runtime initialization.
51 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
52 pub unsafe fn init(argc: isize, argv: *const *const u8) {
53     // The standard streams might be closed on application startup. To prevent
54     // std::io::{stdin, stdout,stderr} objects from using other unrelated file
55     // resources opened later, we reopen standards streams when they are closed.
56     sanitize_standard_fds();
57
58     // By default, some platforms will send a *signal* when an EPIPE error
59     // would otherwise be delivered. This runtime doesn't install a SIGPIPE
60     // handler, causing it to kill the program, which isn't exactly what we
61     // want!
62     //
63     // Hence, we set SIGPIPE to ignore when the program starts up in order
64     // to prevent this problem.
65     reset_sigpipe();
66
67     stack_overflow::init();
68     args::init(argc, argv);
69
70     // Normally, `thread::spawn` will call `Thread::set_name` but since this thread
71     // already exists, we have to call it ourselves. We only do this on macos
72     // because some unix-like operating systems such as Linux share process-id and
73     // thread-id for the main thread and so renaming the main thread will rename the
74     // process and we only want to enable this on platforms we've tested.
75     if cfg!(target_os = "macos") {
76         thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
77     }
78
79     unsafe fn sanitize_standard_fds() {
80         // fast path with a single syscall for systems with poll()
81         #[cfg(not(any(
82             miri,
83             target_os = "emscripten",
84             target_os = "fuchsia",
85             target_os = "vxworks",
86             // The poll on Darwin doesn't set POLLNVAL for closed fds.
87             target_os = "macos",
88             target_os = "ios",
89             target_os = "watchos",
90             target_os = "redox",
91             target_os = "l4re",
92             target_os = "horizon",
93         )))]
94         'poll: {
95             use crate::sys::os::errno;
96             let pfds: &mut [_] = &mut [
97                 libc::pollfd { fd: 0, events: 0, revents: 0 },
98                 libc::pollfd { fd: 1, events: 0, revents: 0 },
99                 libc::pollfd { fd: 2, events: 0, revents: 0 },
100             ];
101
102             while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
103                 match errno() {
104                     libc::EINTR => continue,
105                     libc::EINVAL | libc::EAGAIN | libc::ENOMEM => {
106                         // RLIMIT_NOFILE or temporary allocation failures
107                         // may be preventing use of poll(), fall back to fcntl
108                         break 'poll;
109                     }
110                     _ => libc::abort(),
111                 }
112             }
113             for pfd in pfds {
114                 if pfd.revents & libc::POLLNVAL == 0 {
115                     continue;
116                 }
117                 if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
118                     // If the stream is closed but we failed to reopen it, abort the
119                     // process. Otherwise we wouldn't preserve the safety of
120                     // operations on the corresponding Rust object Stdin, Stdout, or
121                     // Stderr.
122                     libc::abort();
123                 }
124             }
125             return;
126         }
127
128         // fallback in case poll isn't available or limited by RLIMIT_NOFILE
129         #[cfg(not(any(
130             // The standard fds are always available in Miri.
131             miri,
132             target_os = "emscripten",
133             target_os = "fuchsia",
134             target_os = "vxworks",
135             target_os = "l4re",
136             target_os = "horizon",
137         )))]
138         {
139             use crate::sys::os::errno;
140             for fd in 0..3 {
141                 if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
142                     if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
143                         // If the stream is closed but we failed to reopen it, abort the
144                         // process. Otherwise we wouldn't preserve the safety of
145                         // operations on the corresponding Rust object Stdin, Stdout, or
146                         // Stderr.
147                         libc::abort();
148                     }
149                 }
150             }
151         }
152     }
153
154     unsafe fn reset_sigpipe() {
155         #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia", target_os = "horizon")))]
156         rtassert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
157     }
158 }
159
160 // SAFETY: must be called only once during runtime cleanup.
161 // NOTE: this is not guaranteed to run, for example when the program aborts.
162 pub unsafe fn cleanup() {
163     stack_overflow::cleanup();
164 }
165
166 #[cfg(target_os = "android")]
167 pub use crate::sys::android::signal;
168 #[cfg(not(target_os = "android"))]
169 pub use libc::signal;
170
171 pub fn decode_error_kind(errno: i32) -> ErrorKind {
172     use ErrorKind::*;
173     match errno as libc::c_int {
174         libc::E2BIG => ArgumentListTooLong,
175         libc::EADDRINUSE => AddrInUse,
176         libc::EADDRNOTAVAIL => AddrNotAvailable,
177         libc::EBUSY => ResourceBusy,
178         libc::ECONNABORTED => ConnectionAborted,
179         libc::ECONNREFUSED => ConnectionRefused,
180         libc::ECONNRESET => ConnectionReset,
181         libc::EDEADLK => Deadlock,
182         libc::EDQUOT => FilesystemQuotaExceeded,
183         libc::EEXIST => AlreadyExists,
184         libc::EFBIG => FileTooLarge,
185         libc::EHOSTUNREACH => HostUnreachable,
186         libc::EINTR => Interrupted,
187         libc::EINVAL => InvalidInput,
188         libc::EISDIR => IsADirectory,
189         libc::ELOOP => FilesystemLoop,
190         libc::ENOENT => NotFound,
191         libc::ENOMEM => OutOfMemory,
192         libc::ENOSPC => StorageFull,
193         libc::ENOSYS => Unsupported,
194         libc::EMLINK => TooManyLinks,
195         libc::ENAMETOOLONG => InvalidFilename,
196         libc::ENETDOWN => NetworkDown,
197         libc::ENETUNREACH => NetworkUnreachable,
198         libc::ENOTCONN => NotConnected,
199         libc::ENOTDIR => NotADirectory,
200         libc::ENOTEMPTY => DirectoryNotEmpty,
201         libc::EPIPE => BrokenPipe,
202         libc::EROFS => ReadOnlyFilesystem,
203         libc::ESPIPE => NotSeekable,
204         libc::ESTALE => StaleNetworkFileHandle,
205         libc::ETIMEDOUT => TimedOut,
206         libc::ETXTBSY => ExecutableFileBusy,
207         libc::EXDEV => CrossesDevices,
208
209         libc::EACCES | libc::EPERM => PermissionDenied,
210
211         // These two constants can have the same value on some systems,
212         // but different values on others, so we can't use a match
213         // clause
214         x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,
215
216         _ => Uncategorized,
217     }
218 }
219
220 #[doc(hidden)]
221 pub trait IsMinusOne {
222     fn is_minus_one(&self) -> bool;
223 }
224
225 macro_rules! impl_is_minus_one {
226     ($($t:ident)*) => ($(impl IsMinusOne for $t {
227         fn is_minus_one(&self) -> bool {
228             *self == -1
229         }
230     })*)
231 }
232
233 impl_is_minus_one! { i8 i16 i32 i64 isize }
234
235 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
236     if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
237 }
238
239 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
240 where
241     T: IsMinusOne,
242     F: FnMut() -> T,
243 {
244     loop {
245         match cvt(f()) {
246             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
247             other => return other,
248         }
249     }
250 }
251
252 #[allow(dead_code)] // Not used on all platforms.
253 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
254     if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
255 }
256
257 // libc::abort() will run the SIGABRT handler.  That's fine because anyone who
258 // installs a SIGABRT handler already has to expect it to run in Very Bad
259 // situations (eg, malloc crashing).
260 //
261 // Current glibc's abort() function unblocks SIGABRT, raises SIGABRT, clears the
262 // SIGABRT handler and raises it again, and then starts to get creative.
263 //
264 // See the public documentation for `intrinsics::abort()` and `process::abort()`
265 // for further discussion.
266 //
267 // There is confusion about whether libc::abort() flushes stdio streams.
268 // libc::abort() is required by ISO C 99 (7.14.1.1p5) to be async-signal-safe,
269 // so flushing streams is at least extremely hard, if not entirely impossible.
270 //
271 // However, some versions of POSIX (eg IEEE Std 1003.1-2001) required abort to
272 // do so.  In 1003.1-2004 this was fixed.
273 //
274 // glibc's implementation did the flush, unsafely, before glibc commit
275 // 91e7cf982d01 `abort: Do not flush stdio streams [BZ #15436]' by Florian
276 // Weimer.  According to glibc's NEWS:
277 //
278 //    The abort function terminates the process immediately, without flushing
279 //    stdio streams.  Previous glibc versions used to flush streams, resulting
280 //    in deadlocks and further data corruption.  This change also affects
281 //    process aborts as the result of assertion failures.
282 //
283 // This is an accurate description of the problem.  The only solution for
284 // program with nontrivial use of C stdio is a fixed libc - one which does not
285 // try to flush in abort - since even libc-internal errors, and assertion
286 // failures generated from C, will go via abort().
287 //
288 // On systems with old, buggy, libcs, the impact can be severe for a
289 // multithreaded C program.  It is much less severe for Rust, because Rust
290 // stdlib doesn't use libc stdio buffering.  In a typical Rust program, which
291 // does not use C stdio, even a buggy libc::abort() is, in fact, safe.
292 pub fn abort_internal() -> ! {
293     unsafe { libc::abort() }
294 }
295
296 cfg_if::cfg_if! {
297     if #[cfg(target_os = "android")] {
298         #[link(name = "dl", kind = "static", modifiers = "-bundle",
299             cfg(target_feature = "crt-static"))]
300         #[link(name = "dl", cfg(not(target_feature = "crt-static")))]
301         #[link(name = "log", cfg(not(target_feature = "crt-static")))]
302         extern "C" {}
303     } else if #[cfg(target_os = "freebsd")] {
304         #[link(name = "execinfo")]
305         #[link(name = "pthread")]
306         extern "C" {}
307     } else if #[cfg(target_os = "netbsd")] {
308         #[link(name = "pthread")]
309         #[link(name = "rt")]
310         extern "C" {}
311     } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
312         #[link(name = "pthread")]
313         extern "C" {}
314     } else if #[cfg(target_os = "solaris")] {
315         #[link(name = "socket")]
316         #[link(name = "posix4")]
317         #[link(name = "pthread")]
318         #[link(name = "resolv")]
319         extern "C" {}
320     } else if #[cfg(target_os = "illumos")] {
321         #[link(name = "socket")]
322         #[link(name = "posix4")]
323         #[link(name = "pthread")]
324         #[link(name = "resolv")]
325         #[link(name = "nsl")]
326         // Use libumem for the (malloc-compatible) allocator
327         #[link(name = "umem")]
328         extern "C" {}
329     } else if #[cfg(target_os = "macos")] {
330         #[link(name = "System")]
331         // res_init and friends require -lresolv on macOS/iOS.
332         // See #41582 and https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
333         #[link(name = "resolv")]
334         extern "C" {}
335     } else if #[cfg(any(target_os = "ios", target_os = "watchos"))] {
336         #[link(name = "System")]
337         #[link(name = "objc")]
338         #[link(name = "Security", kind = "framework")]
339         #[link(name = "Foundation", kind = "framework")]
340         #[link(name = "resolv")]
341         extern "C" {}
342     } else if #[cfg(target_os = "fuchsia")] {
343         #[link(name = "zircon")]
344         #[link(name = "fdio")]
345         extern "C" {}
346     } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
347         #[link(name = "dl")]
348         extern "C" {}
349     }
350 }
351
352 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
353 mod unsupported {
354     use crate::io;
355
356     pub fn unsupported<T>() -> io::Result<T> {
357         Err(unsupported_err())
358     }
359
360     pub fn unsupported_err() -> io::Error {
361         io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)
362     }
363 }