1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#![allow(missing_docs, nonstandard_style)]

use crate::io::ErrorKind;

pub use self::rand::hashmap_random_keys;
pub use libc::strlen;

#[cfg(not(target_os = "espidf"))]
#[macro_use]
pub mod weak;

pub mod alloc;
pub mod android;
pub mod args;
#[path = "../unix/cmath.rs"]
pub mod cmath;
pub mod condvar;
pub mod env;
pub mod fd;
pub mod fs;
pub mod futex;
pub mod io;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod kernel_copy;
#[cfg(target_os = "l4re")]
mod l4re;
pub mod memchr;
pub mod mutex;
#[cfg(not(target_os = "l4re"))]
pub mod net;
#[cfg(target_os = "l4re")]
pub use self::l4re::net;
pub mod os;
pub mod os_str;
pub mod path;
pub mod pipe;
pub mod process;
pub mod rand;
pub mod rwlock;
pub mod stack_overflow;
pub mod stdio;
pub mod thread;
pub mod thread_local_dtor;
pub mod thread_local_key;
pub mod time;

#[cfg(target_os = "espidf")]
pub fn init(argc: isize, argv: *const *const u8) {}

#[cfg(not(target_os = "espidf"))]
// SAFETY: 在运行时初始化期间只能调用一次。
// NOTE: 这不能保证运行,例如在外部调用 Rust 代码时。
pub unsafe fn init(argc: isize, argv: *const *const u8) {
    // 标准流可能会在应用程序启动时关闭。
    // 为防止 `std::io::{stdin,stdout,stderr}` 对象使用稍后打开的其他不相关文件资源,我们在关闭标准流后会重新打开它们。
    //
    sanitize_standard_fds();

    // 默认情况下,某些平台会在否则会传递 EPIPE 错误的情况下发送 *信号*。
    // 此运行时未安装 SIGPIPE 处理程序,导致它终止了程序,这不正是我们想要的!
    //
    //
    // 因此,为了防止出现此问题,我们将 SIGPIPE 设置为在程序启动时忽略。
    //
    //
    reset_sigpipe();

    stack_overflow::init();
    args::init(argc, argv);

    unsafe fn sanitize_standard_fds() {
        #[cfg(not(miri))]
        // 标准 fds 始终在 Miri 中可用。
        cfg_if::cfg_if! {
            if #[cfg(not(any(
                target_os = "emscripten",
                target_os = "fuchsia",
                target_os = "vxworks",
                // 达尔文 (Darwin) 的民意调查并未为封闭的 fds 设置 POLLNVAL。
                target_os = "macos",
                target_os = "ios",
                target_os = "redox",
            )))] {
                use crate::sys::os::errno;
                let pfds: &mut [_] = &mut [
                    libc::pollfd { fd: 0, events: 0, revents: 0 },
                    libc::pollfd { fd: 1, events: 0, revents: 0 },
                    libc::pollfd { fd: 2, events: 0, revents: 0 },
                ];
                while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 {
                    if errno() == libc::EINTR {
                        continue;
                    }
                    libc::abort();
                }
                for pfd in pfds {
                    if pfd.revents & libc::POLLNVAL == 0 {
                        continue;
                    }
                    if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
                        // 如果流已关闭,但未能重新打开它,则中止该进程。
                        // 否则,我们不会在相应的 Rust 对象 Stdin、Stdout 或 Stderr 上保持操作的安全性。
                        //
                        //
                        libc::abort();
                    }
                }
            } else if #[cfg(any(target_os = "macos", target_os = "ios", target_os = "redox"))] {
                use crate::sys::os::errno;
                for fd in 0..3 {
                    if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF {
                        if libc::open("/dev/null\0".as_ptr().cast(), libc::O_RDWR, 0) == -1 {
                            libc::abort();
                        }
                    }
                }
            }
        }
    }

    unsafe fn reset_sigpipe() {
        #[cfg(not(any(target_os = "emscripten", target_os = "fuchsia")))]
        rtassert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);
    }
}

