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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! 拥有和借用的操作系统句柄。

#![unstable(feature = "io_safety", issue = "87074")]

use super::raw::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
use crate::convert::TryFrom;
use crate::fmt;
use crate::fs;
use crate::marker::PhantomData;
use crate::mem::forget;
use crate::sys::c;
use crate::sys_common::{AsInner, FromInner, IntoInner};

/// 借来的句柄。
///
/// 它有一个生命周期参数,将它与拥有句柄的事物的生命周期联系起来。
///
/// 这使用 `repr(transparent)` 并具有主机句柄的表示形式,因此它可以在 FFI 中将句柄作为参数传递的地方使用,它不会被捕获或消耗。
///
///
/// 请注意,它*可能*具有值 `INVALID_HANDLE_VALUE` (-1),有时这是一个有效的句柄值。有关完整故事,请参见 [这个][here]。
///
/// 并且,它*可能*具有值 `NULL` (0),当控制台与进程分离或使用 `windows_subsystem` 时,可能会发生这种情况。
///
/// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
///
///
///
///
#[derive(Copy, Clone)]
#[repr(transparent)]
#[unstable(feature = "io_safety", issue = "87074")]
pub struct BorrowedHandle<'handle> {
    handle: RawHandle,
    _phantom: PhantomData<&'handle OwnedHandle>,
}

/// 拥有所有权的句柄。
///
/// 这将会丢弃时关闭句柄。
///
/// 请注意,它*可能*具有值 `INVALID_HANDLE_VALUE` (-1),有时这是一个有效的句柄值。有关完整故事,请参见 [这个][here]。
///
/// 并且,它*可能*具有值 `NULL` (0),当控制台与进程分离或使用 `windows_subsystem` 时,可能会发生这种情况。
///
///
/// `OwnedHandle` 使用 [`CloseHandle`] 在关闭时丢弃其句柄。
/// 因此,它不能与句柄一起使用来打开需要用 [`RegCloseKey`] 关闭的注册表项。
///
/// [`CloseHandle`]: https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
/// [`RegCloseKey`]: https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
///
/// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
///
///
#[unstable(feature = "io_safety", issue = "87074")]
pub struct OwnedHandle {
    handle: RawHandle,
}

/// 返回值或输出参数句柄的 FFI 类型,其中 `NULL` 用作指示错误的哨兵值,例如在 `CreateThread` 的返回值中。
/// 这使用 `repr(transparent)` 并具有主机句柄的表示,因此它可以用于此类 FFI 声明。
///
/// 您可以对 `HandleOrNull` 做的唯一有用的事情是使用其 [`TryFrom`] 实现将其转换成一个 `OwnedHandle`; 此转换负责检查 `NULL`。
/// 这可确保此类 FFI 调用在未先检查 `NULL` 的情况下无法开始使用句柄。
///
/// 此类型涉及除 `NULL` 之外的任何有效值,包括 `INVALID_HANDLE_VALUE`。
/// 这是因为使用 `NULL` 作为它的哨兵值的 API 不会将 `INVALID_HANDLE_VALUE` 视为特殊值。
///
/// 如果它持有一个有效的句柄,它将关闭 丢弃 上的句柄。
///
///
///
///
///
#[repr(transparent)]
#[unstable(feature = "io_safety", issue = "87074")]
#[derive(Debug)]
pub struct HandleOrNull(OwnedHandle);

/// 返回值或输出参数句柄的 FFI 类型,其中 `INVALID_HANDLE_VALUE` 用作哨兵值以指示错误,例如在 `CreateFileW` 的返回值中。
/// 这使用 `repr(transparent)` 并具有主机句柄的表示,因此它可以用于此类 FFI 声明。
///
/// 您可以对 `HandleOrInvalid` 做的唯一有用的事情是使用其 [`TryFrom`] 实现将其转换为 `OwnedHandle`; 此转换负责检查 `INVALID_HANDLE_VALUE`。
///
/// 这可确保此类 FFI 调用在未先检查 `INVALID_HANDLE_VALUE` 的情况下无法开始使用句柄。
///
/// 此类型涉及除 `INVALID_HANDLE_VALUE` 之外的任何有效值,包括 `NULL`。
/// 这是因为使用 `INVALID_HANDLE_VALUE` 作为它的哨兵值的 API 在 `windows_subsystem = "windows"` 或其他 I/O 设备分离的情况下可能会返回 `NULL`。
///
/// 如果它持有一个有效的句柄,它将关闭 丢弃 上的句柄。
///
///
///
///
#[repr(transparent)]
#[unstable(feature = "io_safety", issue = "87074")]
#[derive(Debug)]
pub struct HandleOrInvalid(OwnedHandle);

