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