Skip to main content

miri/shims/unix/
udp_socket.rs

1use std::cell::{Cell, RefCell, RefMut};
2use std::io;
3use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
4use std::time::Duration;
5
6use mio::event::Source;
7use rustc_target::spec::Os;
8
9use crate::shims::files::{EvalContextExt as _, FileDescription, FileDescriptionRef};
10use crate::shims::unix::UnixFileDescription;
11use crate::shims::unix::socket::{
12    EvalContextExt, UnixSocketFileDescription, socket_action_deadline,
13};
14use crate::*;
15
16#[derive(Debug)]
17pub(super) struct UdpSocket {
18    /// Family of the socket, used to ensure that the socket only binds/connects to addresses
19    /// of the same family.
20    family: socket2::Domain,
21    /// The underlying host socket.
22    socket: RefCell<mio::net::UdpSocket>,
23    /// Whether this fd is non-blocking or not.
24    is_non_block: Cell<bool>,
25    /// Whether the socket is implicitly or explicitly bound to an address.
26    is_bound: Cell<bool>,
27    /// Whether a default destination address has been set for this socket.
28    has_default_destination: Cell<bool>,
29    /// The current blocking I/O readiness of the file description.
30    io_readiness: RefCell<Readiness>,
31    /// Read timeout of the socket. [`None`] means that reads can block indefinitely.
32    /// The timeout is applied to the monotonic clock (the Unix specification doesn't
33    /// specify which clock to use, but the monotonic clock is more common for
34    /// relative timeouts).
35    /// This is ignored when the socket is non-blocking.
36    read_timeout: Cell<Option<Duration>>,
37    /// Write timeout of the socket. [`None`] means that writes can block indefinitely.
38    /// The timeout is applied to the monotonic clock (the Unix specification doesn't
39    /// specify which clock to use, but the monotonic clock is more common
40    /// for relative timeouts).
41    /// This is ignored when the socket is non-blocking.
42    write_timeout: Cell<Option<Duration>>,
43    /// State for being watched by epoll.
44    watched: ReadinessWatched,
45}
46
47impl UdpSocket {
48    pub fn new<'tcx>(
49        family: socket2::Domain,
50        is_non_block: bool,
51        ecx: &mut MiriInterpCx<'tcx>,
52    ) -> io::Result<FileDescriptionRef<Self>> {
53        let socket =
54            socket2::Socket::new(family, socket2::Type::DGRAM, Some(socket2::Protocol::UDP))?;
55        // The underlying host socket needs to be non-blocking. The actual
56        // blocking mode of the socket is stored in `is_non_block`.
57        socket.set_nonblocking(true)?;
58
59        let socket = cfg_select! {
60            // Turn the `socket2::Socket` into a `mio::UdpSocket`. We cannot construct the
61            // mio socket directly, since its only constructor is `UdpSocket::bind`.
62            unix => {{
63                use std::os::fd::OwnedFd;
64                mio::net::UdpSocket::from(OwnedFd::from(socket))
65            }},
66            windows => {{
67                use std::os::windows::io::OwnedSocket;
68                mio::net::UdpSocket::from(OwnedSocket::from(socket))
69            }},
70            _ => unreachable!("unsupported host platform"),
71        };
72
73        let udp_socket = UdpSocket {
74            family,
75            socket: RefCell::new(socket),
76            is_non_block: Cell::new(is_non_block),
77            is_bound: Cell::new(false),
78            has_default_destination: Cell::new(false),
79            // We can set the default readiness to the empty readiness
80            // since the socket will be registered to the blocking I/O
81            // directly after its creation.
82            io_readiness: RefCell::new(Readiness::EMPTY),
83            read_timeout: Cell::new(None),
84            write_timeout: Cell::new(None),
85            watched: ReadinessWatched::default(),
86        };
87
88        let fd = ecx.machine.fds.new_ref(udp_socket);
89
90        // Add the UDP socket to the blocking I/O manager as it's always
91        // backed by a mio UdpSocket.
92        ecx.machine.blocking_io.register(fd.clone());
93
94        Ok(fd)
95    }
96}
97
98impl FileDescription for UdpSocket {
99    fn name(&self) -> &'static str {
100        "udp socket"
101    }
102
103    fn read<'tcx>(
104        self: FileDescriptionRef<Self>,
105        communicate_allowed: bool,
106        ptr: Pointer,
107        len: u64,
108        ecx: &mut MiriInterpCx<'tcx>,
109        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
110    ) -> InterpResult<'tcx> {
111        self.recv(
112            communicate_allowed,
113            ptr,
114            len,
115            /* is_peek */ false,
116            /* is_non_block */ false,
117            ecx,
118            callback!(
119                @capture<'tcx> {
120                    finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
121                } |ecx, result: Result<(u64, Option<SocketAddr>), IoError>| {
122                    finish.call(ecx, result.map(|(bytes, _)| bytes))
123                }
124            ),
125        )
126    }
127
128    fn write<'tcx>(
129        self: FileDescriptionRef<Self>,
130        communicate_allowed: bool,
131        ptr: Pointer,
132        len: u64,
133        ecx: &mut MiriInterpCx<'tcx>,
134        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
135    ) -> InterpResult<'tcx> {
136        self.send(
137            communicate_allowed,
138            ptr,
139            len,
140            /* is_non_block */ false,
141            /* dest_addr */ None,
142            ecx,
143            finish,
144        )
145    }
146
147    fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
148        self
149    }
150
151    fn readiness_watched(&self) -> Option<&ReadinessWatched> {
152        Some(&self.watched)
153    }
154
155    fn readiness(&self) -> Readiness {
156        *self.io_readiness.borrow()
157    }
158}
159
160impl UnixFileDescription for UdpSocket {
161    fn get_flags<'tcx>(&self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
162        let mut flags = ecx.eval_libc_i32("O_RDWR");
163
164        if self.is_non_block.get() {
165            flags |= ecx.eval_libc_i32("O_NONBLOCK");
166        }
167
168        interp_ok(Scalar::from_i32(flags))
169    }
170
171    fn set_flags<'tcx>(
172        &self,
173        mut flag: i32,
174        ecx: &mut MiriInterpCx<'tcx>,
175    ) -> InterpResult<'tcx, Scalar> {
176        let o_nonblock = ecx.eval_libc_i32("O_NONBLOCK");
177
178        // O_NONBLOCK flag can be set / unset by user.
179        if flag & o_nonblock == o_nonblock {
180            self.is_non_block.set(true);
181            flag &= !o_nonblock;
182        } else {
183            self.is_non_block.set(false);
184        }
185
186        // Throw error if there is any unsupported flag.
187        if flag != 0 {
188            throw_unsup_format!("fcntl: only O_NONBLOCK is supported for sockets")
189        }
190
191        interp_ok(Scalar::from_i32(0))
192    }
193
194    fn as_socket(
195        self: FileDescriptionRef<Self>,
196    ) -> Option<FileDescriptionRef<dyn UnixSocketFileDescription>> {
197        Some(self)
198    }
199}
200
201impl UnixSocketFileDescription for UdpSocket {
202    fn bind<'tcx>(
203        self: FileDescriptionRef<Self>,
204        communicate_allowed: bool,
205        address: SocketAddr,
206        ecx: &mut MiriInterpCx<'tcx>,
207    ) -> InterpResult<'tcx, Result<(), IoError>> {
208        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
209
210        let address_family = match &address {
211            SocketAddr::V4(_) => socket2::Domain::IPV4,
212            SocketAddr::V6(_) => socket2::Domain::IPV6,
213        };
214
215        if self.family != address_family {
216            // Attempted to bind an address from a family that doesn't match
217            // the family of the socket.
218            let err = if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::MacOs) {
219                // Linux man page states that `EINVAL` is used when there is an address family mismatch.
220                // See <https://man7.org/linux/man-pages/man2/bind.2.html>
221                // macOS also returns `EINVAL` but their man page does not specify this.
222                LibcError("EINVAL")
223            } else {
224                // POSIX man page states that `EAFNOSUPPORT` should be used when there is an address
225                // family mismatch.
226                // See <https://man7.org/linux/man-pages/man3/bind.3p.html>
227                LibcError("EAFNOSUPPORT")
228            };
229            return interp_ok(Err(err));
230        }
231
232        // `bind` is a non-blocking operation for UDP sockets.
233        if let Err(e) = self.with_socket_ref(|s| s.bind(&socket2::SockAddr::from(address))).unwrap()
234        {
235            return interp_ok(Err(IoError::HostError(e)));
236        }
237
238        // The socket has been explicitly bound to a local address.
239        self.is_bound.set(true);
240
241        interp_ok(Ok(()))
242    }
243
244    fn connect<'tcx>(
245        self: FileDescriptionRef<Self>,
246        communicate_allowed: bool,
247        address: SocketAddr,
248        ecx: &mut MiriInterpCx<'tcx>,
249        finish: DynMachineCallback<'tcx, Result<(), IoError>>,
250    ) -> InterpResult<'tcx> {
251        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
252
253        if self.has_default_destination.get() {
254            // POSIX is very vague about whether it's allowed to set the default destination address
255            // of a non-connection-mode socket multiple times. Some platforms support it while others don't.
256            // We thus only allow setting the destination address at most once.
257            // See <https://github.com/rust-lang/miri/pull/5507#issuecomment-6779828795>
258            throw_unsup_format!("calling `connect` a second time on a UDP socket is unsupported");
259        }
260
261        if let Err(e) = self.socket.borrow().connect(address) {
262            return finish.call(ecx, Err(IoError::HostError(e)));
263        }
264
265        // POSIX specifies that unbound sockets get bound to an unassigned
266        // local address after `connect` has been invoked on them.
267        // We thus treat the socket as implicitly bound.
268        self.is_bound.set(true);
269
270        self.has_default_destination.set(true);
271
272        finish.call(ecx, Ok(()))
273    }
274
275    fn send<'tcx>(
276        self: FileDescriptionRef<Self>,
277        communicate_allowed: bool,
278        ptr: Pointer,
279        len: u64,
280        is_non_block: bool,
281        dest_addr: Option<SocketAddr>,
282        ecx: &mut MiriInterpCx<'tcx>,
283        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
284    ) -> InterpResult<'tcx> {
285        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
286
287        let is_non_block = is_non_block || self.is_non_block.get();
288
289        if is_non_block {
290            // We have a non-blocking operation or a non-blocking socket and
291            // thus don't want to block until we can send.
292            let result = ecx.try_non_block_send(&self, ptr, len, dest_addr)?;
293            finish.call(ecx, result)
294        } else {
295            let deadline = socket_action_deadline(ecx, is_non_block, self.write_timeout.get());
296
297            // The socket is in blocking mode and thus the send call should block
298            // until we can send some bytes into the socket or the timeout exceeded.
299            ecx.block_for_send(self, deadline, ptr, len, dest_addr, finish)
300        }
301    }
302
303    fn recv<'tcx>(
304        self: FileDescriptionRef<Self>,
305        communicate_allowed: bool,
306        ptr: Pointer,
307        len: u64,
308        is_peek: bool,
309        is_non_block: bool,
310        ecx: &mut MiriInterpCx<'tcx>,
311        finish: DynMachineCallback<'tcx, Result<(u64, Option<SocketAddr>), IoError>>,
312    ) -> InterpResult<'tcx> {
313        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
314
315        let is_non_block = is_non_block || self.is_non_block.get();
316
317        if is_non_block {
318            // We have a non-blocking operation or a non-blocking socket and
319            // thus don't want to block until we can receive.
320            let result = ecx.try_non_block_recv(&self, ptr, len, is_peek)?;
321            finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr))))
322        } else {
323            let deadline = socket_action_deadline(ecx, is_non_block, self.read_timeout.get());
324
325            // The socket is in blocking mode and thus the receive call should block
326            // until we can receive some bytes from the socket or the timeout exceeded.
327            ecx.block_for_recv(self, deadline, ptr, len, is_peek, callback!(
328                @capture<'tcx> {
329                    finish: DynMachineCallback<'tcx, Result<(u64, Option<SocketAddr>), IoError>>,
330                } |ecx, result: Result<(u64, SocketAddr), IoError>| {
331                    // For UDP sockets we always have access to the address from where the
332                    // data originated.
333                    finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr))))
334                }
335            ))
336        }
337    }
338
339    fn setsockopt<'tcx>(
340        self: FileDescriptionRef<Self>,
341        level: i32,
342        option: i32,
343        value_ptr: Pointer,
344        value_len: u64,
345        ecx: &mut MiriInterpCx<'tcx>,
346    ) -> InterpResult<'tcx, Result<(), IoError>> {
347        if level == ecx.eval_libc_i32("SOL_SOCKET") {
348            return ecx.set_generic_socket_option(option, value_ptr, value_len, self);
349        } else if level == ecx.eval_libc_i32("IPPROTO_IP") {
350            let socket = self.socket.borrow();
351            return ecx.set_ip_socket_option(
352                option,
353                value_ptr,
354                value_len,
355                socket2::SockRef::from(&*socket),
356            );
357        }
358
359        throw_unsup_format!(
360            "setsockopt: level {level:#x} is unsupported, only SOL_SOCKET and IPPROTO_IP \
361            are allowed"
362        );
363    }
364
365    fn getsockopt<'tcx>(
366        self: FileDescriptionRef<Self>,
367        level: i32,
368        option: i32,
369        ecx: &mut MiriInterpCx<'tcx>,
370    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
371        if level == ecx.eval_libc_i32("SOL_SOCKET") {
372            ecx.get_generic_socket_option(option, self)
373        } else if level == ecx.eval_libc_i32("IPPROTO_IP") {
374            let socket = self.socket.borrow();
375            ecx.get_ip_socket_option(option, socket2::SockRef::from(&*socket))
376        } else {
377            throw_unsup_format!(
378                "getsockopt: level {level:#x} is unsupported, only SOL_SOCKET and IPPROTO_IP \
379                are allowed"
380            )
381        }
382    }
383
384    fn getsockname<'tcx>(
385        self: FileDescriptionRef<Self>,
386        communicate_allowed: bool,
387        _ecx: &mut MiriInterpCx<'tcx>,
388    ) -> InterpResult<'tcx, Result<SocketAddr, IoError>> {
389        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
390
391        if !self.is_bound.get() {
392            // Since Windows returns EINVAL when invoking `getsockname` on
393            // a socket which hasn't been bound yet, we need to manually
394            // return an unspecified address here.
395
396            let address = if self.family == socket2::Domain::IPV4 {
397                SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, /* port */ 0))
398            } else {
399                SocketAddr::V6(SocketAddrV6::new(
400                    Ipv6Addr::UNSPECIFIED,
401                    /* port */ 0,
402                    /* flowinfo */ 0,
403                    /* scope_id */ 0,
404                ))
405            };
406            return interp_ok(Ok(address));
407        }
408
409        interp_ok(self.socket.borrow().local_addr().map_err(IoError::HostError))
410    }
411
412    fn getpeername<'tcx>(
413        self: FileDescriptionRef<Self>,
414        communicate_allowed: bool,
415        ecx: &mut MiriInterpCx<'tcx>,
416        finish: DynMachineCallback<'tcx, Result<SocketAddr, IoError>>,
417    ) -> InterpResult<'tcx> {
418        assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
419
420        finish.call(ecx, self.socket.borrow().peer_addr().map_err(IoError::HostError))
421    }
422
423    fn set_read_timeout<'tcx>(
424        self: FileDescriptionRef<Self>,
425        timeout: Option<Duration>,
426    ) -> InterpResult<'tcx> {
427        self.read_timeout.set(timeout);
428        interp_ok(())
429    }
430
431    fn get_read_timeout<'tcx>(
432        self: FileDescriptionRef<Self>,
433    ) -> InterpResult<'tcx, Option<Duration>> {
434        interp_ok(self.read_timeout.get())
435    }
436
437    fn set_write_timeout<'tcx>(
438        self: FileDescriptionRef<Self>,
439        timeout: Option<Duration>,
440    ) -> InterpResult<'tcx> {
441        self.write_timeout.set(timeout);
442        interp_ok(())
443    }
444
445    fn get_write_timeout<'tcx>(
446        self: FileDescriptionRef<Self>,
447    ) -> InterpResult<'tcx, Option<Duration>> {
448        interp_ok(self.write_timeout.get())
449    }
450
451    fn with_socket_ref<T>(&self, cb: impl FnOnce(socket2::SockRef<'_>) -> T) -> Result<T, ()>
452    where
453        Self: Sized,
454    {
455        let socket = self.socket.borrow();
456        Ok(cb(socket2::SockRef::from(&*socket)))
457    }
458}
459
460impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {}
461trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
462    /// Block the thread until we can send bytes into the connected socket
463    /// or an error occurred.
464    ///
465    /// This recursively calls itself should the operation still block for some reason.
466    fn block_for_send(
467        &mut self,
468        socket: FileDescriptionRef<UdpSocket>,
469        deadline: Option<Deadline>,
470        buffer_ptr: Pointer,
471        length: u64,
472        dest_addr: Option<SocketAddr>,
473        finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
474    ) -> InterpResult<'tcx> {
475        let ecx = self.eval_context_mut();
476        // Since the callback holds a strong reference to the socket, the file description
477        // won't be closed as long as some thread is blocked on it. While this reflects
478        // what Linux does, for other Unix systems this might differ from the native behavior.
479        ecx.block_thread_for_io(
480            socket.clone(),
481            BlockingIoInterest::Write,
482            deadline.clone(),
483            callback!(@capture<'tcx> {
484                socket: FileDescriptionRef<UdpSocket>,
485                deadline: Option<Deadline>,
486                buffer_ptr: Pointer,
487                length: u64,
488                dest_addr: Option<SocketAddr>,
489                finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
490            } |ecx, kind: UnblockKind| {
491                // Remove the blocking I/O interest for unblocking this thread.
492                ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread());
493
494                match kind {
495                    UnblockKind::Ready => { /* fall-through to below */ },
496                    // When the write timeout is exceeded EAGAIN/EWOULDBLOCK is returned.
497                    UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK")))
498                }
499
500                match ecx.try_non_block_send(&socket, buffer_ptr, length, dest_addr)? {
501                    Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => {
502                        // We need to block the thread again as it would still block.
503                        ecx.block_for_send(socket, deadline, buffer_ptr, length, dest_addr, finish)
504                    },
505                    result => finish.call(ecx, result)
506                }
507            }),
508        )
509    }
510
511    /// Attempt to send bytes to another socket. If `dest_addr` is [`Some`], the data
512    /// is sent to the address specified in `dest_addr`. Otherwise, the data is sent
513    /// to the default destination address.
514    fn try_non_block_send(
515        &mut self,
516        socket: &FileDescriptionRef<UdpSocket>,
517        buffer_ptr: Pointer,
518        length: u64,
519        dest_addr: Option<SocketAddr>,
520    ) -> InterpResult<'tcx, Result<u64, IoError>> {
521        let ecx = self.eval_context_mut();
522
523        let host_socket = socket.socket.borrow();
524
525        if dest_addr.is_some() && socket.has_default_destination.get() {
526            // The sendto POSIX man page specifies that "[...] If a peer address has been pre-specified, either
527            // the message shall be sent to the address specified by dest_addr (overriding the pre-specified
528            // peer address), or the function shall return -1 and set errno to [EISCONN]. [...]".
529            // It turns out that Linux implements the prior option while BSD-based platforms implement the latter.
530            // Since both are allowed by POSIX, we try to model this as good as possible.
531
532            if matches!(ecx.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) {
533                // We're on a BSD target. When both `dest_addr` and a default destination address
534                // are available, those platforms return EISCONN and don't perform the operation.
535                return interp_ok(Err(LibcError("EISCONN")));
536            } else if cfg!(any(target_os = "freebsd", target_vendor = "apple")) {
537                // We're on a BSD host and on a non-BSD target. On such targets `dest_addr` should
538                // overwrite the default destination address, however, we cannot achieve this nicely
539                // since the host disallows that. We thus throw an unsupported error.
540                throw_unsup_format!(
541                    "sendto: overwriting default destination address is not supported for UDP sockets on BSD hosts"
542                )
543            }
544        }
545
546        // This is a *non-blocking* write.
547        let result = ecx.write_to_host(buffer_ptr, length, |bytes| {
548            match dest_addr {
549                Some(dest_addr) => host_socket.send_to(bytes, dest_addr),
550                None => host_socket.send(bytes),
551            }
552        })?;
553
554        if result.is_ok() {
555            // A write should never succeed when the `write_closed` readiness is set for this socket.
556            assert!(!socket.io_readiness.borrow().write_closed, "successful write after close");
557
558            if dest_addr.is_some() {
559                // After the first successful `sendto`, the socket gets implicitly bound to a local address.
560                socket.is_bound.set(true);
561            } else {
562                // Can only succeed if `connect` was called, which binds the socket.
563                assert!(socket.is_bound.get());
564            }
565        }
566
567        match result {
568            Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => {
569                // We know that the source is not writable so we need to update its readiness.
570                socket.io_readiness.borrow_mut().writable = false;
571                ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?;
572
573                interp_ok(Err(IoError::HostError(e)))
574            }
575            Err(IoError::HostError(e))
576                if cfg!(windows) && matches!(e.kind(), io::ErrorKind::NotConnected) =>
577            {
578                // Windows returns ENOTCONN instead of EDESTADDRREQ when attempting to `send` without
579                // having a default destination address set. We thus remap this error to an EDESTADDRREQ.
580                interp_ok(Err(IoError::LibcError("EDESTADDRREQ")))
581            }
582            Err(IoError::HostError(e))
583                if cfg!(windows)
584                    && e.raw_os_error().is_some_and(|errno| errno == /* WSAEMSGSIZE */ 10040) =>
585            {
586                // We attempted to write a message which doesn't fit into a single UDP datagram.
587                // On Windows hosts this returns WSAEMSGSIZE while on Unix-like hosts this returns EMSGSIZE.
588                // Since WSAEMSGSIZE doesn't map to a `io::ErrorKind`, Miri throws an unsupported error if we
589                // would just return this I/O error. We thus manually remap this error to EMSGSIZE on Windows
590                // hosts. The mapping needs to be performed here and not directly inside the callback function
591                // where the `host_socket.send` occurs since this callback function returns a result with `io::Error`
592                // instead of `IoError`.
593                // FIXME: remove this if WSAEMSGSIZE ever maps to a `io::ErrorKind`.
594                interp_ok(Err(IoError::LibcError("EMSGSIZE")))
595            }
596            result => interp_ok(result),
597        }
598    }
599
600    /// Block the thread until we can receive bytes from the socket or an error occurred.
601    ///
602    /// This recursively calls itself should the operation still block for some reason.
603    fn block_for_recv(
604        &mut self,
605        socket: FileDescriptionRef<UdpSocket>,
606        deadline: Option<Deadline>,
607        buffer_ptr: Pointer,
608        length: u64,
609        should_peek: bool,
610        finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>,
611    ) -> InterpResult<'tcx> {
612        let recv = self.eval_context_mut();
613        // Since the callback holds a strong reference to the socket, the file description
614        // won't be closed as long as some thread is blocked on it. While this reflects
615        // what Linux does, for other Unix systems this might differ from the native behavior.
616        recv.block_thread_for_io(
617            socket.clone(),
618            BlockingIoInterest::Read,
619            deadline.clone(),
620            callback!(@capture<'tcx> {
621                socket: FileDescriptionRef<UdpSocket>,
622                deadline: Option<Deadline>,
623                buffer_ptr: Pointer,
624                length: u64,
625                should_peek: bool,
626                finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>,
627            } |ecx, kind: UnblockKind| {
628                // Remove the blocking I/O interest for unblocking this thread.
629                ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread());
630
631                match kind {
632                    UnblockKind::Ready => { /* fall-through to below */ },
633                    // When the read timeout is exceeded EAGAIN/EWOULDBLOCK is returned.
634                    UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK")))
635                }
636
637                match ecx.try_non_block_recv(&socket, buffer_ptr, length, should_peek)? {
638                    Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => {
639                        // We need to block the thread again as it would still block.
640                        ecx.block_for_recv(socket, deadline, buffer_ptr, length, should_peek, finish)
641                    },
642                    result => finish.call(ecx, result)
643                }
644            }),
645        )
646    }
647
648    /// Attempt to receive bytes from the socket in a non-blocking manner.
649    fn try_non_block_recv(
650        &mut self,
651        socket: &FileDescriptionRef<UdpSocket>,
652        buffer_ptr: Pointer,
653        length: u64,
654        should_peek: bool,
655    ) -> InterpResult<'tcx, Result<(u64, SocketAddr), IoError>> {
656        let ecx = self.eval_context_mut();
657
658        let host_socket = socket.socket.borrow();
659
660        // If the `read_from_host` below succeeds, this contains the address from where
661        // the data originated. Otherwise, this is `None`.
662        let mut origin_addr = None;
663
664        let mut recv_from_host_socket = |buf: &mut [u8]| {
665            let result =
666                if should_peek { host_socket.peek_from(buf) } else { host_socket.recv_from(buf) };
667
668            result.map(|(bytes, addr)| {
669                // Store the origin address in `origin_addr`. We need to do this since
670                // `read_from_host` expects the callback to return `io::Result<usize>`.
671                origin_addr.replace(addr);
672
673                // Return the amount of bytes received.
674                bytes
675            })
676        };
677
678        // This is a *non-blocking* read/peek.
679        let result = ecx.read_from_host(buffer_ptr, length, |buf| {
680            if cfg!(windows) {
681                // When trying to read a message from the socket which does not fit our
682                // provided buffer, POSIX specifies that the provided buffer should be
683                // filled and the remaining bytes should be discarded. The receive operation
684                // should then return the amount of bytes read. Windows hosts fill the buffer
685                // and discard the excess bytes but return WSAEMSGSIZE instead of the bytes read.
686                // Since the return type of the corresponding operations in the standard library
687                // (and thus also in mio) is `io::Result<(usize, SocketAddr)>`, we essentially
688                // "lose" the address from where this data originated.
689                // To circumvent this, we use a temporary 64KiB buffer which fits any UDP
690                // datagram, receive into this temporary buffer, and then copy at most the first
691                // `length` bytes from the temporary buffer into `buf`.
692
693                #[expect(clippy::as_conversions)]
694                let mut tmp_buf = [0u8; u16::MAX as usize];
695                let result = recv_from_host_socket(&mut tmp_buf).map(|bytes| {
696                    let bytes_received = bytes.min(usize::try_from(length).unwrap());
697                    buf[..bytes_received].copy_from_slice(&tmp_buf[..bytes_received]);
698
699                    // Return the actual amount of bytes written to `buf`.
700                    bytes_received
701                });
702
703                if let Err(ref e) = result {
704                    // Since we received into a big enough temporary buffer, we should never
705                    // fail with WSAEMSGSIZE.
706                    assert_ne!(e.raw_os_error(), Some(/* WSAEMSGSIZE */ 10040))
707                }
708
709                return result;
710            }
711
712            recv_from_host_socket(buf)
713        })?;
714
715        match result {
716            Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => {
717                // We know that the source is not readable so we need to update its readiness.
718                socket.io_readiness.borrow_mut().readable = false;
719                ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?;
720
721                interp_ok(Err(IoError::HostError(e)))
722            }
723            // Since `origin_addr` is only `Some` when `result` is `Ok`, it's okay to unwrap
724            // `origin_addr` in the mapping function of `result`.
725            result => interp_ok(result.map(|bytes| (bytes, origin_addr.unwrap()))),
726        }
727    }
728}
729
730impl SourceFileDescription for UdpSocket {
731    fn with_source(&self, f: &mut dyn FnMut(&mut dyn Source) -> io::Result<()>) -> io::Result<()> {
732        let mut socket = self.socket.borrow_mut();
733        f(&mut *socket)
734    }
735
736    fn get_readiness_mut(&self) -> RefMut<'_, Readiness> {
737        self.io_readiness.borrow_mut()
738    }
739}