Skip to main content

miri/shims/unix/
socket.rs

1use std::io;
2use std::net::{Shutdown, SocketAddr};
3use std::time::Duration;
4
5use rustc_abi::Size;
6use rustc_target::spec::Os;
7
8use crate::shims::files::FdNum;
9use crate::shims::unix::UnixFileDescription;
10use crate::shims::unix::socket_address::EvalContextExt as _;
11use crate::shims::unix::tcp_socket::TcpSocket;
12use crate::shims::unix::udp_socket::UdpSocket;
13use crate::shims::{FileDescription, FileDescriptionRef};
14use crate::*;
15
16/// Represents unix-specific socket file descriptions.
17///
18/// Not to be confused with Unix domain sockets.
19pub trait UnixSocketFileDescription: UnixFileDescription {
20    /// Bind the socket to `address`.
21    fn bind<'tcx>(
22        self: FileDescriptionRef<Self>,
23        _communicate_allowed: bool,
24        _address: SocketAddr,
25        _ecx: &mut MiriInterpCx<'tcx>,
26    ) -> InterpResult<'tcx, Result<(), IoError>> {
27        throw_unsup_format!("cannot bind {}", self.name());
28    }
29
30    /// Start listening on the socket.
31    /// `backlog` specifies how many pending incoming connections can exist at the same
32    /// time before new requests are rejected.
33    fn listen<'tcx>(
34        self: FileDescriptionRef<Self>,
35        _communicate_allowed: bool,
36        _backlog: i32,
37        _ecx: &mut MiriInterpCx<'tcx>,
38    ) -> InterpResult<'tcx, Result<(), IoError>> {
39        throw_unsup_format!("cannot listen on {}", self.name());
40    }
41
42    /// Accept an incoming connection on the socket.
43    /// `is_client_sock_non_block` specifies whether the newly accepted client connection
44    /// should be non-blocking.
45    /// After a successful accept, `finish` should be called with a tuple containing the
46    /// file descriptor of the peer socket and it's address.
47    fn accept<'tcx>(
48        self: FileDescriptionRef<Self>,
49        _communicate_allowed: bool,
50        _is_client_sock_non_block: bool,
51        _ecx: &mut MiriInterpCx<'tcx>,
52        _finish: DynMachineCallback<'tcx, Result<(FdNum, SocketAddr), IoError>>,
53    ) -> InterpResult<'tcx> {
54        throw_unsup_format!("cannot accept {}", self.name());
55    }
56
57    /// Connect the socket to `address`.
58    fn connect<'tcx>(
59        self: FileDescriptionRef<Self>,
60        _communicate_allowed: bool,
61        _address: SocketAddr,
62        _ecx: &mut MiriInterpCx<'tcx>,
63        _finish: DynMachineCallback<'tcx, Result<(), IoError>>,
64    ) -> InterpResult<'tcx> {
65        throw_unsup_format!("cannot connect {}", self.name());
66    }
67
68    /// Receive data on the socket into the given buffer `ptr` and return the socket
69    /// address from where the data originated.
70    /// `len` indicates how many bytes we should try to receive.
71    /// `is_peek` specifies whether the receive removes the bytes from the receive buffer
72    /// ([`false`]) or leaves them in the receive buffer ([`true`]).
73    /// `is_non_block` specifies whether the receive operation is non-blocking.
74    /// After a successful receive, `finish` should be called with a tuple containing the
75    /// amount of bytes received and the socket address from where the data originated, should
76    /// it be provided by the protocol.
77    fn recv<'tcx>(
78        self: FileDescriptionRef<Self>,
79        _communicate_allowed: bool,
80        _ptr: Pointer,
81        _len: u64,
82        _is_peek: bool,
83        _is_non_block: bool,
84        _ecx: &mut MiriInterpCx<'tcx>,
85        _finish: DynMachineCallback<'tcx, Result<(u64, Option<SocketAddr>), IoError>>,
86    ) -> InterpResult<'tcx> {
87        throw_unsup_format!("cannot receive from {}", self.name());
88    }
89
90    /// Send data from the given buffer `ptr` into the socket.
91    /// `len` indicates how many bytes we should try to send.
92    /// `is_non_block` specifies whether the send operation is non-blocking.
93    /// `dest_addr` optionally contains a socket address to which the data
94    /// should be sent instead of the default destination address.
95    /// After a successful send, `finish` should be called with the amount of bytes sent.
96    fn send<'tcx>(
97        self: FileDescriptionRef<Self>,
98        _communicate_allowed: bool,
99        _ptr: Pointer,
100        _len: u64,
101        _is_non_block: bool,
102        _dest_addr: Option<SocketAddr>,
103        _ecx: &mut MiriInterpCx<'tcx>,
104        _finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
105    ) -> InterpResult<'tcx> {
106        throw_unsup_format!("cannot send to {}", self.name());
107    }
108
109    /// Set the socket option `option` on `level`.
110    /// `value_ptr` points to the new value of the socket option, and `value_len` contains
111    /// the amount of bytes the value uses at `value_ptr`.
112    fn setsockopt<'tcx>(
113        self: FileDescriptionRef<Self>,
114        _level: i32,
115        _option: i32,
116        _value_ptr: Pointer,
117        _value_len: u64,
118        _ecx: &mut MiriInterpCx<'tcx>,
119    ) -> InterpResult<'tcx, Result<(), IoError>> {
120        throw_unsup_format!("cannot set socket option on {}", self.name());
121    }
122
123    /// Get the value of a socket option `option` on `level`.
124    fn getsockopt<'tcx>(
125        self: FileDescriptionRef<Self>,
126        _level: i32,
127        _option: i32,
128        _ecx: &mut MiriInterpCx<'tcx>,
129    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
130        throw_unsup_format!("cannot get socket option for {}", self.name());
131    }
132
133    /// Get the local address of the socket.
134    fn getsockname<'tcx>(
135        self: FileDescriptionRef<Self>,
136        _communicate_allowed: bool,
137        _ecx: &mut MiriInterpCx<'tcx>,
138    ) -> InterpResult<'tcx, Result<SocketAddr, IoError>> {
139        throw_unsup_format!("cannot get socket name for {}", self.name());
140    }
141
142    /// Get the remote address of the socket.
143    fn getpeername<'tcx>(
144        self: FileDescriptionRef<Self>,
145        _communicate_allowed: bool,
146        _ecx: &mut MiriInterpCx<'tcx>,
147        _finish: DynMachineCallback<'tcx, Result<SocketAddr, IoError>>,
148    ) -> InterpResult<'tcx> {
149        throw_unsup_format!("cannot get peer name for {}", self.name());
150    }
151
152    /// Shut down the read and/or the write end of the socket.
153    fn shutdown<'tcx>(
154        self: FileDescriptionRef<Self>,
155        _communicate_allowed: bool,
156        _how: Shutdown,
157        _ecx: &mut MiriInterpCx<'tcx>,
158    ) -> InterpResult<'tcx, Result<(), IoError>> {
159        throw_unsup_format!("cannot shut down {}", self.name());
160    }
161
162    // Socket options from SOL_SOCKET which are supported by all socket kinds.
163
164    /// Set the read timeout for the socket.
165    /// If `timeout` is [`None`], then read operations should block indefinitely.
166    /// Otherwise, read operations should block until `timeout` is expired.
167    fn set_read_timeout<'tcx>(
168        self: FileDescriptionRef<Self>,
169        _timeout: Option<Duration>,
170    ) -> InterpResult<'tcx> {
171        throw_unsup_format!("setsockopt: option SO_RCVTIMEO is unsupported for {}", self.name())
172    }
173
174    /// Get the read timeout for the socket.
175    fn get_read_timeout<'tcx>(
176        self: FileDescriptionRef<Self>,
177    ) -> InterpResult<'tcx, Option<Duration>> {
178        throw_unsup_format!("getsockopt: option SO_RCVTIMEO is unsupported for {}", self.name())
179    }
180
181    /// Set the write timeout for the socket.
182    /// If `timeout` is [`None`], then write operations should block indefinitely.
183    /// Otherwise, write operations should block until `timeout` is expired.
184    fn set_write_timeout<'tcx>(
185        self: FileDescriptionRef<Self>,
186        _timeout: Option<Duration>,
187    ) -> InterpResult<'tcx> {
188        throw_unsup_format!("setsockopt: option SO_SNDTIMEO is unsupported for {}", self.name())
189    }
190
191    /// Get the write timeout for the socket.
192    fn get_write_timeout<'tcx>(
193        self: FileDescriptionRef<Self>,
194    ) -> InterpResult<'tcx, Option<Duration>> {
195        throw_unsup_format!("getsockopt: option SO_SNDTIMEO is unsupported for {}", self.name())
196    }
197
198    /// Get the stored I/O error of the socket, if any exists.
199    /// This method should consume the stored error.
200    fn take_error<'tcx>(
201        self: FileDescriptionRef<Self>,
202        _ecx: &mut MiriInterpCx<'tcx>,
203    ) -> InterpResult<'tcx, Option<io::Error>> {
204        throw_unsup_format!("getsockopt: option SO_ERROR is unsupported for {}", self.name())
205    }
206
207    /// If the shimmed socket contains an underlying host socket, the `cb` callback
208    /// function is invoked with a [`socket2::SockRef`] to the underlying host socket
209    /// and [`Ok`] with the return value of the callback is returned.
210    /// Otherwise, when the shimmed socket is not backed by a host socket, [`Err`] is
211    /// returned.
212    fn with_socket_ref<T>(&self, _cb: impl FnOnce(socket2::SockRef<'_>) -> T) -> Result<T, ()>
213    where
214        Self: Sized,
215    {
216        Err(())
217    }
218}
219
220impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
221pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
222    /// For more information on the arguments see the socket manpage:
223    /// <https://linux.die.net/man/2/socket>
224    fn socket(
225        &mut self,
226        domain: &OpTy<'tcx>,
227        type_: &OpTy<'tcx>,
228        protocol: &OpTy<'tcx>,
229    ) -> InterpResult<'tcx, Scalar> {
230        let ecx = self.eval_context_mut();
231
232        let domain = ecx.read_scalar(domain)?.to_i32()?;
233        let mut flags = ecx.read_scalar(type_)?.to_i32()?;
234        let protocol = ecx.read_scalar(protocol)?.to_i32()?;
235
236        // Reject if isolation is enabled
237        if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op {
238            ecx.reject_in_isolation("`socket`", reject_with)?;
239            return ecx.set_errno_and_return_neg1_i32(LibcError("EACCES"));
240        }
241
242        let mut is_non_block = false;
243
244        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
245        // if there is anything left at the end, that's an unsupported flag.
246        if matches!(
247            ecx.tcx.sess.target.os,
248            Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos
249        ) {
250            // SOCK_NONBLOCK and SOCK_CLOEXEC only exist on Linux, Android, FreeBSD,
251            // Solaris, and Illumos targets.
252            let sock_nonblock = ecx.eval_libc_i32("SOCK_NONBLOCK");
253            let sock_cloexec = ecx.eval_libc_i32("SOCK_CLOEXEC");
254            if flags & sock_nonblock == sock_nonblock {
255                is_non_block = true;
256                flags &= !sock_nonblock;
257            }
258            if flags & sock_cloexec == sock_cloexec {
259                // We don't support `exec` so we can ignore this.
260                flags &= !sock_cloexec;
261            }
262        }
263
264        let family = if domain == ecx.eval_libc_i32("AF_INET") {
265            socket2::Domain::IPV4
266        } else if domain == ecx.eval_libc_i32("AF_INET6") {
267            socket2::Domain::IPV6
268        } else {
269            throw_unsup_format!(
270                "socket: domain {:#x} is unsupported, only AF_INET and \
271            AF_INET6 are allowed.",
272                domain
273            );
274        };
275
276        let fd_result = if flags == ecx.eval_libc_i32("SOCK_STREAM") {
277            if ![0, ecx.eval_libc_i32("IPPROTO_TCP")].contains(&protocol) {
278                throw_unsup_format!(
279                    "socket: socket protocol {protocol} is unsupported for \
280                    streaming socket, only IPPROTO_TCP and 0 are allowed"
281                );
282            }
283
284            TcpSocket::new(family, is_non_block, ecx).map(|fd| fd.as_unix())
285        } else if flags == ecx.eval_libc_i32("SOCK_DGRAM") {
286            if ![0, ecx.eval_libc_i32("IPPROTO_UDP")].contains(&protocol) {
287                throw_unsup_format!(
288                    "socket: socket protocol {protocol} is unsupported for \
289                    datagram socket, only IPPROTO_UDP and 0 are allowed"
290                );
291            }
292
293            UdpSocket::new(family, is_non_block, ecx).map(|fd| fd.as_unix())
294        } else {
295            throw_unsup_format!(
296                "socket: type {:#x} is unsupported, only SOCK_STREAM, \
297                SOCK_DGRAM, SOCK_CLOEXEC and SOCK_NONBLOCK are allowed",
298                flags
299            );
300        };
301        let fd = match fd_result {
302            Ok(fd) => fd,
303            Err(e) => return ecx.set_errno_and_return_neg1_i32(e),
304        };
305        let Some(fd_num) = ecx.machine.fds.insert(fd) else {
306            return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE"));
307        };
308        interp_ok(Scalar::from_i32(fd_num))
309    }
310
311    fn bind(
312        &mut self,
313        socket: &OpTy<'tcx>,
314        address: &OpTy<'tcx>,
315        address_len: &OpTy<'tcx>,
316    ) -> InterpResult<'tcx, Scalar> {
317        let ecx = self.eval_context_mut();
318
319        let socket = ecx.read_scalar(socket)?.to_i32()?;
320        let address = match ecx.read_socket_address(address, address_len, "bind")? {
321            Ok(addr) => addr,
322            Err(e) => return ecx.set_errno_and_return_neg1_i32(e),
323        };
324
325        // Get the file handle
326        let Some(fd) = ecx.machine.fds.get(socket) else {
327            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
328        };
329
330        let Some(socket) = fd.as_unix().as_socket() else {
331            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
332        };
333
334        match socket.bind(ecx.machine.communicate(), address, ecx)? {
335            Ok(_) => interp_ok(Scalar::from_i32(0)),
336            Err(e) => ecx.set_errno_and_return_neg1_i32(e),
337        }
338    }
339
340    fn listen(&mut self, socket: &OpTy<'tcx>, backlog: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
341        let ecx = self.eval_context_mut();
342
343        let socket = ecx.read_scalar(socket)?.to_i32()?;
344        let backlog = ecx.read_scalar(backlog)?.to_i32()?;
345
346        // Get the file handle
347        let Some(fd) = ecx.machine.fds.get(socket) else {
348            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
349        };
350
351        let Some(socket) = fd.as_unix().as_socket() else {
352            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
353        };
354
355        match socket.listen(ecx.machine.communicate(), backlog, ecx)? {
356            Ok(_) => interp_ok(Scalar::from_i32(0)),
357            Err(e) => ecx.set_errno_and_return_neg1_i32(e),
358        }
359    }
360
361    /// For more information on the arguments see the accept manpage:
362    /// <https://linux.die.net/man/2/accept4>
363    fn accept4(
364        &mut self,
365        socket: &OpTy<'tcx>,
366        address: &OpTy<'tcx>,
367        address_len: &OpTy<'tcx>,
368        flags: Option<&OpTy<'tcx>>,
369        // Location where the output scalar is written to.
370        dest: &MPlaceTy<'tcx>,
371    ) -> InterpResult<'tcx> {
372        let ecx = self.eval_context_mut();
373
374        let socket = ecx.read_scalar(socket)?.to_i32()?;
375        let address_ptr = ecx.read_pointer(address)?;
376        let address_len_place = ecx.deref_pointer(address_len)?;
377        let mut flags =
378            if let Some(flags) = flags { ecx.read_scalar(flags)?.to_i32()? } else { 0 };
379
380        // Get the file handle
381        let Some(fd) = ecx.machine.fds.get(socket) else {
382            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
383        };
384
385        let Some(socket) = fd.as_unix().as_socket() else {
386            return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest);
387        };
388
389        let mut is_client_sock_nonblock = false;
390
391        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
392        // if there is anything left at the end, that's an unsupported flag.
393        if matches!(
394            ecx.tcx.sess.target.os,
395            Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos
396        ) {
397            // SOCK_NONBLOCK and SOCK_CLOEXEC only exist on Linux, Android, FreeBSD,
398            // Solaris, and Illumos targets.
399            let sock_nonblock = ecx.eval_libc_i32("SOCK_NONBLOCK");
400            let sock_cloexec = ecx.eval_libc_i32("SOCK_CLOEXEC");
401            if flags & sock_nonblock == sock_nonblock {
402                is_client_sock_nonblock = true;
403                flags &= !sock_nonblock;
404            }
405            if flags & sock_cloexec == sock_cloexec {
406                // We don't support `exec` so we can ignore this.
407                flags &= !sock_cloexec;
408            }
409        }
410
411        if flags != 0 {
412            throw_unsup_format!(
413                "accept4: flag {flags:#x} is unsupported, only SOCK_CLOEXEC \
414                and SOCK_NONBLOCK are allowed",
415            );
416        }
417
418        let dest = dest.clone();
419        socket.accept(
420            ecx.machine.communicate(),
421            is_client_sock_nonblock,
422            ecx,
423            callback!(
424                @capture<'tcx> {
425                    address_ptr: Pointer,
426                    address_len_place: MPlaceTy<'tcx>,
427                    dest: MPlaceTy<'tcx>
428                } |ecx, result: Result<(FdNum, SocketAddr), IoError>| {
429                    let (client_sockfd, address) = match result {
430                        Ok(data) => data,
431                        Err(e) => return ecx.set_errno_and_return_neg1(e, &dest),
432                    };
433
434                    if !ecx.ptr_is_null(address_ptr)? {
435                        // We only attempt a write if the address pointer is not a null pointer.
436                        // If the address pointer is a null pointer the user isn't interested in the
437                        // address and we don't need to write anything.
438                        ecx.write_socket_address(Some(&address), address_ptr, &address_len_place)?;
439                    }
440
441                    // We need to write the FD using the destination size since
442                    // `syscall(SYS_accept4, ...)` returns a long which doesn't match
443                    // the int returned from the `accept`/`accept4` syscalls.
444                    // See <https://man7.org/linux/man-pages/man2/syscall.2.html>.
445                    ecx.write_int(client_sockfd, &dest)
446                }
447            ),
448        )
449    }
450
451    fn connect(
452        &mut self,
453        socket: &OpTy<'tcx>,
454        address: &OpTy<'tcx>,
455        address_len: &OpTy<'tcx>,
456        // Location where the output scalar is written to.
457        dest: &MPlaceTy<'tcx>,
458    ) -> InterpResult<'tcx> {
459        let ecx = self.eval_context_mut();
460
461        let socket = ecx.read_scalar(socket)?.to_i32()?;
462        let address = match ecx.read_socket_address(address, address_len, "connect")? {
463            Ok(address) => address,
464            Err(e) => return ecx.set_errno_and_return_neg1(e, dest),
465        };
466
467        // Get the file handle
468        let Some(fd) = ecx.machine.fds.get(socket) else {
469            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
470        };
471
472        let Some(socket) = fd.as_unix().as_socket() else {
473            return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest);
474        };
475
476        let dest = dest.clone();
477
478        socket.connect(
479            ecx.machine.communicate(),
480            address,
481            ecx,
482            callback!(
483                @capture<'tcx> {
484                    dest: MPlaceTy<'tcx>
485                } |ecx, result: Result<(), IoError>| {
486                    ecx.return_io_result_via_errno(result.map(|()| 0), &dest)
487                }
488            ),
489        )
490    }
491
492    fn send(
493        &mut self,
494        socket: &OpTy<'tcx>,
495        buffer: &OpTy<'tcx>,
496        length: &OpTy<'tcx>,
497        flags: &OpTy<'tcx>,
498        dest_addr: Option<(&OpTy<'tcx>, &OpTy<'tcx>)>,
499        // Location where the output scalar is written to.
500        dest: &MPlaceTy<'tcx>,
501    ) -> InterpResult<'tcx> {
502        let ecx = self.eval_context_mut();
503
504        let socket = ecx.read_scalar(socket)?.to_i32()?;
505        let buffer_ptr = ecx.read_pointer(buffer)?;
506        let length = ecx.read_target_usize(length)?;
507        let mut flags = ecx.read_scalar(flags)?.to_i32()?;
508
509        let dest_addr = match dest_addr {
510            Some((dest_addr, dest_addr_len)) => {
511                let dest_addr_ptr = ecx.read_pointer(dest_addr)?;
512                let dest_addr_len_int = ecx.read_int::<u64>(dest_addr_len)?;
513
514                // POSIX says the destination is entirely ignored for TCP sockets, but that does not
515                // match reality, so we eagerly read the destination when one is given.
516                if ecx.ptr_is_null(dest_addr_ptr)? || dest_addr_len_int == 0 {
517                    // If the address pointer is a nullptr or the address length is zero we ignore
518                    // the destination address. BSDs return EINVAL when the address length is zero
519                    // and the address pointer is an invalid pointer; that is so far away from what
520                    // POSIX documents for TCP sockets that we do not try to emulate it.
521                    None
522                } else {
523                    match ecx.read_socket_address(dest_addr, dest_addr_len, "sendto")? {
524                        Ok(dest_addr) => Some(dest_addr),
525                        Err(e) => return ecx.set_errno_and_return_neg1(e, dest),
526                    }
527                }
528            }
529            None => None,
530        };
531
532        // Get the file handle
533        let Some(fd) = ecx.machine.fds.get(socket) else {
534            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
535        };
536
537        let Some(socket) = fd.as_unix().as_socket() else {
538            return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest);
539        };
540
541        let mut is_non_block = false;
542
543        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
544        // if there is anything left at the end, that's an unsupported flag.
545        if matches!(
546            ecx.tcx.sess.target.os,
547            Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos
548        ) {
549            // MSG_NOSIGNAL and MSG_DONTWAIT only exist on Linux, Android, FreeBSD,
550            // Solaris, and Illumos targets.
551            let msg_nosignal = ecx.eval_libc_i32("MSG_NOSIGNAL");
552            let msg_dontwait = ecx.eval_libc_i32("MSG_DONTWAIT");
553            if flags & msg_nosignal == msg_nosignal {
554                // This is only needed to ensure that no EPIPE signal is sent when
555                // trying to send into a stream which is no longer connected.
556                // Since we don't support signals, we can ignore this.
557                flags &= !msg_nosignal;
558            }
559            if flags & msg_dontwait == msg_dontwait {
560                flags &= !msg_dontwait;
561                is_non_block = true;
562            }
563        }
564
565        if flags != 0 {
566            throw_unsup_format!(
567                "send: flag {flags:#x} is unsupported, only MSG_NOSIGNAL and MSG_DONTWAIT are allowed",
568            );
569        }
570
571        let dest = dest.clone();
572
573        socket.send(
574            ecx.machine.communicate(),
575            buffer_ptr,
576            length,
577            is_non_block,
578            dest_addr,
579            ecx,
580            callback!(
581                @capture<'tcx> {
582                    dest: MPlaceTy<'tcx>,
583                } |ecx, result: Result<u64, IoError>| {
584                    match result {
585                        Ok(bytes_sent) =>
586                            ecx.write_scalar(Scalar::from_target_isize(bytes_sent.try_into().unwrap(), ecx), &dest),
587                        Err(e) => ecx.set_errno_and_return_neg1(e, &dest)
588                    }
589                }
590            )
591        )
592    }
593
594    fn recv(
595        &mut self,
596        socket: &OpTy<'tcx>,
597        buffer: &OpTy<'tcx>,
598        length: &OpTy<'tcx>,
599        flags: &OpTy<'tcx>,
600        dest_addr: Option<(&OpTy<'tcx>, &OpTy<'tcx>)>,
601        // Location where the output scalar is written to.
602        dest: &MPlaceTy<'tcx>,
603    ) -> InterpResult<'tcx> {
604        let ecx = self.eval_context_mut();
605
606        let socket = ecx.read_scalar(socket)?.to_i32()?;
607        let buffer_ptr = ecx.read_pointer(buffer)?;
608        let length = ecx.read_target_usize(length)?;
609        let mut flags = ecx.read_scalar(flags)?.to_i32()?;
610
611        let dest_addr = match dest_addr {
612            Some((addr, addr_len)) => Some((ecx.read_pointer(addr)?, ecx.deref_pointer(addr_len)?)),
613            None => None,
614        };
615
616        // Get the file handle
617        let Some(fd) = ecx.machine.fds.get(socket) else {
618            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
619        };
620
621        let Some(socket) = fd.as_unix().as_socket() else {
622            return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest);
623        };
624
625        let mut is_peek = false;
626        let mut is_non_block = false;
627
628        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
629        // if there is anything left at the end, that's an unsupported flag.
630
631        let msg_peek = ecx.eval_libc_i32("MSG_PEEK");
632        if flags & msg_peek == msg_peek {
633            is_peek = true;
634            flags &= !msg_peek;
635        }
636
637        if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) {
638            // MSG_CMSG_CLOEXEC only exists on Linux, Android, FreeBSD,
639            // and Illumos targets.
640            let msg_cmsg_cloexec = ecx.eval_libc_i32("MSG_CMSG_CLOEXEC");
641            if flags & msg_cmsg_cloexec == msg_cmsg_cloexec {
642                // We don't support `exec` so we can ignore this.
643                flags &= !msg_cmsg_cloexec;
644            }
645        }
646
647        if matches!(
648            ecx.tcx.sess.target.os,
649            Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos
650        ) {
651            // MSG_DONTWAIT only exists on Linux, Android, FreeBSD,
652            // Solaris, and Illumos targets.
653            let msg_dontwait = ecx.eval_libc_i32("MSG_DONTWAIT");
654            if flags & msg_dontwait == msg_dontwait {
655                flags &= !msg_dontwait;
656                is_non_block = true;
657            }
658        }
659
660        if flags != 0 {
661            throw_unsup_format!(
662                "recv: flag {flags:#x} is unsupported, only MSG_PEEK, MSG_DONTWAIT \
663                and MSG_CMSG_CLOEXEC are allowed",
664            );
665        }
666
667        let dest = dest.clone();
668
669        socket.recv(
670            ecx.machine.communicate(),
671            buffer_ptr,
672            length,
673            is_peek,
674            is_non_block,
675            ecx,
676            callback!(
677                @capture<'tcx> {
678                    dest_addr: Option<(Pointer, MPlaceTy<'tcx>)>,
679                    dest: MPlaceTy<'tcx>,
680                } |ecx, result: Result<(u64, Option<SocketAddr>), IoError>| {
681                    let (bytes_received, mut origin_addr_opt) = match result {
682                        Ok(data) => data,
683                        Err(e) => return ecx.set_errno_and_return_neg1(e, &dest)
684                    };
685
686                    if let Some((addr_ptr, addr_len_mplace)) = dest_addr  {
687                        if ecx.ptr_is_null(addr_ptr)? {
688                            // When the `addr_ptr` is a null pointer the caller is not interested in
689                            // the socket address.
690                            origin_addr_opt = None;
691                        }
692                        // The recvfrom(3) man page specifies that "[...] the value stored in the object pointed to
693                        // `address` is unspecified [...]" should the protocol not provide the source address of the message.
694                        // In this case we do the same thing as the Linux implementation and simply don't write anything to the
695                        // `addr_ptr` pointer and zero the `addr_len_mplace` place.
696                        ecx.write_socket_address(origin_addr_opt.as_ref(), addr_ptr, &addr_len_mplace)?;
697                    }
698
699                    ecx.write_scalar(Scalar::from_target_isize(bytes_received.try_into().unwrap(), ecx), &dest)
700
701                }
702            ),
703        )
704    }
705
706    fn setsockopt(
707        &mut self,
708        socket: &OpTy<'tcx>,
709        level: &OpTy<'tcx>,
710        option_name: &OpTy<'tcx>,
711        option_value: &OpTy<'tcx>,
712        option_len: &OpTy<'tcx>,
713    ) -> InterpResult<'tcx, Scalar> {
714        let ecx = self.eval_context_mut();
715
716        let socket = ecx.read_scalar(socket)?.to_i32()?;
717        let level = ecx.read_scalar(level)?.to_i32()?;
718        let option_name = ecx.read_scalar(option_name)?.to_i32()?;
719        let option_value_ptr = ecx.read_pointer(option_value)?;
720        let Ok(option_len) = u64::try_from(ecx.read_int::<i128>(option_len)?) else {
721            return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
722        };
723
724        // Check that the buffer has (at least) the given size.
725        ecx.check_ptr_access(
726            option_value_ptr,
727            Size::from_bytes(option_len),
728            CheckInAllocMsg::MemoryAccess,
729        )?;
730
731        // Get the file handle
732        let Some(fd) = ecx.machine.fds.get(socket) else {
733            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
734        };
735
736        let Some(socket) = fd.as_unix().as_socket() else {
737            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
738        };
739
740        let result = socket.setsockopt(level, option_name, option_value_ptr, option_len, ecx)?;
741        match result {
742            Ok(_) => interp_ok(Scalar::from_i32(0)),
743            Err(e) => ecx.set_errno_and_return_neg1_i32(e),
744        }
745    }
746
747    fn getsockopt(
748        &mut self,
749        socket: &OpTy<'tcx>,
750        level: &OpTy<'tcx>,
751        option_name: &OpTy<'tcx>,
752        option_value: &OpTy<'tcx>,
753        option_len_ptr: &OpTy<'tcx>,
754    ) -> InterpResult<'tcx, Scalar> {
755        let ecx = self.eval_context_mut();
756
757        let socket = ecx.read_scalar(socket)?.to_i32()?;
758        let level = ecx.read_scalar(level)?.to_i32()?;
759        let option_name = ecx.read_scalar(option_name)?.to_i32()?;
760        // These two pointers are used to return the value: `len_ptr` initially stores how much space
761        // is available. If the actual value fits into that space, it is written to
762        // `value_ptr` and `len_ptr` is updated to represent how many bytes
763        // were actually written. If the value does not fit, it is silently truncated.
764        // Also see <https://pubs.opengroup.org/onlinepubs/9799919799/functions/getsockopt.html>.
765        let option_value_ptr = ecx.read_pointer(option_value)?;
766        let option_len_place = ecx.deref_pointer(option_len_ptr)?;
767
768        // Get the file handle
769        let Some(fd) = ecx.machine.fds.get(socket) else {
770            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
771        };
772
773        let Some(socket) = fd.as_unix().as_socket() else {
774            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
775        };
776
777        if ecx.ptr_is_null(option_value_ptr)? || ecx.ptr_is_null(option_len_place.ptr())? {
778            // This socket option returns a value and thus we need to return EFAULT
779            // when either the value or the length pointers are null pointers.
780            return ecx.set_errno_and_return_neg1_i32(LibcError("EFAULT"));
781        }
782
783        let Ok(option_len) = u64::try_from(ecx.read_int::<i128>(&option_len_place)?) else {
784            return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL"));
785        };
786
787        // Check that the buffer has (at least) the given size.
788        ecx.check_ptr_access(
789            option_value_ptr,
790            Size::from_bytes(option_len),
791            CheckInAllocMsg::MemoryAccess,
792        )?;
793
794        // `socket.getsockopt` returns a temporary buffer as `option_value_ptr` might not point
795        // to a large enough buffer, in which case we have to truncate.
796        let value_mplace = match socket.getsockopt(level, option_name, ecx)? {
797            Ok(value_mplace) => value_mplace,
798            Err(e) => return ecx.set_errno_and_return_neg1_i32(e),
799        };
800
801        // Truncated size of the output value.
802        let output_value_len = value_mplace.layout.size.min(Size::from_bytes(option_len));
803        // Copy the truncated value into the buffer pointed to by `option_value_ptr`.
804        ecx.mem_copy(
805            value_mplace.ptr(),
806            option_value_ptr,
807            // Truncate the value to fit the provided buffer.
808            output_value_len,
809            // The buffers are guaranteed to not overlap since the `value_mplace`
810            // was just newly allocated on the stack.
811            true,
812        )?;
813        // Deallocate the value buffer as it was only needed to store the value and
814        // copy it into the buffer pointed to by `option_value_ptr`.
815        ecx.deallocate_ptr(value_mplace.ptr(), None, MemoryKind::Stack)?;
816
817        // On output, the length pointer contains the amount of bytes written -- not the size
818        // of the value before truncation.
819        ecx.write_int(output_value_len.bytes(), &option_len_place)?;
820
821        interp_ok(Scalar::from_i32(0))
822    }
823
824    fn getsockname(
825        &mut self,
826        socket: &OpTy<'tcx>,
827        address: &OpTy<'tcx>,
828        address_len: &OpTy<'tcx>,
829    ) -> InterpResult<'tcx, Scalar> {
830        let ecx = self.eval_context_mut();
831
832        let socket = ecx.read_scalar(socket)?.to_i32()?;
833        let address_ptr = ecx.read_pointer(address)?;
834        let address_len_place = ecx.deref_pointer(address_len)?;
835
836        // Get the file handle
837        let Some(fd) = ecx.machine.fds.get(socket) else {
838            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
839        };
840
841        let Some(socket) = fd.as_unix().as_socket() else {
842            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
843        };
844
845        let address = match socket.getsockname(ecx.machine.communicate(), ecx)? {
846            Ok(address) => address,
847            Err(e) => return ecx.set_errno_and_return_neg1_i32(e),
848        };
849
850        ecx.write_socket_address(Some(&address), address_ptr, &address_len_place)
851            .map(|()| Scalar::from_i32(0))
852    }
853
854    fn getpeername(
855        &mut self,
856        socket: &OpTy<'tcx>,
857        address: &OpTy<'tcx>,
858        address_len: &OpTy<'tcx>,
859        // Location where the output scalar is written to.
860        dest: &MPlaceTy<'tcx>,
861    ) -> InterpResult<'tcx> {
862        let ecx = self.eval_context_mut();
863
864        let socket = ecx.read_scalar(socket)?.to_i32()?;
865        let address_ptr = ecx.read_pointer(address)?;
866        let address_len_place = ecx.deref_pointer(address_len)?;
867
868        // Get the file handle
869        let Some(fd) = ecx.machine.fds.get(socket) else {
870            return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest);
871        };
872
873        let Some(socket) = fd.as_unix().as_socket() else {
874            return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest);
875        };
876
877        let dest = dest.clone();
878
879        socket.getpeername(
880            ecx.machine.communicate(),
881            ecx,
882            callback!(
883                @capture<'tcx> {
884                    address_ptr: Pointer,
885                    address_len_place: MPlaceTy<'tcx>,
886                    dest: MPlaceTy<'tcx>,
887                } |ecx, result: Result<SocketAddr, IoError>| {
888                    let address = match result {
889                        Ok(address) => address,
890                        Err(e) => return ecx.set_errno_and_return_neg1(e, &dest)
891                    };
892
893                    ecx.write_socket_address(
894                        Some(&address),
895                        address_ptr,
896                        &address_len_place,
897                    )?;
898                    ecx.write_scalar(Scalar::from_i32(0), &dest)
899                }
900            ),
901        )
902    }
903
904    fn shutdown(&mut self, socket: &OpTy<'tcx>, how: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
905        let ecx = self.eval_context_mut();
906
907        let socket = ecx.read_scalar(socket)?.to_i32()?;
908        let how = ecx.read_scalar(how)?.to_i32()?;
909
910        // Get the file handle
911        let Some(fd) = ecx.machine.fds.get(socket) else {
912            return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF"));
913        };
914
915        let Some(socket) = fd.as_unix().as_socket() else {
916            return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK"));
917        };
918
919        let is_read_shutdown = how == ecx.eval_libc_i32("SHUT_RD");
920        let is_write_shutdown = how == ecx.eval_libc_i32("SHUT_WR");
921        let is_read_write_shutdown = how == ecx.eval_libc_i32("SHUT_RDWR");
922
923        let how = match () {
924            _ if is_read_shutdown => Shutdown::Read,
925            _ if is_write_shutdown => Shutdown::Write,
926            _ if is_read_write_shutdown => Shutdown::Both,
927            // An invalid value was passed to `how`.
928            _ => return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")),
929        };
930
931        match socket.shutdown(ecx.machine.communicate(), how, ecx)? {
932            Ok(_) => interp_ok(Scalar::from_i32(0)),
933            Err(e) => ecx.set_errno_and_return_neg1_i32(e),
934        }
935    }
936
937    /// Set the `option` socket option on level SOL_SOCKET for `socket`.
938    /// `value_ptr` points to the new value of the socket option, and `value_len`
939    /// contains the amount of bytes the value uses at `value_ptr`.
940    fn set_generic_socket_option<T: UnixSocketFileDescription>(
941        &mut self,
942        option: i32,
943        value_ptr: Pointer,
944        value_len: u64,
945        socket: FileDescriptionRef<T>,
946    ) -> InterpResult<'tcx, Result<(), IoError>> {
947        let ecx = self.eval_context_mut();
948
949        let opt_so_rcvtimeo = ecx.eval_libc_i32("SO_RCVTIMEO");
950        let opt_so_sndtimeo = ecx.eval_libc_i32("SO_SNDTIMEO");
951        let opt_so_reuseaddr = ecx.eval_libc_i32("SO_REUSEADDR");
952        let opt_so_linger = if matches!(ecx.tcx.sess.target.os, Os::MacOs) {
953            // On macOS the SO_LINGER socket option sets the linger duration in kernel ticks
954            // while the SO_LINGER_SEC socket option sets the linger duration in seconds.
955            ecx.eval_libc_i32("SO_LINGER_SEC")
956        } else {
957            // For all other targets SO_LINGER sets the linger duration in seconds.
958            ecx.eval_libc_i32("SO_LINGER")
959        };
960        let opt_so_keepalive = ecx.eval_libc_i32("SO_KEEPALIVE");
961
962        if matches!(ecx.tcx.sess.target.os, Os::MacOs | Os::FreeBsd | Os::NetBsd) {
963            // SO_NOSIGPIPE only exists on MacOS, FreeBSD, and NetBSD.
964            let opt_so_nosigpipe = ecx.eval_libc_i32("SO_NOSIGPIPE");
965
966            if option == opt_so_nosigpipe {
967                if value_len != 4 {
968                    // Option value should be C-int which is usually 4 bytes.
969                    return interp_ok(Err(LibcError("EINVAL")));
970                }
971                let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.i32);
972                let _val = ecx.read_scalar(&option_value)?.to_i32()?;
973                // We entirely ignore this value since we do not support signals anyway.
974
975                return interp_ok(Ok(()));
976            }
977        }
978
979        if option == opt_so_rcvtimeo || option == opt_so_sndtimeo {
980            let timeval_layout = ecx.libc_ty_layout("timeval");
981            let option_value = ecx.ptr_to_mplace(value_ptr, timeval_layout);
982
983            let timeout = match ecx.read_timeval(&option_value)? {
984                None => return interp_ok(Err(LibcError("EINVAL"))),
985                Some(Duration::ZERO) => None,
986                Some(duration) => Some(duration),
987            };
988
989            if option == opt_so_rcvtimeo {
990                socket.set_read_timeout(timeout)?;
991            } else {
992                socket.set_write_timeout(timeout)?;
993            }
994
995            return interp_ok(Ok(()));
996        }
997
998        if option == opt_so_reuseaddr {
999            if value_len != 4 {
1000                // Option value should be C-int which is usually 4 bytes.
1001                return interp_ok(Err(LibcError("EINVAL")));
1002            }
1003            let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.i32);
1004            let reuse = ecx.read_scalar(&option_value)?.to_i32()? != 0;
1005
1006            let result = socket.with_socket_ref(|s| s.set_reuse_address(reuse)).map_err(|()| {
1007                err_unsup_format!(
1008                    "setsockopt: option SO_REUSEADDR is unsupported for {}",
1009                    socket.name()
1010                )
1011            })?;
1012            return interp_ok(result.map_err(IoError::HostError));
1013        } else if option == opt_so_linger {
1014            let linger_layout = ecx.libc_ty_layout("linger");
1015            if value_len != linger_layout.size.bytes() {
1016                // Size should be equal to the size of a linger struct.
1017                return interp_ok(Err(LibcError("EINVAL")));
1018            }
1019            let option_value = ecx.ptr_to_mplace(value_ptr, linger_layout);
1020
1021            let onoff_field = ecx.project_field_named(&option_value, "l_onoff")?;
1022            let onoff = ecx.read_scalar(&onoff_field)?.to_i32()? != 0;
1023
1024            let linger_field = ecx.project_field_named(&option_value, "l_linger")?;
1025            let linger = ecx.read_scalar(&linger_field)?.to_i32()?;
1026
1027            let linger = onoff.then_some(Duration::from_secs(u64::try_from(linger).unwrap()));
1028
1029            let result = socket.with_socket_ref(|s| s.set_linger(linger)).map_err(|()| {
1030                err_unsup_format!(
1031                    "setsockopt: option SO_LINGER is unsupported for {}",
1032                    socket.name()
1033                )
1034            })?;
1035            return interp_ok(result.map_err(IoError::HostError));
1036        } else if option == opt_so_keepalive {
1037            if value_len != 4 {
1038                // Option value should be C-int which is usually 4 bytes.
1039                return interp_ok(Err(LibcError("EINVAL")));
1040            }
1041            let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.i32);
1042            let keepalive = ecx.read_scalar(&option_value)?.to_i32()? != 0;
1043
1044            let result = socket.with_socket_ref(|s| s.set_keepalive(keepalive)).map_err(|()| {
1045                err_unsup_format!(
1046                    "setsockopt: option SO_LINGER is unsupported for {}",
1047                    socket.name()
1048                )
1049            })?;
1050            return interp_ok(result.map_err(IoError::HostError));
1051        }
1052
1053        throw_unsup_format!("setsockopt: option {option:#x} is unsupported for level SOL_SOCKET");
1054    }
1055
1056    /// Set the `option` socket option on level IPPROTO_IP for `socket`.
1057    /// `value_ptr` points to the new value of the socket option, and `value_len`
1058    /// contains the amount of bytes the value uses at `value_ptr`.
1059    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1060    /// the shimmed socket.
1061    fn set_ipv4_socket_option(
1062        &self,
1063        option: i32,
1064        value_ptr: Pointer,
1065        value_len: u64,
1066        socket: socket2::SockRef<'_>,
1067    ) -> InterpResult<'tcx, Result<(), IoError>> {
1068        let ecx = self.eval_context_ref();
1069
1070        let opt_ip_ttl = ecx.eval_libc_i32("IP_TTL");
1071
1072        if option == opt_ip_ttl {
1073            if value_len != 4 {
1074                // Option value should be C-uint which is usually 4 bytes.
1075                return interp_ok(Err(LibcError("EINVAL")));
1076            }
1077            let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.u32);
1078            let ttl = ecx.read_scalar(&option_value)?.to_u32()?;
1079
1080            return interp_ok(socket.set_ttl_v4(ttl).map_err(IoError::HostError));
1081        }
1082
1083        throw_unsup_format!("setsockopt: option {option:#x} is unsupported for level IPPROTO_IP",);
1084    }
1085
1086    /// Set the `option` socket option on level IPPROTO_IPV6 for `socket`.
1087    /// `value_ptr` points to the new value of the socket option, and `value_len`
1088    /// contains the amount of bytes the value uses at `value_ptr`.
1089    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1090    /// the shimmed socket.
1091    /// `supports_multicast` specifies whether the protocol of `socket` supports
1092    /// multicast transmissions or not.
1093    fn set_ipv6_socket_option(
1094        &self,
1095        option: i32,
1096        value_ptr: Pointer,
1097        value_len: u64,
1098        socket: socket2::SockRef<'_>,
1099        supports_multicast: bool,
1100    ) -> InterpResult<'tcx, Result<(), IoError>> {
1101        let ecx = self.eval_context_ref();
1102
1103        let opt_ipv6_unicast_hops = ecx.eval_libc_i32("IPV6_UNICAST_HOPS");
1104        let opt_ipv6_multicast_hops = ecx.eval_libc_i32("IPV6_MULTICAST_HOPS");
1105
1106        if option == opt_ipv6_unicast_hops || option == opt_ipv6_multicast_hops {
1107            if value_len != 4 {
1108                // Option value should be C-uint which is usually 4 bytes.
1109                return interp_ok(Err(LibcError("EINVAL")));
1110            }
1111            let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.u32);
1112            let hop_limit = ecx.read_scalar(&option_value)?.to_u32()?;
1113
1114            if option == opt_ipv6_unicast_hops {
1115                return interp_ok(
1116                    socket.set_unicast_hops_v6(hop_limit).map_err(IoError::HostError),
1117                );
1118            } else if supports_multicast {
1119                return interp_ok(
1120                    socket.set_multicast_hops_v6(hop_limit).map_err(IoError::HostError),
1121                );
1122            } else {
1123                // Attempting to set IPV6_MULTICAST_HOPS on a socket which does not support multicast
1124                // results in a ENOPROTOOPT.
1125                return interp_ok(Err(LibcError("ENOPROTOOPT")));
1126            }
1127        }
1128
1129        throw_unsup_format!("setsockopt: option {option:#x} is unsupported for level IPPROTO_IPV6",);
1130    }
1131
1132    /// Set the `option` socket option on level IPPROTO_TCP for `socket`.
1133    /// `value_ptr` points to the new value of the socket option, and `value_len`
1134    /// contains the amount of bytes the value uses at `value_ptr`.
1135    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1136    /// the shimmed socket.
1137    fn set_tcp_socket_option(
1138        &self,
1139        option: i32,
1140        value_ptr: Pointer,
1141        value_len: u64,
1142        socket: socket2::SockRef<'_>,
1143    ) -> InterpResult<'tcx, Result<(), IoError>> {
1144        let ecx = self.eval_context_ref();
1145
1146        let opt_tcp_nodelay = ecx.eval_libc_i32("TCP_NODELAY");
1147
1148        if option == opt_tcp_nodelay {
1149            if value_len != 4 {
1150                // Option value should be C-int which is usually 4 bytes.
1151                return interp_ok(Err(LibcError("EINVAL")));
1152            }
1153            let option_value = ecx.ptr_to_mplace(value_ptr, ecx.machine.layouts.i32);
1154            let nodelay = ecx.read_scalar(&option_value)?.to_i32()? != 0;
1155
1156            return interp_ok(socket.set_tcp_nodelay(nodelay).map_err(IoError::HostError));
1157        }
1158
1159        throw_unsup_format!("setsockopt: option {option:#x} is unsupported for level IPPROTO_TCP");
1160    }
1161
1162    /// Get the `option` socket option on level SOL_SOCKET for `socket`.
1163    fn get_generic_socket_option<T: UnixSocketFileDescription>(
1164        &mut self,
1165        option: i32,
1166        socket: FileDescriptionRef<T>,
1167    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
1168        let ecx = self.eval_context_mut();
1169
1170        let opt_so_error = ecx.eval_libc_i32("SO_ERROR");
1171        let opt_so_rcvtimeo = ecx.eval_libc_i32("SO_RCVTIMEO");
1172        let opt_so_sndtimeo = ecx.eval_libc_i32("SO_SNDTIMEO");
1173        let opt_so_reuseaddr = ecx.eval_libc_i32("SO_REUSEADDR");
1174        let opt_so_linger = if matches!(ecx.tcx.sess.target.os, Os::MacOs) {
1175            // On macOS the SO_LINGER socket option sets the linger duration in kernel ticks
1176            // while the SO_LINGER_SEC socket option sets the linger duration in seconds.
1177            ecx.eval_libc_i32("SO_LINGER_SEC")
1178        } else {
1179            // For all other targets SO_LINGER sets the linger duration in seconds.
1180            ecx.eval_libc_i32("SO_LINGER")
1181        };
1182        let opt_so_keepalive = ecx.eval_libc_i32("SO_KEEPALIVE");
1183
1184        if option == opt_so_error {
1185            let return_value = match socket.take_error(ecx)? {
1186                Some(err) => ecx.io_error_to_errnum(err)?.to_i32()?,
1187                // If there is no error, we return 0 as the option value.
1188                None => 0,
1189            };
1190
1191            // Allocate new buffer on the stack with the `i32` layout.
1192            let value_buffer = ecx.allocate(ecx.machine.layouts.i32, MemoryKind::Stack)?;
1193            ecx.write_int(return_value, &value_buffer)?;
1194            return interp_ok(Ok(value_buffer));
1195        } else if option == opt_so_rcvtimeo || option == opt_so_sndtimeo {
1196            let timeout = if option == opt_so_rcvtimeo {
1197                socket.get_read_timeout()?
1198            } else {
1199                socket.get_write_timeout()?
1200            }
1201            .unwrap_or_default();
1202
1203            let secs = timeout.as_secs();
1204            let usecs = timeout.subsec_micros();
1205
1206            let timeval_layout = ecx.libc_ty_layout("timeval");
1207            // Allocate new buffer on the stack with the `timeval` layout.
1208            let timeval_buffer = ecx.allocate(timeval_layout, MemoryKind::Stack)?;
1209
1210            let sec_field = ecx.project_field_named(&timeval_buffer, "tv_sec")?;
1211            ecx.write_int(secs, &sec_field)?;
1212
1213            let usec_field = ecx.project_field_named(&timeval_buffer, "tv_usec")?;
1214            ecx.write_int(usecs, &usec_field)?;
1215
1216            return interp_ok(Ok(timeval_buffer));
1217        }
1218
1219        if option == opt_so_reuseaddr {
1220            let reuse = match socket.with_socket_ref(|s| s.reuse_address()) {
1221                Ok(Ok(reuse)) => reuse,
1222                Ok(Err(e)) => return interp_ok(Err(IoError::HostError(e))),
1223                Err(()) =>
1224                    throw_unsup_format!(
1225                        "getsockopt: option SO_REUSEADDR is unsupported for {}",
1226                        socket.name()
1227                    ),
1228            };
1229
1230            // Allocate new buffer on the stack with the `i32` layout.
1231            let value_buffer = ecx.allocate(ecx.machine.layouts.i32, MemoryKind::Stack)?;
1232            ecx.write_int(i32::from(reuse), &value_buffer)?;
1233
1234            return interp_ok(Ok(value_buffer));
1235        } else if option == opt_so_linger {
1236            let linger = match socket.with_socket_ref(|s| s.linger()) {
1237                Ok(Ok(linger)) => linger,
1238                Ok(Err(e)) => return interp_ok(Err(IoError::HostError(e))),
1239                Err(()) =>
1240                    throw_unsup_format!(
1241                        "getsockopt: option SO_LINGER is unsupported for {}",
1242                        socket.name()
1243                    ),
1244            };
1245
1246            let linger_layout = ecx.libc_ty_layout("linger");
1247            // Allocate new buffer on the stack with the `linger` layout.
1248            let linger_buffer = ecx.allocate(linger_layout, MemoryKind::Stack)?;
1249
1250            let onoff_field = ecx.project_field_named(&linger_buffer, "l_onoff")?;
1251            let onoff = i32::from(linger.is_some());
1252            ecx.write_int(onoff, &onoff_field)?;
1253
1254            let linger_field = ecx.project_field_named(&linger_buffer, "l_linger")?;
1255            let secs = i32::try_from(linger.unwrap_or_default().as_secs()).unwrap();
1256            ecx.write_int(secs, &linger_field)?;
1257
1258            return interp_ok(Ok(linger_buffer));
1259        } else if option == opt_so_keepalive {
1260            let keepalive = match socket.with_socket_ref(|s| s.keepalive()) {
1261                Ok(Ok(keepalive)) => keepalive,
1262                Ok(Err(e)) => return interp_ok(Err(IoError::HostError(e))),
1263                Err(()) =>
1264                    throw_unsup_format!(
1265                        "getsockopt: option SO_KEEPALIVE is unsupported for {}",
1266                        socket.name()
1267                    ),
1268            };
1269
1270            // Allocate new buffer on the stack with the `i32` layout.
1271            let value_buffer = ecx.allocate(ecx.machine.layouts.i32, MemoryKind::Stack)?;
1272            ecx.write_int(i32::from(keepalive), &value_buffer)?;
1273
1274            return interp_ok(Ok(value_buffer));
1275        }
1276
1277        throw_unsup_format!("getsockopt: option {option:#x} is unsupported for level SOL_SOCKET",);
1278    }
1279
1280    /// Get the `option` socket option on level IPPROTO_IP for `socket`.
1281    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1282    /// the shimmed socket.
1283    fn get_ipv4_socket_option(
1284        &mut self,
1285        option: i32,
1286        socket: socket2::SockRef<'_>,
1287    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
1288        let ecx = self.eval_context_mut();
1289
1290        let opt_ip_ttl = ecx.eval_libc_i32("IP_TTL");
1291
1292        if option == opt_ip_ttl {
1293            let ttl = match socket.ttl_v4() {
1294                Ok(ttl) => ttl,
1295                Err(e) => return interp_ok(Err(IoError::HostError(e))),
1296            };
1297
1298            // Allocate new buffer on the stack with the `u32` layout.
1299            let value_buffer = ecx.allocate(ecx.machine.layouts.u32, MemoryKind::Stack)?;
1300            ecx.write_int(ttl, &value_buffer)?;
1301            return interp_ok(Ok(value_buffer));
1302        }
1303
1304        throw_unsup_format!("getsockopt: option {option:#x} is unsupported for level IPPROTO_IP",);
1305    }
1306
1307    /// Get the `option` socket option on level IPPROTO_IPV6 for `socket`.
1308    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1309    /// the shimmed socket.
1310    /// `supports_multicast` specifies whether the protocol of `socket` supports
1311    /// multicast transmissions or not.
1312    fn get_ipv6_socket_option(
1313        &mut self,
1314        option: i32,
1315        socket: socket2::SockRef<'_>,
1316        supports_multicast: bool,
1317    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
1318        let ecx = self.eval_context_mut();
1319
1320        let opt_ipv6_unicast_hops = ecx.eval_libc_i32("IPV6_UNICAST_HOPS");
1321        let opt_ipv6_multicast_hops = ecx.eval_libc_i32("IPV6_MULTICAST_HOPS");
1322
1323        if option == opt_ipv6_unicast_hops || option == opt_ipv6_multicast_hops {
1324            let hops_result = if option == opt_ipv6_unicast_hops {
1325                socket.unicast_hops_v6()
1326            } else if supports_multicast {
1327                socket.multicast_hops_v6()
1328            } else {
1329                // Attempting to read IPV6_MULTICAST_HOPS from a socket which does not support multicast
1330                // results in a ENOPROTOOPT.
1331                return interp_ok(Err(LibcError("ENOPROTOOPT")));
1332            };
1333
1334            let hops = match hops_result {
1335                Ok(hops) => hops,
1336                Err(e) => return interp_ok(Err(IoError::HostError(e))),
1337            };
1338
1339            // Allocate new buffer on the stack with the `u32` layout.
1340            let value_buffer = ecx.allocate(ecx.machine.layouts.u32, MemoryKind::Stack)?;
1341            ecx.write_int(hops, &value_buffer)?;
1342            return interp_ok(Ok(value_buffer));
1343        }
1344
1345        throw_unsup_format!("getsockopt: option {option:#x} is unsupported for level IPPROTO_IPV6",);
1346    }
1347
1348    /// Get the `option` socket option on level IPPROTO_TCP for `socket`.
1349    /// `socket` is a [`socket2::SockRef`] to the underlying host socket of
1350    /// the shimmed socket.
1351    fn get_tcp_socket_option(
1352        &mut self,
1353        option: i32,
1354        socket: socket2::SockRef<'_>,
1355    ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
1356        let ecx = self.eval_context_mut();
1357
1358        let opt_tcp_nodelay = ecx.eval_libc_i32("TCP_NODELAY");
1359
1360        if option == opt_tcp_nodelay {
1361            let nodelay = match socket.tcp_nodelay() {
1362                Ok(nodelay) => nodelay,
1363                Err(e) => return interp_ok(Err(IoError::HostError(e))),
1364            };
1365
1366            // Allocate new buffer on the stack with the `i32` layout.
1367            let value_buffer = ecx.allocate(ecx.machine.layouts.i32, MemoryKind::Stack)?;
1368            ecx.write_int(i32::from(nodelay), &value_buffer)?;
1369            return interp_ok(Ok(value_buffer));
1370        }
1371
1372        throw_unsup_format!("getsockopt: option {option:#x} is unsupported for level IPPROTO_TCP");
1373    }
1374}
1375
1376/// Get the deadline for an action (e.g. reading or writing).
1377/// When `is_non_block` is [`true`], the returned deadline is "now", i.e.,
1378/// we wake up immediately if the action cannot be completed.
1379/// If `action_timeout` is `Some(duration)`, the returned deadline is in the
1380/// future, at now + `duration`. Otherwise, no deadline ([`None`]) is
1381/// returned, indicating that the action can block indefinitely.
1382pub(crate) fn socket_action_deadline<'tcx>(
1383    ecx: &MiriInterpCx<'tcx>,
1384    is_non_block: bool,
1385    action_timeout: Option<Duration>,
1386) -> Option<Deadline> {
1387    if is_non_block {
1388        // Non-blocking sockets always have a zero timeout.
1389        Some(ecx.machine.monotonic_clock.now().into())
1390    } else {
1391        action_timeout.map(|duration| ecx.machine.monotonic_clock.now().add_lossy(duration).into())
1392    }
1393}