This file (https://github.com/bytecodealliance/wasmtime/blob/master/docs/WASI-tutorial.md) gives a very simple hello world example in the .WAT format. Is there a similar example that does file IO (e.g. write a string to "output.txt") that uses a file descriptor that is passed in from the runtime itself (instead of one that uses "open"/libpreopen)?
The simplest way to do that would be to pass in the file descriptor as index 0 and have the program read from stdin
Or, for output, pass it in as index 1 and have the program write to stdout
In the future we plan to add more ways to pass in handles, but for now, stdin/stdout/stderr and directories are what can be passed in, so the simplest thing is to just use those.
Tangential question - how do we know the file descriptors of pre-opened directories in Wasm (besides the normal stdin/stdout/stderr descriptors)? I see in the wasi libc source code, that "__wasilibc_find_relpath" returns dirfd (https://github.com/WebAssembly/wasi-libc/blob/master/libc-bottom-half/libpreopen/libpreopen.c). But I cannot find its implementation and it does not seem to be described as a WASI system call in the spec. I assume this function must have access to the file descriptors of the pre-opened directories passed to the program.
As __wasilibc_populate_libpreopen
(which is called by a WASI executable when it initializes), enumerating FD from 3 until __wasi_fd_prestat_dir_name
returns non-success could help you.
Actually this is not documented. But I guess there's no documented way.
So this might not be entirely relevant, but I did a PoC where you can assign an fd to a resource in Wasmtime directly from the CLI and then read and/or write on it (call fd_read
and fd_write
only, plus fd_fdstat_get
which is always available). Here's the sources: https://github.com/kubkon/wasi-compute The example is in Rust though and not wat.
The example I pasted in required certain customisations that I added to Wasmtime and which are only available in my fork, but hopefully the README should explain it relatively OK
Last updated: Nov 22 2024 at 16:03 UTC