Debian Codegraph @

debian/rust-vendor/mio/src/sys/wasip1/mod.rs

raw
1 //! # Notes
2 //!
3 //! The current implementation is somewhat limited. The `Waker` is not
4 //! implemented, as at the time of writing there is no way to support to wake-up
5 //! a thread from calling `poll_oneoff`.
6 //!
7 //! Furthermore the (re/de)register functions also don't work while concurrently
8 //! polling as both registering and polling requires a lock on the
9 //! `subscriptions`.
10 //!
11 //! Finally `Selector::try_clone`, required by `Registry::try_clone`, doesn't
12 //! work. However this could be implemented by use of an `Arc`.
13 //!
14 //! In summary, this only (barely) works using a single thread.
15
16 use std::cmp::min;
17 use std::io;
18 #[cfg(all(feature = "net", debug_assertions))]
19 use std::sync::atomic::{AtomicUsize, Ordering};
20 use std::sync::{Arc, Mutex};
21 use std::time::Duration;
22
23 #[cfg(feature = "net")]
24 use crate::{Interest, Token};
25
26 cfg_net! {
27 pub(crate) mod tcp {
28 use std::io;
29 use std::net::{self, SocketAddr};
30
31 pub(crate) fn accept(listener: &net::TcpListener) -> io::Result<(net::TcpStream, SocketAddr)> {
32 let (stream, addr) = listener.accept()?;
33 stream.set_nonblocking(true)?;
34 Ok((stream, addr))
35 }
36 }
37 }
38
39 /// Unique id for use as `SelectorId`.
40 #[cfg(all(debug_assertions, feature = "net"))]
41 static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
42
43 pub(crate) struct Selector {
44 #[cfg(all(debug_assertions, feature = "net"))]
45 id: usize,
46 /// Subscriptions (reads events) we're interested in.
47 subscriptions: Arc<Mutex<Vec<wasi::Subscription>>>,
48 }
49
50 impl Selector {
51 pub(crate) fn new() -> io::Result<Selector> {
52 Ok(Selector {
53 #[cfg(all(debug_assertions, feature = "net"))]
54 id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
55 subscriptions: Arc::new(Mutex::new(Vec::new())),
56 })
57 }
58
59 #[cfg(all(debug_assertions, feature = "net"))]
60 pub(crate) fn id(&self) -> usize {
61 self.id
62 }
63
64 pub(crate) fn select(&self, events: &mut Events, timeout: Option<Duration>) -> io::Result<()> {
65 events.clear();
66
67 let mut subscriptions = self.subscriptions.lock().unwrap();
68
69 // If we want to a use a timeout in the `wasi_poll_oneoff()` function
70 // we need another subscription to the list.
71 if let Some(timeout) = timeout {
72 subscriptions.push(timeout_subscription(timeout));
73 }
74
75 // `poll_oneoff` needs the same number of events as subscriptions.
76 let length = subscriptions.len();
77 events.reserve(length);
78
79 debug_assert!(events.capacity() >= length);
80 #[cfg(debug_assertions)]
81 if length == 0 {
82 warn!(
83 "calling mio::Poll::poll with empty subscriptions, this likely not what you want"
84 );
85 }
86
87 let res = unsafe { wasi::poll_oneoff(subscriptions.as_ptr(), events.as_mut_ptr(), length) };
88
89 // Remove the timeout subscription we possibly added above.
90 if timeout.is_some() {
91 let timeout_sub = subscriptions.pop();
92 debug_assert_eq!(
93 timeout_sub.unwrap().u.tag,
94 wasi::EVENTTYPE_CLOCK.raw(),
95 "failed to remove timeout subscription"
96 );
97 }
98
99 drop(subscriptions); // Unlock.
100
101 match res {
102 Ok(n_events) => {
103 // Safety: `poll_oneoff` initialises the `events` for us.
104 unsafe { events.set_len(n_events) };
105
106 // Remove the timeout event.
107 if timeout.is_some() {
108 if let Some(index) = events.iter().position(is_timeout_event) {
109 events.swap_remove(index);
110 }
111 }
112
113 check_errors(&events)
114 }
115 Err(err) => Err(io_err(err)),
116 }
117 }
118
119 pub(crate) fn try_clone(&self) -> io::Result<Selector> {
120 Ok(Selector {
121 #[cfg(all(debug_assertions, feature = "net"))]
122 id: self.id,
123 subscriptions: self.subscriptions.clone(),
124 })
125 }
126
127 cfg_io_source! {
128 pub(crate) fn register(
129 &self,
130 fd: wasi::Fd,
131 token: Token,
132 interests: Interest,
133 ) -> io::Result<()> {
134 let mut subscriptions = self.subscriptions.lock().unwrap();
135
136 if interests.is_writable() {
137 let subscription = wasi::Subscription {
138 userdata: token.0 as wasi::Userdata,
139 u: wasi::SubscriptionU {
140 tag: wasi::EVENTTYPE_FD_WRITE.raw(),
141 u: wasi::SubscriptionUU {
142 fd_write: wasi::SubscriptionFdReadwrite {
143 file_descriptor: fd,
144 },
145 },
146 },
147 };
148 subscriptions.push(subscription);
149 }
150
151 if interests.is_readable() {
152 let subscription = wasi::Subscription {
153 userdata: token.0 as wasi::Userdata,
154 u: wasi::SubscriptionU {
155 tag: wasi::EVENTTYPE_FD_READ.raw(),
156 u: wasi::SubscriptionUU {
157 fd_read: wasi::SubscriptionFdReadwrite {
158 file_descriptor: fd,
159 },
160 },
161 },
162 };
163 subscriptions.push(subscription);
164 }
165
166 Ok(())
167 }
168
169 pub(crate) fn reregister(
170 &self,
171 fd: wasi::Fd,
172 token: Token,
173 interests: Interest,
174 ) -> io::Result<()> {
175 self.deregister(fd)
176 .and_then(|()| self.register(fd, token, interests))
177 }
178
179 pub(crate) fn deregister(&self, fd: wasi::Fd) -> io::Result<()> {
180 let mut subscriptions = self.subscriptions.lock().unwrap();
181
182 let predicate = |subscription: &wasi::Subscription| {
183 // Safety: `subscription.u.tag` defines the type of the union in
184 // `subscription.u.u`.
185 match subscription.u.tag {
186 t if t == wasi::EVENTTYPE_FD_WRITE.raw() => unsafe {
187 subscription.u.u.fd_write.file_descriptor == fd
188 },
189 t if t == wasi::EVENTTYPE_FD_READ.raw() => unsafe {
190 subscription.u.u.fd_read.file_descriptor == fd
191 },
192 _ => false,
193 }
194 };
195
196 let mut ret = Err(io::ErrorKind::NotFound.into());
197
198 while let Some(index) = subscriptions.iter().position(predicate) {
199 subscriptions.swap_remove(index);
200 ret = Ok(())
201 }
202
203 ret
204 }
205 }
206 }
207
208 /// Token used to a add a timeout subscription, also used in removing it again.
209 const TIMEOUT_TOKEN: wasi::Userdata = wasi::Userdata::MAX;
210
211 /// Returns a `wasi::Subscription` for `timeout`.
212 fn timeout_subscription(timeout: Duration) -> wasi::Subscription {
213 wasi::Subscription {
214 userdata: TIMEOUT_TOKEN,
215 u: wasi::SubscriptionU {
216 tag: wasi::EVENTTYPE_CLOCK.raw(),
217 u: wasi::SubscriptionUU {
218 clock: wasi::SubscriptionClock {
219 id: wasi::CLOCKID_MONOTONIC,
220 // Timestamp is in nanoseconds.
221 timeout: min(wasi::Timestamp::MAX as u128, timeout.as_nanos())
222 as wasi::Timestamp,
223 // Give the implementation another millisecond to coalesce
224 // events.
225 precision: Duration::from_millis(1).as_nanos() as wasi::Timestamp,
226 // Zero means the `timeout` is considered relative to the
227 // current time.
228 flags: 0,
229 },
230 },
231 },
232 }
233 }
234
235 fn is_timeout_event(event: &wasi::Event) -> bool {
236 event.type_ == wasi::EVENTTYPE_CLOCK && event.userdata == TIMEOUT_TOKEN
237 }
238
239 /// Check all events for possible errors, it returns the first error found.
240 fn check_errors(events: &[Event]) -> io::Result<()> {
241 for event in events {
242 if event.error != wasi::ERRNO_SUCCESS {
243 return Err(io_err(event.error));
244 }
245 }
246 Ok(())
247 }
248
249 /// Convert `wasi::Errno` into an `io::Error`.
250 fn io_err(errno: wasi::Errno) -> io::Error {
251 // TODO: check if this is valid.
252 io::Error::from_raw_os_error(errno.raw() as i32)
253 }
254
255 pub(crate) type Events = Vec<Event>;
256
257 pub(crate) type Event = wasi::Event;
258
259 pub(crate) mod event {
260 use std::fmt;
261
262 use crate::sys::Event;
263 use crate::Token;
264
265 pub(crate) fn token(event: &Event) -> Token {
266 Token(event.userdata as usize)
267 }
268
269 pub(crate) fn is_readable(event: &Event) -> bool {
270 event.type_ == wasi::EVENTTYPE_FD_READ
271 }
272
273 pub(crate) fn is_writable(event: &Event) -> bool {
274 event.type_ == wasi::EVENTTYPE_FD_WRITE
275 }
276
277 pub(crate) fn is_error(_: &Event) -> bool {
278 // Not supported? It could be that `wasi::Event.error` could be used for
279 // this, but the docs say `error that occurred while processing the
280 // subscription request`, so it's checked in `Select::select` already.
281 false
282 }
283
284 pub(crate) fn is_read_closed(event: &Event) -> bool {
285 event.type_ == wasi::EVENTTYPE_FD_READ
286 // Safety: checked the type of the union above.
287 && (event.fd_readwrite.flags & wasi::EVENTRWFLAGS_FD_READWRITE_HANGUP) != 0
288 }
289
290 pub(crate) fn is_write_closed(event: &Event) -> bool {
291 event.type_ == wasi::EVENTTYPE_FD_WRITE
292 // Safety: checked the type of the union above.
293 && (event.fd_readwrite.flags & wasi::EVENTRWFLAGS_FD_READWRITE_HANGUP) != 0
294 }
295
296 pub(crate) fn is_priority(_: &Event) -> bool {
297 // Not supported.
298 false
299 }
300
301 pub(crate) fn is_aio(_: &Event) -> bool {
302 // Not supported.
303 false
304 }
305
306 pub(crate) fn is_lio(_: &Event) -> bool {
307 // Not supported.
308 false
309 }
310
311 pub(crate) fn debug_details(f: &mut fmt::Formatter<'_>, event: &Event) -> fmt::Result {
312 debug_detail!(
313 TypeDetails(wasi::Eventtype),
314 PartialEq::eq,
315 wasi::EVENTTYPE_CLOCK,
316 wasi::EVENTTYPE_FD_READ,
317 wasi::EVENTTYPE_FD_WRITE,
318 );
319
320 #[allow(clippy::trivially_copy_pass_by_ref)]
321 fn check_flag(got: &wasi::Eventrwflags, want: &wasi::Eventrwflags) -> bool {
322 (got & want) != 0
323 }
324 debug_detail!(
325 EventrwflagsDetails(wasi::Eventrwflags),
326 check_flag,
327 wasi::EVENTRWFLAGS_FD_READWRITE_HANGUP,
328 );
329
330 struct EventFdReadwriteDetails(wasi::EventFdReadwrite);
331
332 impl fmt::Debug for EventFdReadwriteDetails {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.debug_struct("EventFdReadwrite")
335 .field("nbytes", &self.0.nbytes)
336 .field("flags", &EventrwflagsDetails(self.0.flags))
337 .finish()
338 }
339 }
340
341 f.debug_struct("Event")
342 .field("userdata", &event.userdata)
343 .field("error", &event.error)
344 .field("type", &TypeDetails(event.type_))
345 .field("fd_readwrite", &EventFdReadwriteDetails(event.fd_readwrite))
346 .finish()
347 }
348 }
349
350 cfg_os_poll! {
351 cfg_io_source! {
352 pub(crate) struct IoSourceState;
353
354 impl IoSourceState {
355 pub(crate) fn new() -> IoSourceState {
356 IoSourceState
357 }
358
359 pub(crate) fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R>
360 where
361 F: FnOnce(&T) -> io::Result<R>,
362 {
363 // We don't hold state, so we can just call the function and
364 // return.
365 f(io)
366 }
367 }
368 }
369 }