]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mod.rs
Rollup merge of #83553 - jfrimmel:addr-of, r=m-ou-se
[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         libc::ENOMEM => ErrorKind::OutOfMemory,
153
154         // These two constants can have the same value on some systems,
155         // but different values on others, so we can't use a match
156         // clause
157         x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock,
158
159         _ => ErrorKind::Other,
160     }
161 }
162
163 #[doc(hidden)]
164 pub trait IsMinusOne {
165     fn is_minus_one(&self) -> bool;
166 }
167
168 macro_rules! impl_is_minus_one {
169     ($($t:ident)*) => ($(impl IsMinusOne for $t {
170         fn is_minus_one(&self) -> bool {
171             *self == -1
172         }
173     })*)
174 }
175
176 impl_is_minus_one! { i8 i16 i32 i64 isize }
177
178 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
179     if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
180 }
181
182 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
183 where
184     T: IsMinusOne,
185     F: FnMut() -> T,
186 {
187     loop {
188         match cvt(f()) {
189             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
190             other => return other,
191         }
192     }
193 }
194
195 pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
196     if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
197 }
198
199 // On Unix-like platforms, libc::abort will unregister signal handlers
200 // including the SIGABRT handler, preventing the abort from being blocked, and
201 // fclose streams, with the side effect of flushing them so libc buffered
202 // output will be printed.  Additionally the shell will generally print a more
203 // understandable error message like "Abort trap" rather than "Illegal
204 // instruction" that intrinsics::abort would cause, as intrinsics::abort is
205 // implemented as an illegal instruction.
206 pub fn abort_internal() -> ! {
207     unsafe { libc::abort() }
208 }
209
210 cfg_if::cfg_if! {
211     if #[cfg(target_os = "android")] {
212         #[link(name = "dl")]
213         #[link(name = "log")]
214         #[link(name = "gcc")]
215         extern "C" {}
216     } else if #[cfg(target_os = "freebsd")] {
217         #[link(name = "execinfo")]
218         #[link(name = "pthread")]
219         extern "C" {}
220     } else if #[cfg(target_os = "netbsd")] {
221         #[link(name = "pthread")]
222         #[link(name = "rt")]
223         extern "C" {}
224     } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
225         #[link(name = "pthread")]
226         extern "C" {}
227     } else if #[cfg(target_os = "solaris")] {
228         #[link(name = "socket")]
229         #[link(name = "posix4")]
230         #[link(name = "pthread")]
231         #[link(name = "resolv")]
232         extern "C" {}
233     } else if #[cfg(target_os = "illumos")] {
234         #[link(name = "socket")]
235         #[link(name = "posix4")]
236         #[link(name = "pthread")]
237         #[link(name = "resolv")]
238         #[link(name = "nsl")]
239         // Use libumem for the (malloc-compatible) allocator
240         #[link(name = "umem")]
241         extern "C" {}
242     } else if #[cfg(target_os = "macos")] {
243         #[link(name = "System")]
244         // res_init and friends require -lresolv on macOS/iOS.
245         // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
246         #[link(name = "resolv")]
247         extern "C" {}
248     } else if #[cfg(target_os = "ios")] {
249         #[link(name = "System")]
250         #[link(name = "objc")]
251         #[link(name = "Security", kind = "framework")]
252         #[link(name = "Foundation", kind = "framework")]
253         #[link(name = "resolv")]
254         extern "C" {}
255     } else if #[cfg(target_os = "fuchsia")] {
256         #[link(name = "zircon")]
257         #[link(name = "fdio")]
258         extern "C" {}
259     }
260 }