// SAFETY: 在运行时清理期间只能调用一次。
// NOTE: 这不能保证运行,例如当程序中止时。
pub unsafe fn cleanup() {
    stack_overflow::cleanup();
}

#[cfg(target_os = "android")]
pub use crate::sys::android::signal;
#[cfg(not(target_os = "android"))]
pub use libc::signal;

pub fn decode_error_kind(errno: i32) -> ErrorKind {
    use ErrorKind::*;
    match errno as libc::c_int {
        libc::E2BIG => ArgumentListTooLong,
        libc::EADDRINUSE => AddrInUse,
        libc::EADDRNOTAVAIL => AddrNotAvailable,
        libc::EBUSY => ResourceBusy,
        libc::ECONNABORTED => ConnectionAborted,
        libc::ECONNREFUSED => ConnectionRefused,
        libc::ECONNRESET => ConnectionReset,
        libc::EDEADLK => Deadlock,
        libc::EDQUOT => FilesystemQuotaExceeded,
        libc::EEXIST => AlreadyExists,
        libc::EFBIG => FileTooLarge,
        libc::EHOSTUNREACH => HostUnreachable,
        libc::EINTR => Interrupted,
        libc::EINVAL => InvalidInput,
        libc::EISDIR => IsADirectory,
        libc::ELOOP => FilesystemLoop,
        libc::ENOENT => NotFound,
        libc::ENOMEM => OutOfMemory,
        libc::ENOSPC => StorageFull,
        libc::ENOSYS => Unsupported,
        libc::EMLINK => TooManyLinks,
        libc::ENAMETOOLONG => FilenameTooLong,
        libc::ENETDOWN => NetworkDown,
        libc::ENETUNREACH => NetworkUnreachable,
        libc::ENOTCONN => NotConnected,
        libc::ENOTDIR => NotADirectory,
        libc::ENOTEMPTY => DirectoryNotEmpty,
        libc::EPIPE => BrokenPipe,
        libc::EROFS => ReadOnlyFilesystem,
        libc::ESPIPE => NotSeekable,
        libc::ESTALE => StaleNetworkFileHandle,
        libc::ETIMEDOUT => TimedOut,
        libc::ETXTBSY => ExecutableFileBusy,
        libc::EXDEV => CrossesDevices,

        libc::EACCES | libc::EPERM => PermissionDenied,

        // 这两个常量在某些系统上可以具有相同的值,但在其他系统上可以具有不同的值,因此我们不能使用 match 子句
        //
        //
        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => WouldBlock,

        _ => Uncategorized,
    }
}

#[doc(hidden)]
pub trait IsMinusOne {
    fn is_minus_one(&self) -> bool;
}

macro_rules! impl_is_minus_one {
    ($($t:ident)*) => ($(impl IsMinusOne for $t {
        fn is_minus_one(&self) -> bool {
            *self == -1
        }
    })*)
}

impl_is_minus_one! { i8 i16 i32 i64 isize }

pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
    if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
}

pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
where
    T: IsMinusOne,
    F: FnMut() -> T,
{
    loop {
        match cvt(f()) {
            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
            other => return other,
        }
    }
}

pub fn cvt_nz(error: libc::c_int) -> crate::io::Result<()> {
    if error == 0 { Ok(()) } else { Err(crate::io::Error::from_raw_os_error(error)) }
}

