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