]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mod.rs
Auto merge of #84410 - BoxyUwU:blue, r=varkor
[rust.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 ext;
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 path;
35 pub mod pipe;
36 pub mod process;
37 pub mod rand;
38 pub mod rwlock;
39 pub mod stack_overflow;
40 pub mod stdio;
41 pub mod thread;
42 pub mod thread_local_dtor;
43 pub mod thread_local_key;
44 pub mod time;
45
46 pub use crate::sys_common::os_str_bytes as os_str;
47
48 // SAFETY: must be called only once during runtime initialization.
49 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
50 pub unsafe fn init(argc: isize, argv: *const *const u8) {
51     // The standard streams might be closed on application startup. To prevent
52     // std::io::{stdin, stdout,stderr} objects from using other unrelated file
53     // resources opened later, we reopen standards streams when they are closed.
54     sanitize_standard_fds();
55
56     // By default, some platforms will send a *signal* when an EPIPE error
57     // would otherwise be delivered. This runtime doesn't install a SIGPIPE
58     // handler, causing it to kill the program, which isn't exactly what we
59     // want!
60     //
61     // Hence, we set SIGPIPE to ignore when the program starts up in order
62     // to prevent this problem.
63     reset_sigpipe();
64
65     stack_overflow::init();
66     args::init(argc, argv);
67
68     unsafe fn sanitize_standard_fds() {
69         #[cfg(not(miri))]
70         // The standard fds are always available in Miri.
71         cfg_if::cfg_if! {
72             if #[cfg(not(any(
73                 target_os = "emscripten",
74                 target_os = "fuchsia",
75                 target_os = "vxworks",
76                 // The poll on Darwin doesn't set POLLNVAL for closed fds.
77                 target_os = "macos",
78                 target_os = "ios",
79                 target_os = "redox",
80             )))] {
81                 use crate::sys::os::errno;
82                 let pfds: &mut [_] = &mut [
83                     libc::pollfd { fd: 0, events: 0, revents: 0 },
84                     libc::pollfd { fd: 1, events: 0, revents: 0 },
85                     libc::pollfd { fd: 2, events: 0, revents: 0 },
86                 ];
87                 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
88                     if errno() == libc::EINTR {
89                         continue;
90                     }
91                     libc::abort();
92                 }
93                 for pfd in pfds {
94                     if pfd.revents & libc::POLLNVAL == 0 {
95                         continue;
96                     }
97                     if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
98                         // If the stream is closed but we failed to reopen it, abort the
99                         // process. Otherwise we wouldn't preserve the safety of
100                         // operations on the corresponding Rust object Stdin, Stdout, or
101                         // Stderr.
102                         libc::abort();
103                     }
104                 }
105             } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
106                 use crate::sys::os::errno;
107                 for fd in 0..3 {
108                     if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
109                         if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
110                             libc::abort();
111                         }
112                     }
113                 }
114             }
115         }
116     }
117
118     unsafe fn reset_sigpipe() {
119         #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
120         assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
121     }
122 }
123
124 // SAFETY: must be called only once during runtime cleanup.
125 // NOTE: this is not guaranteed to run, for example when the program aborts.
126 pub unsafe fn cleanup() {
127     args::cleanup();
128     stack_overflow::cleanup();
129 }
130
131 #[cfg(target_os = "android")]
132 pub use crate::sys::android::signal;
133 #[cfg(not(target_os = "android"))]
134 pub use libc::signal;
135
136 pub fn decode_error_kind(errno: i32) -> ErrorKind {
137     match errno as libc::c_int {
138         libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
139         libc::ECONNRESET => ErrorKind::ConnectionReset,
140         libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
141         libc::EPIPE => ErrorKind::BrokenPipe,
142         libc::ENOTCONN => ErrorKind::NotConnected,
143         libc::ECONNABORTED => ErrorKind::ConnectionAborted,
144         libc::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
145         libc::EADDRINUSE => ErrorKind::AddrInUse,
146         libc::ENOENT => ErrorKind::NotFound,
147         libc::EINTR => ErrorKind::Interrupted,
148         libc::EINVAL => ErrorKind::InvalidInput,
149         libc::ETIMEDOUT => ErrorKind::TimedOut,
150         libc::EEXIST => ErrorKind::AlreadyExists,
151         libc::ENOSYS => ErrorKind::Unsupported,
152
153         // These two constants can have the same value on some systems,
154         // but different values on others, so we can't use a match
155         // clause
156         x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock,
157
158         _ => ErrorKind::Other,
159     }
160 }
161
162 #[doc(hidden)]
163 pub trait IsMinusOne {
164     fn is_minus_one(&self) -> bool;
165 }
166
167 macro_rules! impl_is_minus_one {
168     ($($t:ident)*) => ($(impl IsMinusOne for $t {
169         fn is_minus_one(&self) -> bool {
170             *self == -1
171         }
172     })*)
173 }
174
175 impl_is_minus_one! { i8 i16 i32 i64 isize }
176
177 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
178     if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
179 }
180
181 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
182 where
183     T: IsMinusOne,
184     F: FnMut() -> T,
185 {
186     loop {
187         match cvt(f()) {
188             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
189             other => return other,
190         }
191     }
192 }
193
194 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
195     if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
196 }
197
198 // On Unix-like platforms, libc::abort will unregister signal handlers
199 // including the SIGABRT handler, preventing the abort from being blocked, and
200 // fclose streams, with the side effect of flushing them so libc buffered
201 // output will be printed.  Additionally the shell will generally print a more
202 // understandable error message like "Abort trap" rather than "Illegal
203 // instruction" that intrinsics::abort would cause, as intrinsics::abort is
204 // implemented as an illegal instruction.
205 pub fn abort_internal() -> ! {
206     unsafe { libc::abort() }
207 }
208
209 cfg_if::cfg_if! {
210     if #[cfg(target_os = "android")] {
211         #[link(name = "dl")]
212         #[link(name = "log")]
213         #[link(name = "gcc")]
214         extern "C" {}
215     } else if #[cfg(target_os = "freebsd")] {
216         #[link(name = "execinfo")]
217         #[link(name = "pthread")]
218         extern "C" {}
219     } else if #[cfg(target_os = "netbsd")] {
220         #[link(name = "pthread")]
221         #[link(name = "rt")]
222         extern "C" {}
223     } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
224         #[link(name = "pthread")]
225         extern "C" {}
226     } else if #[cfg(target_os = "solaris")] {
227         #[link(name = "socket")]
228         #[link(name = "posix4")]
229         #[link(name = "pthread")]
230         #[link(name = "resolv")]
231         extern "C" {}
232     } else if #[cfg(target_os = "illumos")] {
233         #[link(name = "socket")]
234         #[link(name = "posix4")]
235         #[link(name = "pthread")]
236         #[link(name = "resolv")]
237         #[link(name = "nsl")]
238         // Use libumem for the (malloc-compatible) allocator
239         #[link(name = "umem")]
240         extern "C" {}
241     } else if #[cfg(target_os = "macos")] {
242         #[link(name = "System")]
243         // res_init and friends require -lresolv on macOS/iOS.
244         // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
245         #[link(name = "resolv")]
246         extern "C" {}
247     } else if #[cfg(target_os = "ios")] {
248         #[link(name = "System")]
249         #[link(name = "objc")]
250         #[link(name = "Security", kind = "framework")]
251         #[link(name = "Foundation", kind = "framework")]
252         #[link(name = "resolv")]
253         extern "C" {}
254     } else if #[cfg(target_os = "fuchsia")] {
255         #[link(name = "zircon")]
256         #[link(name = "fdio")]
257         extern "C" {}
258     }
259 }