Skip to main content

wasi_virt_layer_cli/generator/
poll.rs

1use crate::generator::{Generator, GeneratorCtx};
2use crate::util::WalrusFID as _;
3
4/// A generator for handling the atomic wait timeout in `WaitPoll`.
5/// 
6/// If `ctx.threads` is true, this generator replaces the `__wvl_poll_atomic_wait` import
7/// with a function that executes the `memory.atomic.wait32` instruction.
8/// If `ctx.threads` is false, it replaces the import with a dummy function that returns `2`
9/// (which corresponds to timed out) immediately, allowing the fallback busy loop in `WaitPoll` to execute.
10#[derive(Debug, Default)]
11pub struct PollWait;
12
13impl Generator for PollWait {
14    fn post_combine(
15        &mut self,
16        module: &mut walrus::Module,
17        ctx: &GeneratorCtx,
18    ) -> eyre::Result<()> {
19        if let Some(id) = ("wvl_poll", "__wvl_poll_atomic_wait").get_fid(&module.imports).ok() {
20            if ctx.threads {
21                let vfs_mem = ctx.vfs_used_memory_id.unwrap();
22                module.replace_imported_func(id, |(builder, args)| {
23                    builder.func_body()
24                        .local_get(args[0])
25                        .local_get(args[1])
26                        .local_get(args[2])
27                        .atomic_wait(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 }, false);
28                }).map_err(|e| eyre::eyre!("Failed to replace __wvl_poll_atomic_wait with atomic.wait: {e}"))?;
29            } else {
30                module.replace_imported_func(id, |(builder, _args)| {
31                    builder.func_body()
32                        .i32_const(2); // 2 means timed out
33                }).map_err(|e| eyre::eyre!("Failed to replace __wvl_poll_atomic_wait with dummy return: {e}"))?;
34            }
35        }
36        Ok(())
37    }
38}