Documentation
¶
Overview ¶
Package wasi is a WASI preview 1 (wasi_snapshot_preview1) host written against a byte-addressed guest memory and the engine's rootfs.FS.
It implements every function Go's wasip1 port imports (runtime, syscall, internal/syscall/unix), with the layouts and errno values of the snapshot-01 specification (docs/REFERENCES.md). It knows nothing of a WebAssembly runtime: a host calls Proc.Call with the raw arguments and a Memory, so the same code serves the native executor (as a wazero host module) and the browser executor (from a worker, over shared memory).
Index ¶
- Constants
- Variables
- func CheckBlock(ptr, align, size uint32, memSize uint64) error
- type Child
- type Config
- type ExitStatus
- type FDOp
- type FDOpKind
- type FDTable
- type Func
- type Group
- type GroupLimits
- type HostFunc
- type HostModule
- type Import
- type Instance
- type Memory
- type Mount
- type Proc
- func (p *Proc) Call(fn int, args []uint64, m Memory) Result
- func (p *Proc) CallImport(i int, args []uint64, m Memory) Result
- func (p *Proc) CapValue(name string) (string, bool)
- func (p *Proc) ChildChanged() <-chan struct{}
- func (p *Proc) Children() []*Child
- func (p *Proc) Cloexec(fd uint32) (bool, uint32)
- func (p *Proc) CloneFDs(cwd string, ops []FDOp) (*FDTable, uint32)
- func (p *Proc) Close()
- func (p *Proc) Dup(fd, from uint32) (uint32, uint32)
- func (p *Proc) Dup2(fd, to uint32) uint32
- func (p *Proc) Emit(module, action string, attrs map[string]string)
- func (p *Proc) Group() *Group
- func (p *Proc) HasCap(c string) bool
- func (p *Proc) Instance(module string) Instance
- func (p *Proc) IsTerminal(fd uint32) bool
- func (p *Proc) Label() string
- func (p *Proc) LookPath(name, pathList, cwd string) (string, uint32)
- func (p *Proc) Parent() *Proc
- func (p *Proc) Pid() uint32
- func (p *Proc) Pipe() (r, w uint32, errno uint32)
- func (p *Proc) ReadModule(abs string) ([]byte, uint32)
- func (p *Proc) Reap(pid uint32) (*Child, uint32)
- func (p *Proc) SetCloexec(fd uint32, on bool) uint32
- func (p *Proc) Spawn(spec SpawnSpec) (*Child, uint32)
- func (p *Proc) SpawnWait(spec SpawnSpec, then func(c *Child, errno uint32, m Memory) Result) Result
- func (p *Proc) Stat(abs string, nofollow bool) (*rootfs.Info, uint32)
- func (p *Proc) Terminal() *Terminal
- type Realloc
- type Result
- type SpawnSpec
- type Spawner
- type Stdin
- type Terminal
Constants ¶
const ( ECHILD = 12 ENOEXEC = 45 ENOMEM = 48 ENOTTY = 59 ESRCH = 71 )
Errno values the process primitives return, beyond those of wasi.go.
const ( F32 = 'f' F64 = 'F' )
Value types beyond I32 and I64.
const ( EADDRINUSE = 3 EADDRNOTAVAIL = 4 EAFNOSUPPORT = 5 EALREADY = 7 ECONNABORTED = 13 ECONNREFUSED = 14 ECONNRESET = 15 EHOSTUNREACH = 23 EINPROGRESS = 26 EINTR = 27 EISCONN = 30 EMFILE = 33 EMSGSIZE = 35 ENETDOWN = 38 ENETUNREACH = 40 ENOBUFS = 42 ENOPROTOOPT = 50 ENOTCONN = 53 ENOTSOCK = 57 EPIPE = 64 EPROTOTYPE = 67 ETIMEDOUT = 73 EAI_NONAME = 84 EAI_SERVICE = 85 )
More errno values of wasi_snapshot_preview1 (enum order), and the getaddrinfo ones WasmEdge adds.
const ( ESUCCESS = 0 E2BIG = 1 EACCES = 2 EAGAIN = 6 EBADF = 8 EEXIST = 20 EFAULT = 21 EINVAL = 28 EIO = 29 EISDIR = 31 ELOOP = 32 ENAMETOOLONG = 37 ENOENT = 44 ENOSPC = 51 ENOSYS = 52 ENOTDIR = 54 ENOTEMPTY = 55 ENOTSUP = 58 EPERM = 63 EROFS = 69 ESPIPE = 70 EXDEV = 75 ENOTCAPABLE = 76 )
Errno values of wasi_snapshot_preview1 (enum order of the spec).
const ( I32 = 'i' I64 = 'I' )
Param types of a function's core-wasm signature.
const MaxArgBytes = 256 << 10
MaxArgBytes bounds a spawn's argv and env together (Linux's ARG_MAX order of magnitude): E2BIG past it.
const MaxFDs = 1024
MaxFDs bounds the descriptors a process may hold.
const MaxModuleBytes = 128 << 20
MaxModuleBytes bounds a module a process spawns (spawns repeat, up to the group's rate, so each read is bounded on its own).
const MaxParams = 17
MaxParams bounds a host function's core parameters: the canonical ABI flattens at most 16 (MAX_FLAT_PARAMS), plus one return-area pointer.
const PipeSize = 64 << 10
PipeSize is a pipe's capacity in bytes (Linux's default).
const PreviewModule = "wasi_snapshot_preview1"
PreviewModule is the import module of Funcs.
const StdinSize = 64 << 10
StdinSize bounds what a process's stdin holds ahead of the guest.
const WASIXModule = "wasix_32v1"
WASIXModule is the import module name.
Variables ¶
var FuncIndex = func() map[string]int { m := make(map[string]int, len(Funcs)) for i, f := range Funcs { m[f.Name] = i } return m }()
FuncIndex maps a name to its index in Funcs.
var Funcs = []Func{ {"args_get", "ii", false}, {"args_sizes_get", "ii", false}, {"environ_get", "ii", false}, {"environ_sizes_get", "ii", false}, {"clock_res_get", "ii", false}, {"clock_time_get", "iIi", false}, {"fd_advise", "iIIi", false}, {"fd_allocate", "iII", false}, {"fd_close", "i", false}, {"fd_datasync", "i", false}, {"fd_fdstat_get", "ii", false}, {"fd_fdstat_set_flags", "ii", false}, {"fd_fdstat_set_rights", "iII", false}, {"fd_filestat_get", "ii", false}, {"fd_filestat_set_size", "iI", false}, {"fd_filestat_set_times", "iIIi", false}, {"fd_pread", "iiiIi", false}, {"fd_prestat_get", "ii", false}, {"fd_prestat_dir_name", "iii", false}, {"fd_pwrite", "iiiIi", false}, {"fd_read", "iiii", false}, {"fd_readdir", "iiiIi", false}, {"fd_renumber", "ii", false}, {"fd_seek", "iIii", false}, {"fd_sync", "i", false}, {"fd_tell", "ii", false}, {"fd_write", "iiii", false}, {"path_create_directory", "iii", false}, {"path_filestat_get", "iiiii", false}, {"path_filestat_set_times", "iiiiIIi", false}, {"path_link", "iiiiiii", false}, {"path_open", "iiiiiIIii", false}, {"path_readlink", "iiiiii", false}, {"path_remove_directory", "iii", false}, {"path_rename", "iiiiii", false}, {"path_symlink", "iiiii", false}, {"path_unlink_file", "iii", false}, {"poll_oneoff", "iiii", false}, {"proc_exit", "i", true}, {"proc_raise", "i", false}, {"sched_yield", "", false}, {"random_get", "ii", false}, {"sock_accept", "iii", false}, {"sock_recv", "iiiiii", false}, {"sock_send", "iiiii", false}, {"sock_shutdown", "ii", false}, {"sock_open", "iii", false}, {"sock_bind", "iii", false}, {"sock_listen", "ii", false}, {"sock_connect", "iii", false}, {"sock_recv_from", "iiiiiiii", false}, {"sock_send_to", "iiiiiii", false}, {"sock_getsockopt", "iiiii", false}, {"sock_setsockopt", "iiiii", false}, {"sock_getlocaladdr", "iii", false}, {"sock_getpeeraddr", "iii", false}, {"sock_getaddrinfo", "iiiiiiii", false}, }
Funcs lists the imports, in a fixed order a host may index by.
Functions ¶
func CheckBlock ¶ added in v0.13.0
CheckBlock refuses a block a guest's allocator returned unless it is aligned and lies inside a memory of memSize bytes. The guest chooses ptr, so the sum is computed without overflow.
Types ¶
type Child ¶ added in v0.15.0
type Child struct {
// contains filtered or unexported fields
}
Child is a process started by Spawn, as its parent sees it.
func NewChild ¶ added in v0.15.0
NewChild is for executors: the handle Spawn returns, with the child's pid and how to kill it. The executor calls Exit when it ends.
func (*Child) Done ¶ added in v0.15.0
func (c *Child) Done() <-chan struct{}
Done is closed when the child has ended.
func (*Child) Exit ¶ added in v0.15.0
func (c *Child) Exit(s ExitStatus, parent *Proc)
Exit records the child's end (executors call it once).
func (*Child) Status ¶ added in v0.15.0
func (c *Child) Status() ExitStatus
Status is how the child ended; valid once Done is closed.
type Config ¶
type Config struct {
Args, Env []string
FS *rootfs.FS
// Mounts are further trees, each preopened under its own path after
// "/" (fd 4 onwards), as wasmtime's --dir host::guest does: a guest
// resolves an absolute path against the longest matching preopen.
Mounts []Mount
Stdin io.Reader
Stdout, Stderr io.Writer
// Now is the realtime clock (default time.Now).
Now func() time.Time
// Rand is the randomness source (default crypto/rand).
Rand io.Reader
// Net is the container's place on a network; nil means no network
// (sock_open fails with ENOTSUP).
Net netdriver.Endpoint
// Modules are the host modules served beside wasi_snapshot_preview1,
// in the order of the import table (Imports); an executor passes the
// same list it defined the imports from.
Modules []HostModule
// Caps are the capabilities the process was started with ("gpu").
Caps []string
// Parent is the process that started this one, if any.
Parent *Proc
// FDs, when set, is the initial descriptor table (a spawned child's,
// from CloneFDs) instead of stdio, "/" and the mounts.
FDs *FDTable
// Group is the container's process tree (pids, limits, kill); nil
// makes a group of this process alone.
Group *Group
// Spawner starts child processes (the executor's); nil refuses them.
Spawner Spawner
// Terminal describes the container's terminal, if any.
Terminal *Terminal
// MemoryLimitBytes is this process's linear-memory limit, reserved
// in the group's memory budget.
MemoryLimitBytes int64
// Admitted says Group.Admit already reserved this process's room (a
// Spawner sets it).
Admitted bool
// Label names the process's container (runtime.Spec.ID): host modules
// report it with what they show of the process (a surface's pane).
Label string
// OnEvent receives what host modules report with Proc.Emit (a GPU
// sanction); nil drops them. A child process reports through its parent.
OnEvent func(module, action string, attrs map[string]string)
}
Config is a process's world.
type ExitStatus ¶ added in v0.15.0
type ExitStatus struct {
// Code is the proc_exit code (the full u32; WASIX reports its low 16
// bits, so 0..255 survive), when Signal is 0.
Code uint32
// Signal is 9 (SIGKILL) for a process killed or timed out, 6
// (SIGABRT) for one that trapped, 0 for a normal exit.
Signal int
}
ExitStatus is how a process ended.
type FDOp ¶ added in v0.15.0
type FDOp struct {
Kind FDOpKind
FD, To uint32
Path string
OFlags uint32 // preview 1 oflags (creat, directory, excl, trunc)
FDFlags uint32 // preview 1 fdflags (append, nonblock)
Write bool
}
FDOp is one file action.
type FDOpKind ¶ added in v0.15.0
type FDOpKind int
FDOpKind is a file action applied to a child's table.
const ( // FDClose closes FD; closing a preopen is ignored (the child keeps // its capabilities). FDClose FDOpKind = iota // FDDup2 makes To a copy of FD (clearing To's cloexec); onto a // preopen it fails with EBADF. FDDup2 // FDOpen opens Path (absolute, or relative to the child's cwd) at FD // with OFlags, FDFlags and Write, like path_open. FDOpen // FDChdir sets the child's cwd to Path (resolved like FDOpen). FDChdir // FDFchdir sets the child's cwd to the directory open at FD. FDFchdir )
File actions, in posix_spawn's terms.
type FDTable ¶ added in v0.15.0
type FDTable struct {
Cwd string
// contains filtered or unexported fields
}
FDTable is a child's initial descriptor table and cwd, made by CloneFDs and handed to Spawner.Spawn.
type Func ¶
type Func struct {
Name string
Params string // one of I32/I64 per parameter
// NoResult is set for proc_exit; every other function returns an errno.
NoResult bool
}
Func describes one import.
type Group ¶ added in v0.15.0
type Group struct {
// contains filtered or unexported fields
}
Group is a container's process tree.
func NewGroup ¶ added in v0.15.0
func NewGroup(lim GroupLimits) *Group
NewGroup returns an empty group.
func (*Group) Admit ¶ added in v0.15.0
Admit reserves room for one more process of memory limit mem: EAGAIN past the process count or the spawn rate, ENOMEM past the memory budget, ESRCH once the group was killed. A successful Admit is undone by the process's Close, or by Cancel if it never starts.
func (*Group) Kill ¶ added in v0.15.0
func (g *Group) Kill()
Kill stops every process of the group and refuses new ones.
type GroupLimits ¶ added in v0.15.0
type GroupLimits struct {
// MaxProcs bounds the processes alive at once (default 64).
MaxProcs int
// MaxMemoryBytes bounds the sum of their memory limits (default: no
// bound beyond MaxProcs).
MaxMemoryBytes int64
// SpawnRate and SpawnBurst bound spawns per second, as a token bucket
// (defaults 32 per second, bursts of 64).
SpawnRate float64
SpawnBurst int
}
GroupLimits bound a container's processes. Zero values take the defaults.
type HostFunc ¶ added in v0.13.0
type HostFunc struct {
Name string
// Params has one of I32, I64, F32, F64 per parameter.
Params string
// Result is "" (no result) or one of I32, I64, F32, F64. The value is
// Result.Ret; an F32 or F64 travels as its IEEE-754 bits.
Result string
}
HostFunc is one function of a host module, with its core-wasm signature.
type HostModule ¶ added in v0.13.0
type HostModule interface {
// Module is the import module name, e.g. "wasi_ephemeral_nn".
Module() string
// Funcs lists the functions, in an order the module indexes by.
Funcs() []HostFunc
// Open makes the module's state for process p, at p's first call into
// it. It never fails: a process denied the module (no capability) gets
// an Instance that answers with the module's own error values.
Open(p *Proc) Instance
}
HostModule is an import module a guest may link against.
var WASIX HostModule = wasixModule{}
WASIX is the subset of WASIX (https://wasix.org) that lets a guest start and wait for other programs of its container, served as the host module "wasix_32v1": proc_spawn2, proc_spawn3, proc_join, proc_id, proc_parent, fd_pipe, tty_get and tty_set. Nothing else of WASIX (no fork, exec, threads or signals).
Signatures and layouts are wasix-libc's (api_wasix.h and __wasixlibc_real.c: every argument an i32, the errno as the result); the behaviour follows wasmer's implementation where it is sound, and departs from it where wasmer is wrong (see the go-wasmcontainers/shell repository's docs/REFERENCES.md): exit codes travel raw, fd flags are the descriptor's own, pipe ends have a filestat and a readiness.
type Import ¶ added in v0.13.0
Import is one entry of a process's import table.
func Imports ¶ added in v0.13.0
func Imports(mods []HostModule) ([]Import, error)
Imports returns the import table an executor defines and indexes by: Funcs first (wasi_snapshot_preview1, result I32 except proc_exit), then each module's functions in order. It refuses a malformed module: an empty or duplicate module name, PreviewModule itself, a duplicate function name, a bad type or more than MaxParams parameters.
type Instance ¶ added in v0.13.0
type Instance interface {
// Call runs function fn of Funcs with one value per parameter (I32
// in the low 32 bits, F32/F64 as bits).
Call(fn int, args []uint64, m Memory) Result
// Close releases the state when the process ends. It may run while a
// Wait the instance returned is still pending; a later Resume must
// then fail rather than touch released state.
Close()
}
Instance is a host module's state in one process.
type Memory ¶
Memory is the guest's linear memory. Read returns a slice valid until the next call on the Memory; both return false out of bounds.
type Mount ¶ added in v0.8.0
Mount is a tree preopened at Path; ReadOnly refuses every change made through it with EROFS.
type Proc ¶
type Proc struct {
// contains filtered or unexported fields
}
Proc is one guest process's WASI state.
func (*Proc) Call ¶
Call runs import number fn of Funcs with args (one per parameter, i32 values in the low 32 bits).
func (*Proc) CallImport ¶ added in v0.13.0
CallImport runs entry i of the table Imports(cfg.Modules) returned. Entries past Funcs go to their module's Instance, opened on first use.
func (*Proc) CapValue ¶ added in v0.32.0
CapValue returns the value of a capability granted as "name=value" (run --gpu --gpu-memory=SIZE grants "gpu-memory=BYTES"), and whether it was granted.
func (*Proc) ChildChanged ¶ added in v0.15.0
func (p *Proc) ChildChanged() <-chan struct{}
ChildChanged returns a channel closed at the next child exit (take it before scanning Children, so an exit in between is not missed).
func (*Proc) CloneFDs ¶ added in v0.15.0
CloneFDs copies this process's table (sockets excluded), applies ops in order, then drops every cloexec descriptor. cwd is the starting directory (the parent's PWD). It fails with the errno of the first operation that fails, releasing the partial copy.
func (*Proc) Close ¶ added in v0.10.0
func (p *Proc) Close()
Close releases what the process holds beyond its memory: its host modules' instances, its sockets and their goroutines. An executor calls it when the process ends.
func (*Proc) Dup ¶ added in v0.15.0
Dup copies fd to the lowest free descriptor at or above from (fd_dup, F_DUPFD); the copy's cloexec is clear.
func (*Proc) Dup2 ¶ added in v0.15.0
Dup2 makes to a copy of fd (closing what was at to); onto a preopen it fails with EBADF. The copy keeps fd's nonblock and clears cloexec.
func (*Proc) Emit ¶ added in v0.34.0
Emit reports an event of host module `module` about this process's container (the engine publishes it on its event bus and shows it in inspect). It never blocks the guest: the callback must return quickly.
func (*Proc) HasCap ¶ added in v0.13.0
HasCap reports whether the process was started with capability c (e.g. "gpu", from run --gpu).
func (*Proc) Instance ¶ added in v0.13.0
Instance returns the opened instance of the module named module in this process, or nil; a child's module may look up its parent's this way.
func (*Proc) IsTerminal ¶ added in v0.15.0
IsTerminal reports whether fd is the terminal: one of fds 0..2 marked TTY and still the descriptor the process started with there.
func (*Proc) LookPath ¶ added in v0.15.0
LookPath finds a command: name itself when it contains a "/" (against cwd), else each directory of pathList (colon-separated) as "<dir>/<name>" then "<dir>/<name>.wasm". It returns the first regular file, or ENOENT.
func (*Proc) Parent ¶ added in v0.13.0
Parent is the process that started this one (nil for a container's first process), so a module can share state across a process tree.
func (*Proc) Pid ¶ added in v0.15.0
Pid is this process's number in its container (1 for the first).
func (*Proc) Pipe ¶ added in v0.15.0
Pipe creates a pipe in this process: the read end at r, the write end at w (fd_pipe). It fails with EMFILE when the descriptor table is full.
func (*Proc) ReadModule ¶ added in v0.15.0
ReadModule reads the module a child is to run: an absolute guest path, resolved through this process's preopens. ENOENT when nothing is there, ENOEXEC when it is not a regular file holding a WebAssembly module, or holds more than MaxModuleBytes.
func (*Proc) Reap ¶ added in v0.15.0
Reap removes an ended child from Children; pid 0 reaps any ended one. It returns the child, nil with ECHILD when there is no such child, or nil with EAGAIN when none of them has ended yet.
func (*Proc) SetCloexec ¶ added in v0.15.0
SetCloexec sets or clears fd's close-on-spawn flag.
func (*Proc) Spawn ¶ added in v0.15.0
Spawn starts a child with the process's Spawner and records it.
func (*Proc) SpawnWait ¶ added in v0.15.0
SpawnWait is Spawn for a host call: the spawn (which may compile the module, and in the browser waits on the event loop) runs off the call, and the call resumes with then once the child runs or the spawn failed. A host function returns its result; it never blocks the engine.
type Realloc ¶ added in v0.13.0
Realloc asks the executor to allocate Size bytes aligned to Align in the guest, with the guest's cabi_realloc export (the canonical ABI's allocator), and to return Then(ptr) instead. The executor checks the block with CheckBlock first; a guest without the export, or a block outside its memory, traps the guest.
type Result ¶
type Result struct {
Errno uint32
// Sleep asks the host to block the guest this long before returning
// (poll_oneoff on clocks). The host may cut it short on a kill.
Sleep time.Duration
// Wait, when set, asks the host to block until Wait is closed, Sleep
// (if not zero) has passed, or the process is killed, and then to
// return what Resume returns instead (which may ask to wait again).
// The call itself never blocks: sockets wait this way.
Wait <-chan struct{}
Resume func(m Memory) Result
// Exit is set by proc_exit, with Code.
Exit bool
Code uint32
// Ret is a host-module function's result (HostFunc.Result); the
// wasi_snapshot_preview1 functions return Errno instead.
Ret uint64
// Realloc, when set, asks the host to allocate in the guest first
// (see Realloc); Wait and Realloc are never both set.
Realloc *Realloc
// Trap, when not empty, ends the guest with a trap of that message (a
// host module's answer to a call the canonical ABI says must trap).
Trap string
}
Result is what a call returned.
type SpawnSpec ¶ added in v0.15.0
type SpawnSpec struct {
// Path is the module's absolute guest path in the container.
Path string
// Argv is argv, argv[0] included (it need not be Path).
Argv []string
// Env is "KEY=value" entries.
Env []string
// FDs is the child's table and cwd (CloneFDs); Spawn takes it over,
// and releases it on failure.
FDs *FDTable
}
SpawnSpec is a child to start.
type Spawner ¶ added in v0.15.0
Spawner starts child processes. Spawn returns ENOENT (nothing at Path), ENOEXEC (not a WebAssembly module), EAGAIN or ENOMEM (a group limit), E2BIG (CheckArgs), ESRCH (the group was killed); the child is already running when it returns.
type Stdin ¶ added in v0.29.1
type Stdin struct {
// contains filtered or unexported fields
}
Stdin is a process's standard input as the host serves it: a goroutine reads the underlying reader into a bounded buffer, and fd_read and poll_oneoff never block on it — when nothing is there yet they ask the host to wait (Result.Wait), as for sockets and pipes. In the browser that keeps the engine's event loop free: the reader may well be fed by messages that loop delivers (an attach stream, a terminal), which a blocking Read there would never let in.
A process and the children it spawns share one Stdin (wrap once, with NewStdin, and hand the same value on), so no two goroutines compete for the underlying reader.
type Terminal ¶ added in v0.15.0
type Terminal struct {
// TTY says which of fds 0, 1, 2 are the terminal.
TTY [3]bool
// contains filtered or unexported fields
}
Terminal is a container's terminal (run -t, exec -it).
func NewTerminal ¶ added in v0.15.0
NewTerminal returns a terminal of the given size, echoing, in line mode.
func (*Terminal) OnMode ¶ added in v0.29.2
OnMode registers f to be called, outside the terminal's lock, after every SetMode. f must not block: SetMode runs in a guest's tty_set.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package hostmodtest is a host module for tests ("wctr_test"): the executors' tests run testdata/wasm/hostmod against it, natively and in the browser, so both sides of the seam are exercised by one guest.
|
Package hostmodtest is a host module for tests ("wctr_test"): the executors' tests run testdata/wasm/hostmod against it, natively and in the browser, so both sides of the seam are exercised by one guest. |