1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use virtual_fs::Pipe;

use super::*;
use crate::syscalls::*;

/// ### `fd_pipe()`
/// Creates ta pipe that feeds data between two file handles
/// Output:
/// - `Fd`
///     First file handle that represents one end of the pipe
/// - `Fd`
///     Second file handle that represents the other end of the pipe
#[instrument(level = "trace", skip_all, fields(fd1 = field::Empty, fd2 = field::Empty), ret)]
pub fn fd_pipe<M: MemorySize>(
    ctx: FunctionEnvMut<'_, WasiEnv>,
    ro_fd1: WasmPtr<WasiFd, M>,
    ro_fd2: WasmPtr<WasiFd, M>,
) -> Errno {
    let env = ctx.data();
    let (memory, state, inodes) = unsafe { env.get_memory_and_wasi_state_and_inodes(&ctx, 0) };

    let (pipe1, pipe2) = Pipe::channel();

    let inode1 = state.fs.create_inode_with_default_stat(
        inodes,
        Kind::Pipe { pipe: pipe1 },
        false,
        "pipe".to_string().into(),
    );
    let inode2 = state.fs.create_inode_with_default_stat(
        inodes,
        Kind::Pipe { pipe: pipe2 },
        false,
        "pipe".to_string().into(),
    );

    let rights = Rights::FD_READ
        | Rights::FD_WRITE
        | Rights::FD_SYNC
        | Rights::FD_DATASYNC
        | Rights::POLL_FD_READWRITE
        | Rights::FD_FDSTAT_SET_FLAGS;
    let fd1 = wasi_try!(state
        .fs
        .create_fd(rights, rights, Fdflags::empty(), 0, inode1));
    let fd2 = wasi_try!(state
        .fs
        .create_fd(rights, rights, Fdflags::empty(), 0, inode2));
    Span::current().record("fd1", fd1).record("fd2", fd2);

    wasi_try_mem!(ro_fd1.write(&memory, fd1));
    wasi_try_mem!(ro_fd2.write(&memory, fd2));

    Errno::Success
}