Debian Codegraph @

imports/wasi_snapshot_preview1/poll.go

raw symbols SCIP
1 package wasi_snapshot_preview1
2
3 import (
4 "context"
5 "time"
6
7 "github.com/tetratelabs/wazero/api"
8 "github.com/tetratelabs/wazero/experimental/sys"
9 internalsys "github.com/tetratelabs/wazero/internal/sys"
10 "github.com/tetratelabs/wazero/internal/wasip1"
11 "github.com/tetratelabs/wazero/internal/wasm"
12 )
13
14 // pollOneoff is the WASI function named PollOneoffName that concurrently
15 // polls for the occurrence of a set of events.
16 //
17 // # Parameters
18 //
19 // - in: pointer to the subscriptions (48 bytes each)
20 // - out: pointer to the resulting events (32 bytes each)
21 // - nsubscriptions: count of subscriptions, zero returns sys.EINVAL.
22 // - resultNevents: count of events.
23 //
24 // Result (Errno)
25 //
26 // The return value is 0 except the following error conditions:
27 // - sys.EINVAL: the parameters are invalid
28 // - sys.ENOTSUP: a parameters is valid, but not yet supported.
29 // - sys.EFAULT: there is not enough memory to read the subscriptions or
30 // write results.
31 //
32 // # Notes
33 //
34 // - Since the `out` pointer nests Errno, the result is always 0.
35 // - This is similar to `poll` in POSIX.
36 //
37 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#poll_oneoff
38 // See https://linux.die.net/man/3/poll
39 var pollOneoff = newHostFunc(
40 wasip1.PollOneoffName, pollOneoffFn,
41 []wasm.ValueType{i32, i32, i32, i32},
42 "in", "out", "nsubscriptions", "result.nevents",
43 )
44
45 type event struct {
46 eventType byte
47 userData []byte
48 errno wasip1.Errno
49 }
50
51 func pollOneoffFn(_ context.Context, mod api.Module, params []uint64) sys.Errno {
52 in := uint32(params[0])
53 out := uint32(params[1])
54 nsubscriptions := uint32(params[2])
55 resultNevents := uint32(params[3])
56
57 if nsubscriptions == 0 {
58 return sys.EINVAL
59 }
60
61 mem := mod.Memory()
62
63 // Ensure capacity prior to the read loop to reduce error handling.
64 inBuf, ok := mem.Read(in, nsubscriptions*48)
65 if !ok {
66 return sys.EFAULT
67 }
68 outBuf, ok := mem.Read(out, nsubscriptions*32)
69 // zero-out all buffer before writing
70 clear(outBuf)
71
72 if !ok {
73 return sys.EFAULT
74 }
75
76 // Eagerly write the number of events which will equal subscriptions unless
77 // there's a fault in parsing (not processing).
78 if !mod.Memory().WriteUint32Le(resultNevents, nsubscriptions) {
79 return sys.EFAULT
80 }
81
82 // Loop through all subscriptions and write their output.
83
84 // Extract FS context, used in the body of the for loop for FS access.
85 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
86 // Slice of events that are processed out of the loop (blocking stdin subscribers).
87 var blockingStdinSubs []*event
88 // The timeout is initialized at max Duration, the loop will find the minimum.
89 var timeout time.Duration = 1<<63 - 1
90 // Count of all the subscriptions that have been already written back to outBuf.
91 // nevents*32 returns at all times the offset where the next event should be written:
92 // this way we ensure that there are no gaps between records.
93 nevents := uint32(0)
94
95 // Layout is subscription_u: Union
96 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#subscription_u
97 for i := uint32(0); i < nsubscriptions; i++ {
98 inOffset := i * 48
99 outOffset := nevents * 32
100
101 eventType := inBuf[inOffset+8] // +8 past userdata
102 // +8 past userdata +8 contents_offset
103 argBuf := inBuf[inOffset+8+8:]
104 userData := inBuf[inOffset : inOffset+8]
105
106 evt := &event{
107 eventType: eventType,
108 userData: userData,
109 errno: wasip1.ErrnoSuccess,
110 }
111
112 switch eventType {
113 case wasip1.EventTypeClock: // handle later
114 newTimeout, err := processClockEvent(argBuf)
115 if err != 0 {
116 return err
117 }
118 // Min timeout.
119 if newTimeout < timeout {
120 timeout = newTimeout
121 }
122 // Ack the clock event to the outBuf.
123 writeEvent(outBuf[outOffset:], evt)
124 nevents++
125 case wasip1.EventTypeFdRead:
126 fd := int32(le.Uint32(argBuf))
127 if fd < 0 {
128 return sys.EBADF
129 }
130 if file, ok := fsc.LookupFile(fd); !ok {
131 evt.errno = wasip1.ErrnoBadf
132 writeEvent(outBuf[outOffset:], evt)
133 nevents++
134 } else if fd != internalsys.FdStdin && isNonblock(file.File) {
135 writeEvent(outBuf[outOffset:], evt)
136 nevents++
137 } else {
138 // if the fd is Stdin, and it is in blocking mode,
139 // do not ack yet, append to a slice for delayed evaluation.
140 blockingStdinSubs = append(blockingStdinSubs, evt)
141 }
142 case wasip1.EventTypeFdWrite:
143 fd := int32(le.Uint32(argBuf))
144 if fd < 0 {
145 return sys.EBADF
146 }
147 if _, ok := fsc.LookupFile(fd); ok {
148 evt.errno = wasip1.ErrnoNotsup
149 } else {
150 evt.errno = wasip1.ErrnoBadf
151 }
152 nevents++
153 writeEvent(outBuf[outOffset:], evt)
154 default:
155 return sys.EINVAL
156 }
157 }
158
159 sysCtx := mod.(*wasm.ModuleInstance).Sys
160 if nevents == nsubscriptions {
161 // We already wrote back all the results. We already wrote this number
162 // earlier to offset `resultNevents`.
163 // We only need to observe the timeout (nonzero if there are clock subscriptions)
164 // and return.
165 if timeout > 0 {
166 sysCtx.Nanosleep(int64(timeout))
167 }
168 return 0
169 }
170
171 // If there are blocking stdin subscribers, check for data with given timeout.
172 stdin, ok := fsc.LookupFile(internalsys.FdStdin)
173 if !ok {
174 return sys.EBADF
175 }
176
177 // Wait for the timeout to expire, or for some data to become available on Stdin.
178 if p, ok := stdin.File.(sys.Pollable); ok {
179 if stdinReady, errno := p.Poll(sys.POLLIN, int32(timeout.Milliseconds())); errno != 0 {
180 return errno
181 } else if stdinReady {
182 // stdin has data ready to for reading, write back all the events
183 for i := range blockingStdinSubs {
184 evt := blockingStdinSubs[i]
185 evt.errno = 0
186 writeEvent(outBuf[nevents*32:], evt)
187 nevents++
188 }
189 }
190 }
191
192 if nevents != nsubscriptions {
193 if !mod.Memory().WriteUint32Le(resultNevents, nevents) {
194 return sys.EFAULT
195 }
196 }
197
198 return 0
199 }
200
201 // processClockEvent supports only relative name events, as that's what's used
202 // to implement sleep in various compilers including Rust, Zig and TinyGo.
203 func processClockEvent(inBuf []byte) (time.Duration, sys.Errno) {
204 _ /* ID */ = le.Uint32(inBuf[0:8]) // See below
205 timeout := le.Uint64(inBuf[8:16]) // nanos if relative
206 _ /* precision */ = le.Uint64(inBuf[16:24]) // Unused
207 flags := le.Uint16(inBuf[24:32])
208
209 var err sys.Errno
210 // subclockflags has only one flag defined: subscription_clock_abstime
211 switch flags {
212 case 0: // relative time
213 case 1: // subscription_clock_abstime
214 err = sys.ENOTSUP
215 default: // subclockflags has only one flag defined.
216 err = sys.EINVAL
217 }
218
219 if err != 0 {
220 return 0, err
221 } else {
222 // https://linux.die.net/man/3/clock_settime says relative timers are
223 // unaffected. Since this function only supports relative timeout, we can
224 // skip name ID validation and use a single sleep function.
225
226 return time.Duration(timeout), 0
227 }
228 }
229
230 // isNonblock returns true if the file implements PollableFile and is in
231 // non-blocking mode.
232 func isNonblock(f sys.File) bool {
233 if pf, ok := f.(sys.PollableFile); ok {
234 return pf.IsNonblock()
235 }
236 return false
237 }
238
239 // writeEvent writes the event corresponding to the processed subscription.
240 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-event-struct
241 func writeEvent(outBuf []byte, evt *event) {
242 copy(outBuf, evt.userData) // userdata
243 outBuf[8] = byte(evt.errno) // uint16, but safe as < 255
244 outBuf[9] = 0
245 le.PutUint32(outBuf[10:], uint32(evt.eventType))
246 // TODO: When FD events are supported, write outOffset+16
247 }