wasmer_wasix/syscalls/wasi/
fd_event.rs

1use super::*;
2use crate::{fs::NotificationInner, syscalls::*};
3
4/// ### `fd_event()`
5/// Creates a file handle for event notifications
6#[instrument(level = "trace", skip_all, fields(%initial_val, ret_fd = field::Empty), ret)]
7pub fn fd_event<M: MemorySize>(
8    mut ctx: FunctionEnvMut<'_, WasiEnv>,
9    initial_val: u64,
10    flags: EventFdFlags,
11    ret_fd: WasmPtr<WasiFd, M>,
12) -> Result<Errno, WasiError> {
13    WasiEnv::do_pending_operations(&mut ctx)?;
14
15    let fd = wasi_try_ok!(fd_event_internal(&mut ctx, initial_val, flags, None)?);
16
17    let env = ctx.data();
18    let (memory, state, _) = unsafe { env.get_memory_and_wasi_state_and_inodes(&ctx, 0) };
19    Span::current().record("ret_fd", fd);
20    wasi_try_mem_ok!(ret_fd.write(&memory, fd));
21
22    #[cfg(feature = "journal")]
23    if env.enable_journal {
24        JournalEffector::save_fd_event(&mut ctx, initial_val, flags, fd).map_err(|err| {
25            tracing::error!("failed to save fd_event event - {}", err);
26            WasiError::Exit(ExitCode::from(Errno::Fault))
27        })?;
28    }
29
30    Ok(Errno::Success)
31}
32
33pub fn fd_event_internal(
34    ctx: &mut FunctionEnvMut<'_, WasiEnv>,
35    initial_val: u64,
36    flags: EventFdFlags,
37    with_fd: Option<WasiFd>,
38) -> Result<Result<WasiFd, Errno>, WasiError> {
39    let env = ctx.data();
40    let (memory, state, mut inodes) = unsafe { env.get_memory_and_wasi_state_and_inodes(&ctx, 0) };
41
42    let is_semaphore = flags & EVENT_FD_FLAGS_SEMAPHORE != 0;
43    let kind = Kind::EventNotifications {
44        inner: Arc::new(NotificationInner::new(initial_val, is_semaphore)),
45    };
46
47    // Forward EFD_NONBLOCK (== O_NONBLOCK == Fdflags::NONBLOCK) onto the fd.
48    let fs_flags = if flags & EVENT_FD_FLAGS_NONBLOCK != 0 {
49        Fdflags::NONBLOCK
50    } else {
51        Fdflags::empty()
52    };
53
54    let inode =
55        state
56            .fs
57            .create_inode_with_default_stat(inodes, kind, false, "event".to_string().into());
58    let rights = Rights::FD_READ
59        | Rights::FD_WRITE
60        | Rights::POLL_FD_READWRITE
61        | Rights::FD_FDSTAT_SET_FLAGS;
62    let fd = wasi_try_ok_ok!(if let Some(fd) = with_fd {
63        state
64            .fs
65            .with_fd(rights, rights, fs_flags, Fdflagsext::empty(), 0, inode, fd)
66            .map(|_| fd)
67    } else {
68        state
69            .fs
70            .create_fd(rights, rights, fs_flags, Fdflagsext::empty(), 0, inode)
71    });
72
73    Ok(Ok(fd))
74}