Debian Codegraph @

src/iocp/port.rs

raw symbols SCIP
1 //! A safe wrapper around the Windows I/O API.
2
3 use super::dur2timeout;
4
5 use std::fmt;
6 use std::io;
7 use std::marker::PhantomData;
8 use std::mem::MaybeUninit;
9 use std::ops::Deref;
10 use std::os::windows::io::{AsRawHandle, RawHandle};
11 use std::pin::Pin;
12 use std::ptr;
13 use std::sync::Arc;
14 use std::time::Duration;
15
16 use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
17 use windows_sys::Win32::Storage::FileSystem::SetFileCompletionNotificationModes;
18 use windows_sys::Win32::System::Threading::INFINITE;
19 use windows_sys::Win32::System::WindowsProgramming::FILE_SKIP_SET_EVENT_ON_HANDLE;
20 use windows_sys::Win32::System::IO::{
21 CreateIoCompletionPort, GetQueuedCompletionStatusEx, PostQueuedCompletionStatus, OVERLAPPED,
22 OVERLAPPED_ENTRY,
23 };
24
25 /// A completion block which can be used with I/O completion ports.
26 ///
27 /// # Safety
28 ///
29 /// This must be a valid completion block.
30 pub(super) unsafe trait Completion {
31 /// Signal to the completion block that we are about to start an operation.
32 fn try_lock(self: Pin<&Self>) -> bool;
33
34 /// Unlock the completion block.
35 unsafe fn unlock(self: Pin<&Self>);
36 }
37
38 /// The pointer to a completion block.
39 ///
40 /// # Safety
41 ///
42 /// This must be a valid completion block.
43 pub(super) unsafe trait CompletionHandle: Deref + Sized {
44 /// Type of the completion block.
45 type Completion: Completion;
46
47 /// Get a pointer to the completion block.
48 ///
49 /// The pointer is pinned since the underlying object should not be moved
50 /// after creation. This prevents it from being invalidated while it's
51 /// used in an overlapped operation.
52 fn get(&self) -> Pin<&Self::Completion>;
53
54 /// Convert this block into a pointer that can be passed as `*mut OVERLAPPED`.
55 fn into_ptr(this: Self) -> *mut OVERLAPPED;
56
57 /// Convert a pointer that was passed as `*mut OVERLAPPED` into a pointer to this block.
58 ///
59 /// # Safety
60 ///
61 /// This must be a valid pointer to a completion block.
62 unsafe fn from_ptr(ptr: *mut OVERLAPPED) -> Self;
63
64 /// Convert to a pointer without losing ownership.
65 fn as_ptr(&self) -> *mut OVERLAPPED;
66 }
67
68 unsafe impl<T: Completion> CompletionHandle for Pin<&T> {
69 type Completion = T;
70
71 fn get(&self) -> Pin<&Self::Completion> {
72 *self
73 }
74
75 fn into_ptr(this: Self) -> *mut OVERLAPPED {
76 unsafe { Pin::into_inner_unchecked(this) as *const T as *mut OVERLAPPED }
77 }
78
79 unsafe fn from_ptr(ptr: *mut OVERLAPPED) -> Self {
80 Pin::new_unchecked(&*(ptr as *const T))
81 }
82
83 fn as_ptr(&self) -> *mut OVERLAPPED {
84 self.get_ref() as *const T as *mut OVERLAPPED
85 }
86 }
87
88 unsafe impl<T: Completion> CompletionHandle for Pin<Arc<T>> {
89 type Completion = T;
90
91 fn get(&self) -> Pin<&Self::Completion> {
92 self.as_ref()
93 }
94
95 fn into_ptr(this: Self) -> *mut OVERLAPPED {
96 unsafe { Arc::into_raw(Pin::into_inner_unchecked(this)) as *const T as *mut OVERLAPPED }
97 }
98
99 unsafe fn from_ptr(ptr: *mut OVERLAPPED) -> Self {
100 Pin::new_unchecked(Arc::from_raw(ptr as *const T))
101 }
102
103 fn as_ptr(&self) -> *mut OVERLAPPED {
104 self.as_ref().get_ref() as *const T as *mut OVERLAPPED
105 }
106 }
107
108 /// A handle to the I/O completion port.
109 pub(super) struct IoCompletionPort<T> {
110 /// The underlying handle.
111 handle: HANDLE,
112
113 /// We own the status block.
114 _marker: PhantomData<T>,
115 }
116
117 impl<T> Drop for IoCompletionPort<T> {
118 fn drop(&mut self) {
119 unsafe {
120 CloseHandle(self.handle);
121 }
122 }
123 }
124
125 impl<T> AsRawHandle for IoCompletionPort<T> {
126 fn as_raw_handle(&self) -> RawHandle {
127 self.handle as _
128 }
129 }
130
131 impl<T> fmt::Debug for IoCompletionPort<T> {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 struct WriteAsHex(HANDLE);
134
135 impl fmt::Debug for WriteAsHex {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 write!(f, "{:010x}", self.0 as usize)
138 }
139 }
140
141 f.debug_struct("IoCompletionPort")
142 .field("handle", &WriteAsHex(self.handle))
143 .finish()
144 }
145 }
146
147 impl<T: CompletionHandle> IoCompletionPort<T> {
148 /// Create a new I/O completion port.
149 pub(super) fn new(threads: usize) -> io::Result<Self> {
150 let handle = unsafe {
151 CreateIoCompletionPort(
152 INVALID_HANDLE_VALUE,
153 ptr::null_mut(),
154 0,
155 threads.try_into().expect("too many threads"),
156 )
157 };
158
159 if handle.is_null() {
160 Err(io::Error::last_os_error())
161 } else {
162 Ok(Self {
163 handle,
164 _marker: PhantomData,
165 })
166 }
167 }
168
169 /// Register a handle with this I/O completion port.
170 pub(super) fn register(
171 &self,
172 handle: &impl AsRawHandle, // TODO change to AsHandle
173 skip_set_event_on_handle: bool,
174 ) -> io::Result<()> {
175 let handle = handle.as_raw_handle();
176
177 let result =
178 unsafe { CreateIoCompletionPort(handle as _, self.handle, handle as usize, 0) };
179
180 if result.is_null() {
181 return Err(io::Error::last_os_error());
182 }
183
184 if skip_set_event_on_handle {
185 // Set the skip event on handle.
186 let result = unsafe {
187 SetFileCompletionNotificationModes(handle as _, FILE_SKIP_SET_EVENT_ON_HANDLE as _)
188 };
189
190 if result == 0 {
191 return Err(io::Error::last_os_error());
192 }
193 }
194
195 Ok(())
196 }
197
198 /// Post a completion packet to this port.
199 pub(super) fn post(&self, bytes_transferred: usize, id: usize, packet: T) -> io::Result<()> {
200 let result = unsafe {
201 PostQueuedCompletionStatus(
202 self.handle,
203 bytes_transferred
204 .try_into()
205 .expect("too many bytes transferred"),
206 id,
207 T::into_ptr(packet),
208 )
209 };
210
211 if result == 0 {
212 Err(io::Error::last_os_error())
213 } else {
214 Ok(())
215 }
216 }
217
218 /// Wait for completion packets to arrive.
219 pub(super) fn wait(
220 &self,
221 packets: &mut Vec<OverlappedEntry<T>>,
222 timeout: Option<Duration>,
223 ) -> io::Result<usize> {
224 // Drop the current packets.
225 packets.clear();
226
227 let mut count = MaybeUninit::<u32>::uninit();
228 let timeout = timeout.map_or(INFINITE, dur2timeout);
229
230 let result = unsafe {
231 GetQueuedCompletionStatusEx(
232 self.handle,
233 packets.as_mut_ptr() as _,
234 packets.capacity().try_into().expect("too many packets"),
235 count.as_mut_ptr(),
236 timeout,
237 0,
238 )
239 };
240
241 if result == 0 {
242 let io_error = io::Error::last_os_error();
243 if io_error.kind() == io::ErrorKind::TimedOut {
244 Ok(0)
245 } else {
246 Err(io_error)
247 }
248 } else {
249 let count = unsafe { count.assume_init() };
250 unsafe {
251 packets.set_len(count as _);
252 }
253 Ok(count as _)
254 }
255 }
256 }
257
258 /// An `OVERLAPPED_ENTRY` resulting from an I/O completion port.
259 #[repr(transparent)]
260 pub(super) struct OverlappedEntry<T: CompletionHandle> {
261 /// The underlying entry.
262 entry: OVERLAPPED_ENTRY,
263
264 /// We own the status block.
265 _marker: PhantomData<T>,
266 }
267
268 impl<T: CompletionHandle> fmt::Debug for OverlappedEntry<T> {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 f.write_str("OverlappedEntry { .. }")
271 }
272 }
273
274 impl<T: CompletionHandle> OverlappedEntry<T> {
275 /// Convert into the completion packet.
276 pub(super) fn into_packet(self) -> T {
277 let packet = unsafe { self.packet() };
278 std::mem::forget(self);
279 packet
280 }
281
282 /// Get the packet reference that this entry refers to.
283 ///
284 /// # Safety
285 ///
286 /// This function should only be called once, since it moves
287 /// out the `T` from the `OVERLAPPED_ENTRY`.
288 unsafe fn packet(&self) -> T {
289 let packet = T::from_ptr(self.entry.lpOverlapped);
290 packet.get().unlock();
291 packet
292 }
293 }
294
295 impl<T: CompletionHandle> Drop for OverlappedEntry<T> {
296 fn drop(&mut self) {
297 drop(unsafe { self.packet() });
298 }
299 }