// Windows [`HANDLE`] 类型可以跨线程边界传输和共享 (尽管包含 `*mut void`,它通常不是 `Send` 或 `Sync`)。
//
//
// [`HANDLE`]: std::os::windows::raw::HANDLE
//
unsafe impl Send for OwnedHandle {}
unsafe impl Send for HandleOrNull {}
unsafe impl Send for HandleOrInvalid {}
unsafe impl Send for BorrowedHandle<'_> {}
unsafe impl Sync for OwnedHandle {}
unsafe impl Sync for HandleOrNull {}
unsafe impl Sync for HandleOrInvalid {}
unsafe impl Sync for BorrowedHandle<'_> {}

impl BorrowedHandle<'_> {
    /// 返回一个 `BorrowedHandle` 持有给定的原始句柄。
    ///
    /// # Safety
    ///
    /// `handle` 指向的资源必须是有效的打开句柄,它必须在返回的 `BorrowedHandle` 期间保持打开状态。
    ///
    /// 请注意,它*可能*具有值 `INVALID_HANDLE_VALUE` (-1),有时这是一个有效的句柄值。有关完整故事,请参见 [这个][here]。
    ///
    /// 并且,它*可能*具有值 `NULL` (0),当控制台与进程分离或使用 `windows_subsystem` 时,可能会发生这种情况。
    ///
    ///
    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
    ///
    ///
    #[inline]
    #[unstable(feature = "io_safety", issue = "87074")]
    pub unsafe fn borrow_raw_handle(handle: RawHandle) -> Self {
        Self { handle, _phantom: PhantomData }
    }
}

impl TryFrom<HandleOrNull> for OwnedHandle {
    type Error = ();

    #[inline]
    fn try_from(handle_or_null: HandleOrNull) -> Result<Self, ()> {
        let owned_handle = handle_or_null.0;
        if owned_handle.handle.is_null() { Err(()) } else { Ok(owned_handle) }
    }
}

impl TryFrom<HandleOrInvalid> for OwnedHandle {
    type Error = ();

    #[inline]
    fn try_from(handle_or_invalid: HandleOrInvalid) -> Result<Self, ()> {
        let owned_handle = handle_or_invalid.0;
        if owned_handle.handle == c::INVALID_HANDLE_VALUE { Err(()) } else { Ok(owned_handle) }
    }
}

impl AsRawHandle for BorrowedHandle<'_> {
    #[inline]
    fn as_raw_handle(&self) -> RawHandle {
        self.handle
    }
}

impl AsRawHandle for OwnedHandle {
    #[inline]
    fn as_raw_handle(&self) -> RawHandle {
        self.handle
    }
}

impl IntoRawHandle for OwnedHandle {
    #[inline]
    fn into_raw_handle(self) -> RawHandle {
        let handle = self.handle;
        forget(self);
        handle
    }
}

impl FromRawHandle for OwnedHandle {
    /// 从给定的原始句柄构造 `Self` 的新实例。
    ///
    /// # Safety
    ///
    /// `handle` 指向的资源必须是开放的并且适合承担所有权。
    /// 除了 `CloseHandle` 之外,资源不得需要任何清理。
    ///
    /// 特别是,它不能与句柄一起使用来打开需要用 [`RegCloseKey`] 关闭的注册表项。
    ///
    ///
    /// 请注意,它*可能*具有值 `INVALID_HANDLE_VALUE` (-1),有时这是一个有效的句柄值。
    /// 有关完整故事,请参见 [这个][here]。
    ///
    /// [`RegCloseKey`]: https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
    ///
    #[inline]
    unsafe fn from_raw_handle(handle: RawHandle) -> Self {
        Self { handle }
    }
}

impl FromRawHandle for HandleOrNull {
    /// 根据从 Windows API 返回的给定 `RawHandle` 构造一个新的 `Self` 实例,该 API 使用 null 表示失败,例如 `CreateThread`。
    ///
    ///
    /// 对于使用 `INVALID_HANDLE_VALUE` 指示失败的 API,使用 `HandleOrInvalid` 而不是 `HandleOrNull`。
    ///
    /// # Safety
    ///
    /// `handle` 指向的资源必须是打开的,否则是 unowned,或者为 null。请注意,并非所有 Windows API 都使用 null 表示错误;
    /// 有关完整故事,请参见 [这个][here]。
    ///
    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
    ///
    ///
    ///
    #[inline]
    unsafe fn from_raw_handle(handle: RawHandle) -> Self {
        Self(OwnedHandle::from_raw_handle(handle))
    }
}

