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