// libc::abort () 将运行 SIGABRT 处理程序。这很好,因为任何安装 SIGABRT 处理程序的人都必须期望它在非常糟糕的情况下运行 (例如,malloc 崩溃)。
//
// 当前 glibc 的 abort() 函数解除对 SIGABRT 的阻塞,引发 SIGABRT,清除 SIGABRT 处理程序并再次引发它,然后开始发挥创意。
//
// 有关进一步讨论,请参见 `intrinsics::abort()` 和 `process::abort()` 的公共文档。
//
// 关于 libc::abort () 是否刷新标准输入输出流存在混淆。
// ISO C 99 (7.14.1.1p5) 要求 libc::abort () 是异步信号安全的,因此刷新流至少非常困难,如果不是完全不可能的话。
//
// 但是,某些版本的 POSIX (例如 IEEE Std 1003.1-2001) 需要终止来执行此操作。在 1003.1-2004 中,这是确定的。
//
// glibc 的实现在 glibc 提交之前不安全地进行了刷新
// 91e7cf982d01 `关于:不要刷新标准输入输出流 [BZ #15436] by Florian Weimer。根据 glibc 的新闻:
//
//    终止函数立即终止该过程,而不刷新标准输入输出流。以前的 glibc 版本用于刷新流,导致死锁和进一步的数据损坏。
//    由于断言失败,此更改还会影响进程中止。
//
// 这是对问题的准确描述。
// 对于非平凡使用 C 标准输入输出的程序,唯一的解决方案是固定的 libc - 一个不会尝试在终止中刷新 - 因为即使是 libc 内部错误,以及由 C 产生的断言失败,也会通过 abort()。
//
//
// 在具有旧的 buggy、libcs 的系统上,对多线程 C 程序的影响可能很严重。Rust 的严重程度要低得多,因为 Rust stdlib 不使用 libc 标准输入输出缓冲。
// 在典型的 Rust 程序中,不使用 C 标准输入输出,即使是 buggy libc::abort () 实际上也是安全的。
//
//
//
//
//
//
//
//
//
//
//
//
pub fn abort_internal() -> ! {
    unsafe { libc::abort() }
}

cfg_if::cfg_if! {
    if #[cfg(target_os = "android")] {
        #[link(name = "dl")]
        #[link(name = "log")]
        extern "C" {}
    } else if #[cfg(target_os = "freebsd")] {
        #[link(name = "execinfo")]
        #[link(name = "pthread")]
        extern "C" {}
    } else if #[cfg(target_os = "netbsd")] {
        #[link(name = "pthread")]
        #[link(name = "rt")]
        extern "C" {}
    } else if #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] {
        #[link(name = "pthread")]
        extern "C" {}
    } else if #[cfg(target_os = "solaris")] {
        #[link(name = "socket")]
        #[link(name = "posix4")]
        #[link(name = "pthread")]
        #[link(name = "resolv")]
        extern "C" {}
    } else if #[cfg(target_os = "illumos")] {
        #[link(name = "socket")]
        #[link(name = "posix4")]
        #[link(name = "pthread")]
        #[link(name = "resolv")]
        #[link(name = "nsl")]
        // 对 (malloc-compatible) 分配器使用 libumem
        #[link(name = "umem")]
        extern "C" {}
    } else if #[cfg(target_os = "macos")] {
        #[link(name = "System")]
        // res_init 和朋友需要在 macOS/iOS 上使用 -lresolv。
        // 请参见 #41582 和 https://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
        #[link(name = "resolv")]
        extern "C" {}
    } else if #[cfg(target_os = "ios")] {
        #[link(name = "System")]
        #[link(name = "objc")]
        #[link(name = "Security", kind = "framework")]
        #[link(name = "Foundation", kind = "framework")]
        #[link(name = "resolv")]
        extern "C" {}
    } else if #[cfg(target_os = "fuchsia")] {
        #[link(name = "zircon")]
        #[link(name = "fdio")]
        extern "C" {}
    } else if #[cfg(all(target_os = "linux", target_env = "uclibc"))] {
        #[link(name = "dl")]
        extern "C" {}
    }
}

#[cfg(target_os = "espidf")]
mod unsupported {
    use crate::io;

    pub fn unsupported<T>() -> io::Result<T> {
        Err(unsupported_err())
    }

    pub fn unsupported_err() -> io::Error {
        io::Error::new_const(
            io::ErrorKind::Unsupported,
            &"operation not supported on this platform",
        )
    }
}