impl FromRawHandle for HandleOrInvalid {
    /// 根据从 Windows API 返回的给定 `RawHandle` 构造 `Self` 的新实例,该 API 使用 `INVALID_HANDLE_VALUE` 指示失败,例如 `CreateFileW`。
    ///
    ///
    /// 对于使用 null 表示失败的 API,使用 `HandleOrNull` 而不是 `HandleOrInvalid`。
    ///
    /// # Safety
    ///
    /// `handle` 指向的资源必须是打开的,否则为 unowned、null 或等于 `INVALID_HANDLE_VALUE` (-1)。
    /// 请注意,并非所有 Windows API 都使用 `INVALID_HANDLE_VALUE` 来处理错误; 有关完整故事,请参见 [这个][here]。
    ///
    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
    ///
    ///
    ///
    ///
    #[inline]
    unsafe fn from_raw_handle(handle: RawHandle) -> Self {
        Self(OwnedHandle::from_raw_handle(handle))
    }
}

impl Drop for OwnedHandle {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            let _ = c::CloseHandle(self.handle);
        }
    }
}

impl fmt::Debug for BorrowedHandle<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BorrowedHandle").field("handle", &self.handle).finish()
    }
}

impl fmt::Debug for OwnedHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OwnedHandle").field("handle", &self.handle).finish()
    }
}

/// 从底层对象借用句柄的 trait。
#[unstable(feature = "io_safety", issue = "87074")]
pub trait AsHandle {
    /// 借用句柄。
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # #![feature(io_safety)]
    /// use std::fs::File;
    /// # use std::io;
    /// use std::os::windows::io::{AsHandle, BorrowedHandle};
    ///
    /// let mut f = File::open("foo.txt")?;
    /// let borrowed_handle: BorrowedHandle<'_> = f.as_handle();
    /// # Ok::<(), io::Error>(())
    /// ```
    fn as_handle(&self) -> BorrowedHandle<'_>;
}

impl AsHandle for BorrowedHandle<'_> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        *self
    }
}

impl AsHandle for OwnedHandle {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        // 安全性: `OwnedHandle` 和 `BorrowedHandle` 具有相同的有效性不变量,`BorrowdHandle` 受 `&self` 的生命周期限制。
        //
        //
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl AsHandle for fs::File {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        self.as_inner().as_handle()
    }
}

impl From<fs::File> for OwnedHandle {
    #[inline]
    fn from(file: fs::File) -> OwnedHandle {
        file.into_inner().into_inner().into_inner().into()
    }
}

impl From<OwnedHandle> for fs::File {
    #[inline]
    fn from(owned: OwnedHandle) -> Self {
        Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned)))
    }
}

impl AsHandle for crate::io::Stdin {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl<'a> AsHandle for crate::io::StdinLock<'a> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl AsHandle for crate::io::Stdout {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl<'a> AsHandle for crate::io::StdoutLock<'a> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl AsHandle for crate::io::Stderr {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl<'a> AsHandle for crate::io::StderrLock<'a> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl AsHandle for crate::process::ChildStdin {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl From<crate::process::ChildStdin> for OwnedHandle {
    #[inline]
    fn from(child_stdin: crate::process::ChildStdin) -> OwnedHandle {
        unsafe { OwnedHandle::from_raw_handle(child_stdin.into_raw_handle()) }
    }
}

impl AsHandle for crate::process::ChildStdout {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl From<crate::process::ChildStdout> for OwnedHandle {
    #[inline]
    fn from(child_stdout: crate::process::ChildStdout) -> OwnedHandle {
        unsafe { OwnedHandle::from_raw_handle(child_stdout.into_raw_handle()) }
    }
}

impl AsHandle for crate::process::ChildStderr {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl From<crate::process::ChildStderr> for OwnedHandle {
    #[inline]
    fn from(child_stderr: crate::process::ChildStderr) -> OwnedHandle {
        unsafe { OwnedHandle::from_raw_handle(child_stderr.into_raw_handle()) }
    }
}

impl<T> AsHandle for crate::thread::JoinHandle<T> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        unsafe { BorrowedHandle::borrow_raw_handle(self.as_raw_handle()) }
    }
}

impl<T> From<crate::thread::JoinHandle<T>> for OwnedHandle {
    #[inline]
    fn from(join_handle: crate::thread::JoinHandle<T>) -> OwnedHandle {
        join_handle.into_inner().into_handle().into_inner()
    }
}