]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mod.rs
ae16ea07f247824a1f55f3cbbe8da1ffae84e843
[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 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 // NOTE: this is not guaranteed to run, for example when Rust code is called externally.
49 pub unsafe fn init(argc: isize, argv: *const *const u8) {
50     // The standard streams might be closed on application startup. To prevent
51     // std::io::{stdin, stdout,stderr} objects from using other unrelated file
52     // resources opened later, we reopen standards streams when they are closed.
53     sanitize_standard_fds();
54
55     // By default, some platforms will send a *signal* when an EPIPE error
56     // would otherwise be delivered. This runtime doesn't install a SIGPIPE
57     // handler, causing it to kill the program, which isn't exactly what we
58     // want!
59     //
60     // Hence, we set SIGPIPE to ignore when the program starts up in order
61     // to prevent this problem.
62     reset_sigpipe();
63
64     stack_overflow::init();
65     args::init(argc, argv);
66
67     unsafe fn sanitize_standard_fds() {
68         #[cfg(not(miri))]
69         // The standard fds are always available in Miri.
70         cfg_if::cfg_if! {
71             if #[cfg(not(any(
72                 target_os = "emscripten",
73                 target_os = "fuchsia",
74                 target_os = "vxworks",
75                 // The poll on Darwin doesn't set POLLNVAL for closed fds.
76                 target_os = "macos",
77                 target_os = "ios",
78                 target_os = "redox",
79             )))] {
80                 use crate::sys::os::errno;
81                 let pfds: &mut [_] = &mut [
82                     libc::pollfd { fd: 0, events: 0, revents: 0 },
83                     libc::pollfd { fd: 1, events: 0, revents: 0 },
84                     libc::pollfd { fd: 2, events: 0, revents: 0 },
85                 ];
86                 while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
87                     if errno() == libc::EINTR {
88                         continue;
89                     }
90                     libc::abort();
91                 }
92                 for pfd in pfds {
93                     if pfd.revents & libc::POLLNVAL == 0 {
94                         continue;
95                     }
96                     if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
97                         // If the stream is closed but we failed to reopen it, abort the
98                         // process. Otherwise we wouldn't preserve the safety of
99                         // operations on the corresponding Rust object Stdin, Stdout, or
100                         // Stderr.
101                         libc::abort();
102                     }
103                 }
104             } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
105                 use crate::sys::os::errno;
106                 for fd in 0..3 {
107                     if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
108                         if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
109                             libc::abort();
110                         }
111                     }
112                 }
113             }
114         }
115     }
116
117     unsafe fn reset_sigpipe() {
118         #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
119         assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
120     }
121 }
122
123 // SAFETY: must be called only once during runtime cleanup.
124 // NOTE: this is not guaranteed to run, for example when the program aborts.
125 pub unsafe fn cleanup() {
126     args::cleanup();
127     stack_overflow::cleanup();
128 }
129
130 #[cfg(target_os = "android")]
131 pub use crate::sys::android::signal;
132 #[cfg(not(target_os = "android"))]
133 pub use libc::signal;
134
135 pub fn decode_error_kind(errno: i32) -> ErrorKind {
136     match errno as libc::c_int {
137         libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
138         libc::ECONNRESET => ErrorKind::ConnectionReset,
139         libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
140         libc::EPIPE => ErrorKind::BrokenPipe,
141         libc::ENOTCONN => ErrorKind::NotConnected,
142         libc::ECONNABORTED => ErrorKind::ConnectionAborted,
143         libc::EADDRNOTAVAIL => ErrorKind::AddrNotAvailable,
144         libc::EADDRINUSE => ErrorKind::AddrInUse,
145         libc::ENOENT => ErrorKind::NotFound,
146         libc::EINTR => ErrorKind::Interrupted,
147         libc::EINVAL => ErrorKind::InvalidInput,
148         libc::ETIMEDOUT => ErrorKind::TimedOut,
149         libc::EEXIST => ErrorKind::AlreadyExists,
150         libc::ENOSYS => ErrorKind::Unsupported,
151         libc::ENOMEM => ErrorKind::OutOfMemory,
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::Unknown,
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 }