Skip to main content

miri/shims/unix/
virtual_socket.rs

1//! This implements "virtual" sockets, that do not correspond to anything on the host system and
2//! are entirely implemented inside Miri.
3//! This is used to implement `socketpair` and `pipe`.
4
5use std::cell::{Cell, OnceCell, RefCell};
6use std::collections::VecDeque;
7use std::io::{self, ErrorKind, Read};
8
9use rustc_target::spec::Os;
10
11use crate::concurrency::VClock;
12use crate::shims::files::{
13    EvalContextExt as _, FdId, FileDescription, FileDescriptionRef, WeakFileDescriptionRef,
14};
15use crate::shims::unix::UnixFileDescription;
16use crate::shims::unix::linux_like::epoll::{EpollReadiness, EvalContextExt as _};
17use crate::*;
18
19/// The maximum capacity of the socketpair buffer in bytes.
20/// This number is arbitrary as the value can always
21/// be configured in the real system.
22const MAX_SOCKETPAIR_BUFFER_CAPACITY: usize = 0x34000;
23
24#[derive(Debug, PartialEq)]
25enum VirtualSocketType {
26    // Either end of the socketpair fd.
27    Socketpair,
28    // Read end of the pipe.
29    PipeRead,
30    // Write end of the pipe.
31    PipeWrite,
32}
33
34/// One end of a pair of connected virtual sockets.
35#[derive(Debug)]
36struct VirtualSocket {
37    /// The buffer we are reading from, or `None` if this is the writing end of a pipe.
38    /// (In that case, the peer FD will be the reading end of that pipe.)
39    readbuf: Option<RefCell<Buffer>>,
40    /// The `VirtualSocket` file descriptor that is our "peer", and that holds the buffer we are
41    /// writing to. This is a weak reference because the other side may be closed before us; all
42    /// future writes will then trigger EPIPE.
43    peer_fd: OnceCell<WeakFileDescriptionRef<VirtualSocket>>,
44    /// Indicates whether the peer has lost data when the file description is closed.
45    /// This flag is set to `true` if the peer's `readbuf` is non-empty at the time
46    /// of closure.
47    peer_lost_data: Cell<bool>,
48    /// A list of thread ids blocked because the buffer was empty.
49    /// Once another thread writes some bytes, these threads will be unblocked.
50    blocked_read_tid: RefCell<Vec<ThreadId>>,
51    /// A list of thread ids blocked because the buffer was full.
52    /// Once another thread reads some bytes, these threads will be unblocked.
53    blocked_write_tid: RefCell<Vec<ThreadId>>,
54    /// Whether this fd is non-blocking or not.
55    is_nonblock: Cell<bool>,
56    // Differentiate between different virtual socket fd types.
57    fd_type: VirtualSocketType,
58}
59
60#[derive(Debug)]
61struct Buffer {
62    buf: VecDeque<u8>,
63    clock: VClock,
64}
65
66impl Buffer {
67    fn new() -> Self {
68        Buffer { buf: VecDeque::new(), clock: VClock::default() }
69    }
70}
71
72impl VirtualSocket {
73    fn peer_fd(&self) -> &WeakFileDescriptionRef<VirtualSocket> {
74        self.peer_fd.get().unwrap()
75    }
76}
77
78impl FileDescription for VirtualSocket {
79    fn name(&self) -> &'static str {
80        match self.fd_type {
81            VirtualSocketType::Socketpair => "socketpair",
82            VirtualSocketType::PipeRead | VirtualSocketType::PipeWrite => "pipe",
83        }
84    }
85
86    fn metadata<'tcx>(
87        &self,
88    ) -> InterpResult<'tcx, Either<io::Result<std::fs::Metadata>, &'static str>> {
89        let mode_name = match self.fd_type {
90            VirtualSocketType::Socketpair => "S_IFSOCK",
91            VirtualSocketType::PipeRead | VirtualSocketType::PipeWrite => "S_IFIFO",
92        };
93        interp_ok(Either::Right(mode_name))
94    }
95
96    fn destroy<'tcx>(
97        self,
98        _self_id: FdId,
99        _communicate_allowed: bool,
100        ecx: &mut MiriInterpCx<'tcx>,
101    ) -> InterpResult<'tcx, io::Result<()>> {
102        if let Some(peer_fd) = self.peer_fd().upgrade() {
103            // If the current readbuf is non-empty when the file description is closed,
104            // notify the peer that data lost has happened in current file description.
105            if let Some(readbuf) = &self.readbuf {
106                if !readbuf.borrow().buf.is_empty() {
107                    peer_fd.peer_lost_data.set(true);
108                }
109            }
110            // Notify peer fd that close has happened, since that can unblock reads and writes.
111            ecx.update_epoll_active_events(peer_fd, /* force_edge */ false)?;
112        }
113        interp_ok(Ok(()))
114    }
115
116    fn read<'tcx>(
117        self: FileDescriptionRef<Self>,
118        _communicate_allowed: bool,
119        ptr: Pointer,
120        len: usize,
121        ecx: &mut MiriInterpCx<'tcx>,
122        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
123    ) -> InterpResult<'tcx> {
124        virtual_socket_read(self, ptr, len, ecx, finish)
125    }
126
127    fn write<'tcx>(
128        self: FileDescriptionRef<Self>,
129        _communicate_allowed: bool,
130        ptr: Pointer,
131        len: usize,
132        ecx: &mut MiriInterpCx<'tcx>,
133        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
134    ) -> InterpResult<'tcx> {
135        virtual_socket_write(self, ptr, len, ecx, finish)
136    }
137
138    fn short_fd_operations(&self) -> bool {
139        // Linux guarantees that when a read/write on a streaming socket comes back short,
140        // the kernel buffer is empty/full:
141        // See <https://man7.org/linux/man-pages/man7/epoll.7.html> in Q&A section.
142        // So we can't do short reads/writes here.
143        false
144    }
145
146    fn as_unix<'tcx>(&self, _ecx: &MiriInterpCx<'tcx>) -> &dyn UnixFileDescription {
147        self
148    }
149
150    fn get_flags<'tcx>(&self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
151        let mut flags = 0;
152
153        // Get flag for file access mode.
154        // The flag for both socketpair and pipe will remain the same even when the peer
155        // fd is closed, so we need to look at the original type of this socket, not at whether
156        // the peer socket still exists.
157        match self.fd_type {
158            VirtualSocketType::Socketpair => {
159                flags |= ecx.eval_libc_i32("O_RDWR");
160            }
161            VirtualSocketType::PipeRead => {
162                flags |= ecx.eval_libc_i32("O_RDONLY");
163            }
164            VirtualSocketType::PipeWrite => {
165                flags |= ecx.eval_libc_i32("O_WRONLY");
166            }
167        }
168
169        // Get flag for blocking status.
170        if self.is_nonblock.get() {
171            flags |= ecx.eval_libc_i32("O_NONBLOCK");
172        }
173
174        interp_ok(Scalar::from_i32(flags))
175    }
176
177    fn set_flags<'tcx>(
178        &self,
179        mut flag: i32,
180        ecx: &mut MiriInterpCx<'tcx>,
181    ) -> InterpResult<'tcx, Scalar> {
182        let o_nonblock = ecx.eval_libc_i32("O_NONBLOCK");
183
184        // O_NONBLOCK flag can be set / unset by user.
185        if flag & o_nonblock == o_nonblock {
186            self.is_nonblock.set(true);
187            flag &= !o_nonblock;
188        } else {
189            self.is_nonblock.set(false);
190        }
191
192        // Throw error if there is any unsupported flag.
193        if flag != 0 {
194            throw_unsup_format!(
195                "fcntl: only O_NONBLOCK is supported for F_SETFL on socketpairs and pipes"
196            )
197        }
198
199        interp_ok(Scalar::from_i32(0))
200    }
201}
202
203/// Write to VirtualSocket based on the space available and return the written byte size.
204fn virtual_socket_write<'tcx>(
205    self_ref: FileDescriptionRef<VirtualSocket>,
206    ptr: Pointer,
207    len: usize,
208    ecx: &mut MiriInterpCx<'tcx>,
209    finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
210) -> InterpResult<'tcx> {
211    // Always succeed on write size 0.
212    // ("If count is zero and fd refers to a file other than a regular file, the results are not specified.")
213    if len == 0 {
214        return finish.call(ecx, Ok(0));
215    }
216
217    // We are writing to our peer's readbuf.
218    let Some(peer_fd) = self_ref.peer_fd().upgrade() else {
219        // If the upgrade from Weak to Rc fails, it indicates that all read ends have been
220        // closed. It is an error to write even if there would be space.
221        return finish.call(ecx, Err(ErrorKind::BrokenPipe.into()));
222    };
223
224    let Some(writebuf) = &peer_fd.readbuf else {
225        // Writing to the read end of a pipe.
226        return finish.call(ecx, Err(IoError::LibcError("EBADF")));
227    };
228
229    // Let's see if we can write.
230    let available_space = MAX_SOCKETPAIR_BUFFER_CAPACITY.strict_sub(writebuf.borrow().buf.len());
231    if available_space == 0 {
232        if self_ref.is_nonblock.get() {
233            // Non-blocking socketpair with a full buffer.
234            return finish.call(ecx, Err(ErrorKind::WouldBlock.into()));
235        } else {
236            self_ref.blocked_write_tid.borrow_mut().push(ecx.active_thread());
237            // Blocking socketpair with a full buffer.
238            // Block the current thread; only keep a weak ref for this.
239            let weak_self_ref = FileDescriptionRef::downgrade(&self_ref);
240            ecx.block_thread(
241                BlockReason::VirtualSocket,
242                None,
243                callback!(
244                    @capture<'tcx> {
245                        weak_self_ref: WeakFileDescriptionRef<VirtualSocket>,
246                        ptr: Pointer,
247                        len: usize,
248                        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
249                    }
250                    |this, unblock: UnblockKind| {
251                        assert_eq!(unblock, UnblockKind::Ready);
252                        // If we got unblocked, then our peer successfully upgraded its weak
253                        // ref to us. That means we can also upgrade our weak ref.
254                        let self_ref = weak_self_ref.upgrade().unwrap();
255                        virtual_socket_write(self_ref, ptr, len, this, finish)
256                    }
257                ),
258            );
259        }
260    } else {
261        // There is space to write!
262        let mut writebuf = writebuf.borrow_mut();
263        // Remember this clock so `read` can synchronize with us.
264        ecx.release_clock(|clock| {
265            writebuf.clock.join(clock);
266        })?;
267        // Do full write / partial write based on the space available.
268        let write_size = len.min(available_space);
269        let actual_write_size = ecx.write_to_host(&mut writebuf.buf, write_size, ptr)?.unwrap();
270        assert_eq!(actual_write_size, write_size);
271
272        // Need to stop accessing peer_fd so that it can be notified.
273        drop(writebuf);
274
275        // Unblock all threads that are currently blocked on peer_fd's read.
276        let waiting_threads = std::mem::take(&mut *peer_fd.blocked_read_tid.borrow_mut());
277        // FIXME: We can randomize the order of unblocking.
278        for thread_id in waiting_threads {
279            ecx.unblock_thread(thread_id, BlockReason::VirtualSocket)?;
280        }
281        // Notify epoll waiters: we might be no longer writable, peer might now be readable.
282        // The notification to the peer seems to be always sent on Linux, even if the
283        // FD was readable before.
284        ecx.update_epoll_active_events(self_ref, /* force_edge */ false)?;
285        ecx.update_epoll_active_events(peer_fd, /* force_edge */ true)?;
286
287        return finish.call(ecx, Ok(write_size));
288    }
289    interp_ok(())
290}
291
292/// Read from VirtualSocket and return the number of bytes read.
293fn virtual_socket_read<'tcx>(
294    self_ref: FileDescriptionRef<VirtualSocket>,
295    ptr: Pointer,
296    len: usize,
297    ecx: &mut MiriInterpCx<'tcx>,
298    finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
299) -> InterpResult<'tcx> {
300    // Always succeed on read size 0.
301    if len == 0 {
302        return finish.call(ecx, Ok(0));
303    }
304
305    let Some(readbuf) = &self_ref.readbuf else {
306        // FIXME: This should return EBADF, but there's no nice way to do that as there's no
307        // corresponding ErrorKind variant.
308        throw_unsup_format!("reading from the write end of a pipe")
309    };
310
311    if readbuf.borrow_mut().buf.is_empty() {
312        if self_ref.peer_fd().upgrade().is_none() {
313            // Socketpair with no peer and empty buffer.
314            // 0 bytes successfully read indicates end-of-file.
315            return finish.call(ecx, Ok(0));
316        } else if self_ref.is_nonblock.get() {
317            // Non-blocking socketpair with writer and empty buffer.
318            // https://linux.die.net/man/2/read
319            // EAGAIN or EWOULDBLOCK can be returned for socket,
320            // POSIX.1-2001 allows either error to be returned for this case.
321            // Since there is no ErrorKind for EAGAIN, WouldBlock is used.
322            return finish.call(ecx, Err(ErrorKind::WouldBlock.into()));
323        } else {
324            self_ref.blocked_read_tid.borrow_mut().push(ecx.active_thread());
325            // Blocking socketpair with writer and empty buffer.
326            // Block the current thread; only keep a weak ref for this.
327            let weak_self_ref = FileDescriptionRef::downgrade(&self_ref);
328            ecx.block_thread(
329                BlockReason::VirtualSocket,
330                None,
331                callback!(
332                    @capture<'tcx> {
333                        weak_self_ref: WeakFileDescriptionRef<VirtualSocket>,
334                        ptr: Pointer,
335                        len: usize,
336                        finish: DynMachineCallback<'tcx, Result<usize, IoError>>,
337                    }
338                    |this, unblock: UnblockKind| {
339                        assert_eq!(unblock, UnblockKind::Ready);
340                        // If we got unblocked, then our peer successfully upgraded its weak
341                        // ref to us. That means we can also upgrade our weak ref.
342                        let self_ref = weak_self_ref.upgrade().unwrap();
343                        virtual_socket_read(self_ref, ptr, len, this, finish)
344                    }
345                ),
346            );
347        }
348    } else {
349        // There's data to be read!
350        let mut readbuf = readbuf.borrow_mut();
351        // Synchronize with all previous writes to this buffer.
352        // FIXME: this over-synchronizes; a more precise approach would be to
353        // only sync with the writes whose data we will read.
354        ecx.acquire_clock(&readbuf.clock)?;
355
356        // Do full read / partial read based on the space available.
357        // Conveniently, `read` exists on `VecDeque` and has exactly the desired behavior.
358        let read_size = ecx.read_from_host(|buf| readbuf.buf.read(buf), len, ptr)?.unwrap();
359        let readbuf_now_empty = readbuf.buf.is_empty();
360
361        // Need to drop before others can access the readbuf again.
362        drop(readbuf);
363
364        // A notification should be provided for the peer file description even when it can
365        // only write 1 byte. This implementation is not compliant with the actual Linux kernel
366        // implementation. For optimization reasons, the kernel will only mark the file description
367        // as "writable" when it can write more than a certain number of bytes. Since we
368        // don't know what that *certain number* is, we will provide a notification every time
369        // a read is successful. This might result in our epoll emulation providing more
370        // notifications than the real system.
371        if let Some(peer_fd) = self_ref.peer_fd().upgrade() {
372            // Unblock all threads that are currently blocked on peer_fd's write.
373            let waiting_threads = std::mem::take(&mut *peer_fd.blocked_write_tid.borrow_mut());
374            // FIXME: We can randomize the order of unblocking.
375            for thread_id in waiting_threads {
376                ecx.unblock_thread(thread_id, BlockReason::VirtualSocket)?;
377            }
378            // Notify epoll waiters: peer is now writable.
379            // Linux seems to always notify the peer if the read buffer is now empty.
380            // (Linux also does that if this was a "big" read, but to avoid some arbitrary
381            // threshold, we do not match that.)
382            ecx.update_epoll_active_events(peer_fd, /* force_edge */ readbuf_now_empty)?;
383        };
384        // Notify epoll waiters: we might be no longer readable.
385        ecx.update_epoll_active_events(self_ref, /* force_edge */ false)?;
386
387        return finish.call(ecx, Ok(read_size));
388    }
389    interp_ok(())
390}
391
392impl UnixFileDescription for VirtualSocket {
393    fn epoll_active_events<'tcx>(&self) -> InterpResult<'tcx, EpollReadiness> {
394        // We only check the status of EPOLLIN, EPOLLOUT, EPOLLHUP and EPOLLRDHUP flags.
395        // If other event flags need to be supported in the future, the check should be added here.
396
397        let mut epoll_readiness = EpollReadiness::empty();
398
399        // Check if it is readable.
400        if let Some(readbuf) = &self.readbuf {
401            if !readbuf.borrow().buf.is_empty() {
402                epoll_readiness.epollin = true;
403            }
404        } else {
405            // Without a read buffer, reading never blocks, so we are always ready.
406            epoll_readiness.epollin = true;
407        }
408
409        // Check if is writable.
410        if let Some(peer_fd) = self.peer_fd().upgrade() {
411            if let Some(writebuf) = &peer_fd.readbuf {
412                let data_size = writebuf.borrow().buf.len();
413                let available_space = MAX_SOCKETPAIR_BUFFER_CAPACITY.strict_sub(data_size);
414                if available_space != 0 {
415                    epoll_readiness.epollout = true;
416                }
417            } else {
418                // Without a write buffer, writing never blocks.
419                epoll_readiness.epollout = true;
420            }
421        } else {
422            // Peer FD has been closed. This always sets both the RDHUP and HUP flags
423            // as we do not support `shutdown` that could be used to partially close the stream.
424            epoll_readiness.epollrdhup = true;
425            epoll_readiness.epollhup = true;
426            // Since the peer is closed, even if no data is available reads will return EOF and
427            // writes will return EPIPE. In other words, they won't block, so we mark this as ready
428            // for read and write.
429            epoll_readiness.epollin = true;
430            epoll_readiness.epollout = true;
431            // If there is data lost in peer_fd, set EPOLLERR.
432            if self.peer_lost_data.get() {
433                epoll_readiness.epollerr = true;
434            }
435        }
436        interp_ok(epoll_readiness)
437    }
438}
439
440impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
441pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
442    /// For more information on the arguments see the socketpair manpage:
443    /// <https://linux.die.net/man/2/socketpair>
444    fn socketpair(
445        &mut self,
446        domain: &OpTy<'tcx>,
447        type_: &OpTy<'tcx>,
448        protocol: &OpTy<'tcx>,
449        sv: &OpTy<'tcx>,
450    ) -> InterpResult<'tcx, Scalar> {
451        let this = self.eval_context_mut();
452
453        let domain = this.read_scalar(domain)?.to_i32()?;
454        let mut flags = this.read_scalar(type_)?.to_i32()?;
455        let protocol = this.read_scalar(protocol)?.to_i32()?;
456        // This is really a pointer to `[i32; 2]` but we use a ptr-to-first-element representation.
457        let sv = this.deref_pointer_as(sv, this.machine.layouts.i32)?;
458
459        let mut is_sock_nonblock = false;
460
461        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
462        // if there is anything left at the end, that's an unsupported flag.
463        if matches!(this.tcx.sess.target.os, Os::Linux | Os::Android) {
464            // SOCK_NONBLOCK only exists on Linux.
465            let sock_nonblock = this.eval_libc_i32("SOCK_NONBLOCK");
466            let sock_cloexec = this.eval_libc_i32("SOCK_CLOEXEC");
467            if flags & sock_nonblock == sock_nonblock {
468                is_sock_nonblock = true;
469                flags &= !sock_nonblock;
470            }
471            if flags & sock_cloexec == sock_cloexec {
472                flags &= !sock_cloexec;
473            }
474        }
475
476        // Fail on unsupported input.
477        // AF_UNIX and AF_LOCAL are synonyms, so we accept both in case
478        // their values differ.
479        if domain != this.eval_libc_i32("AF_UNIX") && domain != this.eval_libc_i32("AF_LOCAL") {
480            throw_unsup_format!(
481                "socketpair: domain {:#x} is unsupported, only AF_UNIX \
482                                 and AF_LOCAL are allowed",
483                domain
484            );
485        } else if flags != this.eval_libc_i32("SOCK_STREAM") {
486            throw_unsup_format!(
487                "socketpair: type {:#x} is unsupported, only SOCK_STREAM, \
488                                 SOCK_CLOEXEC and SOCK_NONBLOCK are allowed",
489                flags
490            );
491        } else if protocol != 0 {
492            throw_unsup_format!(
493                "socketpair: socket protocol {protocol} is unsupported, \
494                                 only 0 is allowed",
495            );
496        }
497
498        // Generate file descriptions.
499        let fds = &mut this.machine.fds;
500        let fd0 = fds.new_ref(VirtualSocket {
501            readbuf: Some(RefCell::new(Buffer::new())),
502            peer_fd: OnceCell::new(),
503            peer_lost_data: Cell::new(false),
504            blocked_read_tid: RefCell::new(Vec::new()),
505            blocked_write_tid: RefCell::new(Vec::new()),
506            is_nonblock: Cell::new(is_sock_nonblock),
507            fd_type: VirtualSocketType::Socketpair,
508        });
509        let fd1 = fds.new_ref(VirtualSocket {
510            readbuf: Some(RefCell::new(Buffer::new())),
511            peer_fd: OnceCell::new(),
512            peer_lost_data: Cell::new(false),
513            blocked_read_tid: RefCell::new(Vec::new()),
514            blocked_write_tid: RefCell::new(Vec::new()),
515            is_nonblock: Cell::new(is_sock_nonblock),
516            fd_type: VirtualSocketType::Socketpair,
517        });
518
519        // Make the file descriptions point to each other.
520        fd0.peer_fd.set(FileDescriptionRef::downgrade(&fd1)).unwrap();
521        fd1.peer_fd.set(FileDescriptionRef::downgrade(&fd0)).unwrap();
522
523        // Insert the file description to the fd table, generating the file descriptors.
524        let sv0 = fds.insert(fd0);
525        let sv1 = fds.insert(fd1);
526
527        // Return socketpair file descriptors to the caller.
528        let sv0 = Scalar::from_int(sv0, sv.layout.size);
529        let sv1 = Scalar::from_int(sv1, sv.layout.size);
530        this.write_scalar(sv0, &sv)?;
531        this.write_scalar(sv1, &sv.offset(sv.layout.size, sv.layout, this)?)?;
532
533        interp_ok(Scalar::from_i32(0))
534    }
535
536    fn pipe2(
537        &mut self,
538        pipefd: &OpTy<'tcx>,
539        flags: Option<&OpTy<'tcx>>,
540    ) -> InterpResult<'tcx, Scalar> {
541        let this = self.eval_context_mut();
542
543        let pipefd = this.deref_pointer_as(pipefd, this.machine.layouts.i32)?;
544        let mut flags = match flags {
545            Some(flags) => this.read_scalar(flags)?.to_i32()?,
546            None => 0,
547        };
548
549        let cloexec = this.eval_libc_i32("O_CLOEXEC");
550        let o_nonblock = this.eval_libc_i32("O_NONBLOCK");
551
552        // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so
553        // if there is anything left at the end, that's an unsupported flag.
554        let mut is_nonblock = false;
555        if flags & o_nonblock == o_nonblock {
556            is_nonblock = true;
557            flags &= !o_nonblock;
558        }
559        // As usual we ignore CLOEXEC.
560        if flags & cloexec == cloexec {
561            flags &= !cloexec;
562        }
563        if flags != 0 {
564            throw_unsup_format!("unsupported flags in `pipe2`");
565        }
566
567        // Generate file descriptions.
568        // pipefd[0] refers to the read end of the pipe.
569        let fds = &mut this.machine.fds;
570        let fd0 = fds.new_ref(VirtualSocket {
571            readbuf: Some(RefCell::new(Buffer::new())),
572            peer_fd: OnceCell::new(),
573            peer_lost_data: Cell::new(false),
574            blocked_read_tid: RefCell::new(Vec::new()),
575            blocked_write_tid: RefCell::new(Vec::new()),
576            is_nonblock: Cell::new(is_nonblock),
577            fd_type: VirtualSocketType::PipeRead,
578        });
579        let fd1 = fds.new_ref(VirtualSocket {
580            readbuf: None,
581            peer_fd: OnceCell::new(),
582            peer_lost_data: Cell::new(false),
583            blocked_read_tid: RefCell::new(Vec::new()),
584            blocked_write_tid: RefCell::new(Vec::new()),
585            is_nonblock: Cell::new(is_nonblock),
586            fd_type: VirtualSocketType::PipeWrite,
587        });
588
589        // Make the file descriptions point to each other.
590        fd0.peer_fd.set(FileDescriptionRef::downgrade(&fd1)).unwrap();
591        fd1.peer_fd.set(FileDescriptionRef::downgrade(&fd0)).unwrap();
592
593        // Insert the file description to the fd table, generating the file descriptors.
594        let pipefd0 = fds.insert(fd0);
595        let pipefd1 = fds.insert(fd1);
596
597        // Return file descriptors to the caller.
598        let pipefd0 = Scalar::from_int(pipefd0, pipefd.layout.size);
599        let pipefd1 = Scalar::from_int(pipefd1, pipefd.layout.size);
600        this.write_scalar(pipefd0, &pipefd)?;
601        this.write_scalar(pipefd1, &pipefd.offset(pipefd.layout.size, pipefd.layout, this)?)?;
602
603        interp_ok(Scalar::from_i32(0))
604    }
605}