Debian Codegraph @

imports/wasi_snapshot_preview1/fs.go

raw symbols SCIP
1 package wasi_snapshot_preview1
2
3 import (
4 "context"
5 "io"
6 "io/fs"
7 "math"
8 "path"
9 "strings"
10 "unsafe"
11
12 "github.com/tetratelabs/wazero/api"
13 experimentalsys "github.com/tetratelabs/wazero/experimental/sys"
14 socketapi "github.com/tetratelabs/wazero/internal/sock"
15 "github.com/tetratelabs/wazero/internal/sys"
16 "github.com/tetratelabs/wazero/internal/wasip1"
17 "github.com/tetratelabs/wazero/internal/wasm"
18 sysapi "github.com/tetratelabs/wazero/sys"
19 )
20
21 // fdAdvise is the WASI function named FdAdviseName which provides file
22 // advisory information on a file descriptor.
23 //
24 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_advisefd-fd-offset-filesize-len-filesize-advice-advice---errno
25 var fdAdvise = newHostFunc(
26 wasip1.FdAdviseName, fdAdviseFn,
27 []wasm.ValueType{i32, i64, i64, i32},
28 "fd", "offset", "len", "advice",
29 )
30
31 func fdAdviseFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
32 fd := int32(params[0])
33 _ = params[1]
34 _ = params[2]
35 advice := byte(params[3])
36 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
37
38 _, ok := fsc.LookupFile(fd)
39 if !ok {
40 return experimentalsys.EBADF
41 }
42
43 switch advice {
44 case wasip1.FdAdviceNormal,
45 wasip1.FdAdviceSequential,
46 wasip1.FdAdviceRandom,
47 wasip1.FdAdviceWillNeed,
48 wasip1.FdAdviceDontNeed,
49 wasip1.FdAdviceNoReuse:
50 default:
51 return experimentalsys.EINVAL
52 }
53
54 // FdAdvice corresponds to posix_fadvise, but it can only be supported on linux.
55 // However, the purpose of the call is just to do best-effort optimization on OS kernels,
56 // so just making this noop rather than returning NoSup error makes sense and doesn't affect
57 // the semantics of Wasm applications.
58 // TODO: invoke posix_fadvise on linux, and partially on darwin.
59 // - https://gitlab.com/cznic/fileutil/-/blob/v1.1.2/fileutil_linux.go#L87-95
60 // - https://github.com/bytecodealliance/system-interface/blob/62b97f9776b86235f318c3a6e308395a1187439b/src/fs/file_io_ext.rs#L430-L442
61 return 0
62 }
63
64 // fdAllocate is the WASI function named FdAllocateName which forces the
65 // allocation of space in a file.
66 //
67 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_allocatefd-fd-offset-filesize-len-filesize---errno
68 var fdAllocate = newHostFunc(
69 wasip1.FdAllocateName, fdAllocateFn,
70 []wasm.ValueType{i32, i64, i64},
71 "fd", "offset", "len",
72 )
73
74 func fdAllocateFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
75 fd := int32(params[0])
76 offset := params[1]
77 length := params[2]
78
79 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
80 f, ok := fsc.LookupFile(fd)
81 if !ok {
82 return experimentalsys.EBADF
83 }
84
85 tail := int64(offset + length)
86 if tail < 0 {
87 return experimentalsys.EINVAL
88 }
89
90 st, errno := f.File.Stat()
91 if errno != 0 {
92 return errno
93 }
94
95 if st.Size >= tail {
96 return 0 // We already have enough space.
97 }
98
99 return f.File.Truncate(tail)
100 }
101
102 // fdClose is the WASI function named FdCloseName which closes a file
103 // descriptor.
104 //
105 // # Parameters
106 //
107 // - fd: file descriptor to close
108 //
109 // Result (Errno)
110 //
111 // The return value is 0 except the following error conditions:
112 // - sys.EBADF: the fd was not open.
113 // - sys.ENOTSUP: the fs was a pre-open
114 //
115 // Note: This is similar to `close` in POSIX.
116 // See https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_close
117 // and https://linux.die.net/man/3/close
118 var fdClose = newHostFunc(wasip1.FdCloseName, fdCloseFn, []wasm.ValueType{i32}, "fd")
119
120 func fdCloseFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
121 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
122 fd := int32(params[0])
123
124 return fsc.CloseFile(fd)
125 }
126
127 // fdDatasync is the WASI function named FdDatasyncName which synchronizes
128 // the data of a file to disk.
129 //
130 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_datasyncfd-fd---errno
131 var fdDatasync = newHostFunc(wasip1.FdDatasyncName, fdDatasyncFn, []wasm.ValueType{i32}, "fd")
132
133 func fdDatasyncFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
134 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
135 fd := int32(params[0])
136
137 // Check to see if the file descriptor is available
138 if f, ok := fsc.LookupFile(fd); !ok {
139 return experimentalsys.EBADF
140 } else {
141 return f.File.Datasync()
142 }
143 }
144
145 // fdFdstatGet is the WASI function named FdFdstatGetName which returns the
146 // attributes of a file descriptor.
147 //
148 // # Parameters
149 //
150 // - fd: file descriptor to get the fdstat attributes data
151 // - resultFdstat: offset to write the result fdstat data
152 //
153 // Result (Errno)
154 //
155 // The return value is 0 except the following error conditions:
156 // - sys.EBADF: `fd` is invalid
157 // - sys.EFAULT: `resultFdstat` points to an offset out of memory
158 //
159 // fdstat byte layout is 24-byte size, with the following fields:
160 // - fs_filetype 1 byte: the file type
161 // - fs_flags 2 bytes: the file descriptor flag
162 // - 5 pad bytes
163 // - fs_right_base 8 bytes: ignored as rights were removed from WASI.
164 // - fs_right_inheriting 8 bytes: ignored as rights were removed from WASI.
165 //
166 // For example, with a file corresponding with `fd` was a directory (=3) opened
167 // with `fd_read` right (=1) and no fs_flags (=0), parameter resultFdstat=1,
168 // this function writes the below to api.Memory:
169 //
170 // uint16le padding uint64le uint64le
171 // uint8 --+ +--+ +-----------+ +--------------------+ +--------------------+
172 // | | | | | | | | |
173 // []byte{?, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}
174 // resultFdstat --^ ^-- fs_flags ^-- fs_right_base ^-- fs_right_inheriting
175 // |
176 // +-- fs_filetype
177 //
178 // Note: fdFdstatGet returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as
179 // well as additional fields.
180 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fdstat
181 // and https://linux.die.net/man/3/fsync
182 var fdFdstatGet = newHostFunc(wasip1.FdFdstatGetName, fdFdstatGetFn, []wasm.ValueType{i32, i32}, "fd", "result.stat")
183
184 // fdFdstatGetFn cannot currently use proxyResultParams because fdstat is larger
185 // than api.ValueTypeI64 (i64 == 8 bytes, but fdstat is 24).
186 func fdFdstatGetFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
187 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
188
189 fd, resultFdstat := int32(params[0]), uint32(params[1])
190
191 // Ensure we can write the fdstat
192 buf, ok := mod.Memory().Read(resultFdstat, 24)
193 if !ok {
194 return experimentalsys.EFAULT
195 }
196
197 var fdflags uint16
198 var st sysapi.Stat_t
199 var errno experimentalsys.Errno
200 f, ok := fsc.LookupFile(fd)
201 if !ok {
202 return experimentalsys.EBADF
203 } else if st, errno = f.File.Stat(); errno != 0 {
204 return errno
205 } else if f.File.IsAppend() {
206 fdflags |= wasip1.FD_APPEND
207 }
208
209 if isNonblock(f.File) {
210 fdflags |= wasip1.FD_NONBLOCK
211 }
212
213 var fsRightsBase uint32
214 var fsRightsInheriting uint32
215 fileType := getExtendedWasiFiletype(f.File, st.Mode)
216
217 switch fileType {
218 case wasip1.FILETYPE_DIRECTORY:
219 // To satisfy wasi-testsuite, we must advertise that directories cannot
220 // be given seek permission (RIGHT_FD_SEEK).
221 fsRightsBase = dirRightsBase
222 fsRightsInheriting = fileRightsBase | dirRightsBase
223 case wasip1.FILETYPE_CHARACTER_DEVICE:
224 // According to wasi-libc,
225 // > A tty is a character device that we can't seek or tell on.
226 // See https://github.com/WebAssembly/wasi-libc/blob/a6f871343313220b76009827ed0153586361c0d5/libc-bottom-half/sources/isatty.c#L13-L18
227 fsRightsBase = fileRightsBase &^ wasip1.RIGHT_FD_SEEK &^ wasip1.RIGHT_FD_TELL
228 default:
229 fsRightsBase = fileRightsBase
230 }
231
232 writeFdstat(buf, fileType, fdflags, fsRightsBase, fsRightsInheriting)
233 return 0
234 }
235
236 // isPreopenedStdio returns true if the FD is sys.FdStdin, sys.FdStdout or
237 // sys.FdStderr and pre-opened. This double check is needed in case the guest
238 // closes stdin and re-opens it with a random alternative file.
239 //
240 // Currently, we only support non-blocking mode for standard I/O streams.
241 // Non-blocking mode is rarely supported for regular files, and we don't
242 // yet have support for sockets, so we make a special case.
243 //
244 // Note: this to get or set FD_NONBLOCK, but skip FD_APPEND. Our current
245 // implementation can't set FD_APPEND, without re-opening files. As stdio are
246 // pre-opened, we don't know how to re-open them, neither should we close the
247 // underlying file. Later, we could add support for setting FD_APPEND, similar
248 // to SetNonblock.
249 func isPreopenedStdio(fd int32, f *sys.FileEntry) bool {
250 return fd <= sys.FdStderr && f.IsPreopen
251 }
252
253 const fileRightsBase = wasip1.RIGHT_FD_DATASYNC |
254 wasip1.RIGHT_FD_READ |
255 wasip1.RIGHT_FD_SEEK |
256 wasip1.RIGHT_FDSTAT_SET_FLAGS |
257 wasip1.RIGHT_FD_SYNC |
258 wasip1.RIGHT_FD_TELL |
259 wasip1.RIGHT_FD_WRITE |
260 wasip1.RIGHT_FD_ADVISE |
261 wasip1.RIGHT_FD_ALLOCATE |
262 wasip1.RIGHT_FD_FILESTAT_GET |
263 wasip1.RIGHT_FD_FILESTAT_SET_SIZE |
264 wasip1.RIGHT_FD_FILESTAT_SET_TIMES |
265 wasip1.RIGHT_POLL_FD_READWRITE
266
267 const dirRightsBase = wasip1.RIGHT_FD_DATASYNC |
268 wasip1.RIGHT_FDSTAT_SET_FLAGS |
269 wasip1.RIGHT_FD_SYNC |
270 wasip1.RIGHT_PATH_CREATE_DIRECTORY |
271 wasip1.RIGHT_PATH_CREATE_FILE |
272 wasip1.RIGHT_PATH_LINK_SOURCE |
273 wasip1.RIGHT_PATH_LINK_TARGET |
274 wasip1.RIGHT_PATH_OPEN |
275 wasip1.RIGHT_FD_READDIR |
276 wasip1.RIGHT_PATH_READLINK |
277 wasip1.RIGHT_PATH_RENAME_SOURCE |
278 wasip1.RIGHT_PATH_RENAME_TARGET |
279 wasip1.RIGHT_PATH_FILESTAT_GET |
280 wasip1.RIGHT_PATH_FILESTAT_SET_SIZE |
281 wasip1.RIGHT_PATH_FILESTAT_SET_TIMES |
282 wasip1.RIGHT_FD_FILESTAT_GET |
283 wasip1.RIGHT_FD_FILESTAT_SET_TIMES |
284 wasip1.RIGHT_PATH_SYMLINK |
285 wasip1.RIGHT_PATH_REMOVE_DIRECTORY |
286 wasip1.RIGHT_PATH_UNLINK_FILE
287
288 func writeFdstat(buf []byte, fileType uint8, fdflags uint16, fsRightsBase, fsRightsInheriting uint32) {
289 b := (*[24]byte)(buf)
290 le.PutUint16(b[0:], uint16(fileType))
291 le.PutUint16(b[2:], fdflags)
292 le.PutUint32(b[4:], 0)
293 le.PutUint64(b[8:], uint64(fsRightsBase))
294 le.PutUint64(b[16:], uint64(fsRightsInheriting))
295 }
296
297 // fdFdstatSetFlags is the WASI function named FdFdstatSetFlagsName which
298 // adjusts the flags associated with a file descriptor.
299 var fdFdstatSetFlags = newHostFunc(wasip1.FdFdstatSetFlagsName, fdFdstatSetFlagsFn, []wasm.ValueType{i32, i32}, "fd", "flags")
300
301 func fdFdstatSetFlagsFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
302 fd, wasiFlag := int32(params[0]), uint16(params[1])
303 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
304
305 // Currently we only support APPEND and NONBLOCK.
306 if wasip1.FD_DSYNC&wasiFlag != 0 || wasip1.FD_RSYNC&wasiFlag != 0 || wasip1.FD_SYNC&wasiFlag != 0 {
307 return experimentalsys.EINVAL
308 }
309
310 if f, ok := fsc.LookupFile(fd); !ok {
311 return experimentalsys.EBADF
312 } else {
313 nonblock := wasip1.FD_NONBLOCK&wasiFlag != 0
314 if pf, ok := f.File.(experimentalsys.PollableFile); ok {
315 if errno := pf.SetNonblock(nonblock); errno != 0 {
316 return errno
317 }
318 } else if isDir, errno := f.File.IsDir(); errno == 0 && isDir {
319 return experimentalsys.EISDIR
320 } else if nonblock {
321 return experimentalsys.ENOSYS
322 }
323 if stat, err := f.File.Stat(); err == 0 && stat.Mode.IsRegular() {
324 // For normal files, proceed to apply an append flag.
325 append := wasip1.FD_APPEND&wasiFlag != 0
326 return f.File.SetAppend(append)
327 }
328 }
329
330 return 0
331 }
332
333 // fdFdstatSetRights will not be implemented as rights were removed from WASI.
334 //
335 // See https://github.com/bytecodealliance/wasmtime/pull/4666
336 var fdFdstatSetRights = stubFunction(
337 wasip1.FdFdstatSetRightsName,
338 []wasm.ValueType{i32, i64, i64},
339 "fd", "fs_rights_base", "fs_rights_inheriting",
340 )
341
342 // fdFilestatGet is the WASI function named FdFilestatGetName which returns
343 // the stat attributes of an open file.
344 //
345 // # Parameters
346 //
347 // - fd: file descriptor to get the filestat attributes data for
348 // - resultFilestat: offset to write the result filestat data
349 //
350 // Result (Errno)
351 //
352 // The return value is 0 except the following error conditions:
353 // - sys.EBADF: `fd` is invalid
354 // - sys.EIO: could not stat `fd` on filesystem
355 // - sys.EFAULT: `resultFilestat` points to an offset out of memory
356 //
357 // filestat byte layout is 64-byte size, with the following fields:
358 // - dev 8 bytes: the device ID of device containing the file
359 // - ino 8 bytes: the file serial number
360 // - filetype 1 byte: the type of the file
361 // - 7 pad bytes
362 // - nlink 8 bytes: number of hard links to the file
363 // - size 8 bytes: for regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link
364 // - atim 8 bytes: ast data access timestamp
365 // - mtim 8 bytes: last data modification timestamp
366 // - ctim 8 bytes: ast file status change timestamp
367 //
368 // For example, with a regular file this function writes the below to api.Memory:
369 //
370 // uint8 --+
371 // uint64le uint64le | padding uint64le uint64le uint64le uint64le uint64le
372 // +--------------------+ +--------------------+ | +-----------------+ +--------------------+ +-----------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+
373 // | | | | | | | | | | | | | | | | |
374 // []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 117, 80, 0, 0, 0, 0, 0, 0, 160, 153, 212, 128, 110, 221, 35, 23, 160, 153, 212, 128, 110, 221, 35, 23, 160, 153, 212, 128, 110, 221, 35, 23}
375 // resultFilestat ^-- dev ^-- ino ^ ^-- nlink ^-- size ^-- atim ^-- mtim ^-- ctim
376 // |
377 // +-- filetype
378 //
379 // The following properties of filestat are not implemented:
380 // - dev: not supported by Golang FS
381 // - ino: not supported by Golang FS
382 // - nlink: not supported by Golang FS, we use 1
383 // - atime: not supported by Golang FS, we use mtim for this
384 // - ctim: not supported by Golang FS, we use mtim for this
385 //
386 // Note: This is similar to `fstat` in POSIX.
387 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_filestat_getfd-fd---errno-filestat
388 // and https://linux.die.net/man/3/fstat
389 var fdFilestatGet = newHostFunc(wasip1.FdFilestatGetName, fdFilestatGetFn, []wasm.ValueType{i32, i32}, "fd", "result.filestat")
390
391 // fdFilestatGetFn cannot currently use proxyResultParams because filestat is
392 // larger than api.ValueTypeI64 (i64 == 8 bytes, but filestat is 64).
393 func fdFilestatGetFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
394 return fdFilestatGetFunc(mod, int32(params[0]), uint32(params[1]))
395 }
396
397 func fdFilestatGetFunc(mod api.Module, fd int32, resultBuf uint32) experimentalsys.Errno {
398 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
399
400 // Ensure we can write the filestat
401 buf, ok := mod.Memory().Read(resultBuf, 64)
402 if !ok {
403 return experimentalsys.EFAULT
404 }
405
406 f, ok := fsc.LookupFile(fd)
407 if !ok {
408 return experimentalsys.EBADF
409 }
410
411 st, errno := f.File.Stat()
412 if errno != 0 {
413 return errno
414 }
415
416 filetype := getExtendedWasiFiletype(f.File, st.Mode)
417 return writeFilestat(buf, &st, filetype)
418 }
419
420 func getExtendedWasiFiletype(file experimentalsys.File, fm fs.FileMode) (ftype uint8) {
421 ftype = getWasiFiletype(fm)
422 if ftype == wasip1.FILETYPE_UNKNOWN {
423 if _, ok := file.(socketapi.TCPSock); ok {
424 ftype = wasip1.FILETYPE_SOCKET_STREAM
425 } else if _, ok = file.(socketapi.TCPConn); ok {
426 ftype = wasip1.FILETYPE_SOCKET_STREAM
427 }
428 }
429 return
430 }
431
432 func getWasiFiletype(fm fs.FileMode) uint8 {
433 switch {
434 case fm.IsRegular():
435 return wasip1.FILETYPE_REGULAR_FILE
436 case fm.IsDir():
437 return wasip1.FILETYPE_DIRECTORY
438 case fm&fs.ModeSymlink != 0:
439 return wasip1.FILETYPE_SYMBOLIC_LINK
440 case fm&fs.ModeDevice != 0:
441 // Unlike ModeDevice and ModeCharDevice, FILETYPE_CHARACTER_DEVICE and
442 // FILETYPE_BLOCK_DEVICE are set mutually exclusively.
443 if fm&fs.ModeCharDevice != 0 {
444 return wasip1.FILETYPE_CHARACTER_DEVICE
445 }
446 return wasip1.FILETYPE_BLOCK_DEVICE
447 default: // unknown
448 return wasip1.FILETYPE_UNKNOWN
449 }
450 }
451
452 func writeFilestat(buf []byte, st *sysapi.Stat_t, ftype uint8) (errno experimentalsys.Errno) {
453 le.PutUint64(buf, st.Dev)
454 le.PutUint64(buf[8:], st.Ino)
455 le.PutUint64(buf[16:], uint64(ftype))
456 le.PutUint64(buf[24:], st.Nlink)
457 le.PutUint64(buf[32:], uint64(st.Size))
458 le.PutUint64(buf[40:], uint64(st.Atim))
459 le.PutUint64(buf[48:], uint64(st.Mtim))
460 le.PutUint64(buf[56:], uint64(st.Ctim))
461 return
462 }
463
464 // fdFilestatSetSize is the WASI function named FdFilestatSetSizeName which
465 // adjusts the size of an open file.
466 //
467 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_filestat_set_sizefd-fd-size-filesize---errno
468 var fdFilestatSetSize = newHostFunc(wasip1.FdFilestatSetSizeName, fdFilestatSetSizeFn, []wasm.ValueType{i32, i64}, "fd", "size")
469
470 func fdFilestatSetSizeFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
471 fd := int32(params[0])
472 size := int64(params[1])
473
474 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
475
476 // Check to see if the file descriptor is available
477 if f, ok := fsc.LookupFile(fd); !ok {
478 return experimentalsys.EBADF
479 } else {
480 return f.File.Truncate(size)
481 }
482 }
483
484 // fdFilestatSetTimes is the WASI function named functionFdFilestatSetTimes
485 // which adjusts the times of an open file.
486 //
487 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_filestat_set_timesfd-fd-atim-timestamp-mtim-timestamp-fst_flags-fstflags---errno
488 var fdFilestatSetTimes = newHostFunc(
489 wasip1.FdFilestatSetTimesName, fdFilestatSetTimesFn,
490 []wasm.ValueType{i32, i64, i64, i32},
491 "fd", "atim", "mtim", "fst_flags",
492 )
493
494 func fdFilestatSetTimesFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
495 fd := int32(params[0])
496 atim := int64(params[1])
497 mtim := int64(params[2])
498 fstFlags := uint16(params[3])
499
500 sys := mod.(*wasm.ModuleInstance).Sys
501 fsc := sys.FS()
502
503 f, ok := fsc.LookupFile(fd)
504 if !ok {
505 return experimentalsys.EBADF
506 }
507
508 atim, mtim, errno := toTimes(sys.WalltimeNanos, atim, mtim, fstFlags)
509 if errno != 0 {
510 return errno
511 }
512
513 // Try to update the file timestamps by file-descriptor.
514 errno = f.File.Utimens(atim, mtim)
515
516 // Fall back to path based, despite it being less precise.
517 switch errno {
518 case experimentalsys.EPERM, experimentalsys.ENOSYS:
519 errno = f.FS.Utimens(f.Name, atim, mtim)
520 }
521
522 return errno
523 }
524
525 func toTimes(walltime func() int64, atim, mtim int64, fstFlags uint16) (int64, int64, experimentalsys.Errno) {
526 // times[0] == atim, times[1] == mtim
527
528 var nowTim int64
529
530 // coerce atim into a timespec
531 if set, now := fstFlags&wasip1.FstflagsAtim != 0, fstFlags&wasip1.FstflagsAtimNow != 0; set && now {
532 return 0, 0, experimentalsys.EINVAL
533 } else if set {
534 // atim is already correct
535 } else if now {
536 nowTim = walltime()
537 atim = nowTim
538 } else {
539 atim = experimentalsys.UTIME_OMIT
540 }
541
542 // coerce mtim into a timespec
543 if set, now := fstFlags&wasip1.FstflagsMtim != 0, fstFlags&wasip1.FstflagsMtimNow != 0; set && now {
544 return 0, 0, experimentalsys.EINVAL
545 } else if set {
546 // mtim is already correct
547 } else if now {
548 if nowTim != 0 {
549 mtim = nowTim
550 } else {
551 mtim = walltime()
552 }
553 } else {
554 mtim = experimentalsys.UTIME_OMIT
555 }
556 return atim, mtim, 0
557 }
558
559 // fdPread is the WASI function named FdPreadName which reads from a file
560 // descriptor, without using and updating the file descriptor's offset.
561 //
562 // Except for handling offset, this implementation is identical to fdRead.
563 //
564 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_preadfd-fd-iovs-iovec_array-offset-filesize---errno-size
565 var fdPread = newHostFunc(
566 wasip1.FdPreadName, fdPreadFn,
567 []wasm.ValueType{i32, i32, i32, i64, i32},
568 "fd", "iovs", "iovs_len", "offset", "result.nread",
569 )
570
571 func fdPreadFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
572 return fdReadOrPread(mod, params, true)
573 }
574
575 // fdPrestatGet is the WASI function named FdPrestatGetName which returns
576 // the prestat data of a file descriptor.
577 //
578 // # Parameters
579 //
580 // - fd: file descriptor to get the prestat
581 // - resultPrestat: offset to write the result prestat data
582 //
583 // Result (Errno)
584 //
585 // The return value is 0 except the following error conditions:
586 // - sys.EBADF: `fd` is invalid or the `fd` is not a pre-opened directory
587 // - sys.EFAULT: `resultPrestat` points to an offset out of memory
588 //
589 // prestat byte layout is 8 bytes, beginning with an 8-bit tag and 3 pad bytes.
590 // The only valid tag is `prestat_dir`, which is tag zero. This simplifies the
591 // byte layout to 4 empty bytes followed by the uint32le encoded path length.
592 //
593 // For example, the directory name corresponding with `fd` was "/tmp" and
594 // parameter resultPrestat=1, this function writes the below to api.Memory:
595 //
596 // padding uint32le
597 // uint8 --+ +-----+ +--------+
598 // | | | | |
599 // []byte{?, 0, 0, 0, 0, 4, 0, 0, 0, ?}
600 // resultPrestat --^ ^
601 // tag --+ |
602 // +-- size in bytes of the string "/tmp"
603 //
604 // See fdPrestatDirName and
605 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#prestat
606 var fdPrestatGet = newHostFunc(wasip1.FdPrestatGetName, fdPrestatGetFn, []wasm.ValueType{i32, i32}, "fd", "result.prestat")
607
608 func fdPrestatGetFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
609 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
610 fd, resultPrestat := int32(params[0]), uint32(params[1])
611
612 name, errno := preopenPath(fsc, fd)
613 if errno != 0 {
614 return errno
615 }
616
617 // Upper 32-bits are zero because...
618 // * Zero-value 8-bit tag, and 3-byte zero-value padding
619 prestat := uint64(len(name)) << 32
620 if !mod.Memory().WriteUint64Le(resultPrestat, prestat) {
621 return experimentalsys.EFAULT
622 }
623 return 0
624 }
625
626 // fdPrestatDirName is the WASI function named FdPrestatDirNameName which
627 // returns the path of the pre-opened directory of a file descriptor.
628 //
629 // # Parameters
630 //
631 // - fd: file descriptor to get the path of the pre-opened directory
632 // - path: offset in api.Memory to write the result path
633 // - pathLen: count of bytes to write to `path`
634 // - This should match the uint32le fdPrestatGet writes to offset
635 // `resultPrestat`+4
636 //
637 // Result (Errno)
638 //
639 // The return value is 0 except the following error conditions:
640 // - sys.EBADF: `fd` is invalid
641 // - sys.EFAULT: `path` points to an offset out of memory
642 // - sys.ENAMETOOLONG: `pathLen` is longer than the actual length of the result
643 //
644 // For example, the directory name corresponding with `fd` was "/tmp" and
645 // # Parameters path=1 pathLen=4 (correct), this function will write the below to
646 // api.Memory:
647 //
648 // pathLen
649 // +--------------+
650 // | |
651 // []byte{?, '/', 't', 'm', 'p', ?}
652 // path --^
653 //
654 // See fdPrestatGet
655 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_prestat_dir_name
656 var fdPrestatDirName = newHostFunc(
657 wasip1.FdPrestatDirNameName, fdPrestatDirNameFn,
658 []wasm.ValueType{i32, i32, i32},
659 "fd", "result.path", "result.path_len",
660 )
661
662 func fdPrestatDirNameFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
663 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
664 fd, path, pathLen := int32(params[0]), uint32(params[1]), uint32(params[2])
665
666 name, errno := preopenPath(fsc, fd)
667 if errno != 0 {
668 return errno
669 }
670
671 // Some runtimes may have another semantics. See /RATIONALE.md
672 if uint32(len(name)) < pathLen {
673 return experimentalsys.ENAMETOOLONG
674 }
675
676 if !mod.Memory().Write(path, []byte(name)[:pathLen]) {
677 return experimentalsys.EFAULT
678 }
679 return 0
680 }
681
682 // fdPwrite is the WASI function named FdPwriteName which writes to a file
683 // descriptor, without using and updating the file descriptor's offset.
684 //
685 // Except for handling offset, this implementation is identical to fdWrite.
686 //
687 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_pwritefd-fd-iovs-ciovec_array-offset-filesize---errno-size
688 var fdPwrite = newHostFunc(
689 wasip1.FdPwriteName, fdPwriteFn,
690 []wasm.ValueType{i32, i32, i32, i64, i32},
691 "fd", "iovs", "iovs_len", "offset", "result.nwritten",
692 )
693
694 func fdPwriteFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
695 return fdWriteOrPwrite(mod, params, true)
696 }
697
698 // fdRead is the WASI function named FdReadName which reads from a file
699 // descriptor.
700 //
701 // # Parameters
702 //
703 // - fd: an opened file descriptor to read data from
704 // - iovs: offset in api.Memory to read offset, size pairs representing where
705 // to write file data
706 // - Both offset and length are encoded as uint32le
707 // - iovsCount: count of memory offset, size pairs to read sequentially
708 // starting at iovs
709 // - resultNread: offset in api.Memory to write the number of bytes read
710 //
711 // Result (Errno)
712 //
713 // The return value is 0 except the following error conditions:
714 // - sys.EBADF: `fd` is invalid
715 // - sys.EFAULT: `iovs` or `resultNread` point to an offset out of memory
716 // - sys.EIO: a file system error
717 //
718 // For example, this function needs to first read `iovs` to determine where
719 // to write contents. If parameters iovs=1 iovsCount=2, this function reads two
720 // offset/length pairs from api.Memory:
721 //
722 // iovs[0] iovs[1]
723 // +---------------------+ +--------------------+
724 // | uint32le uint32le| |uint32le uint32le|
725 // +---------+ +--------+ +--------+ +--------+
726 // | | | | | | | |
727 // []byte{?, 18, 0, 0, 0, 4, 0, 0, 0, 23, 0, 0, 0, 2, 0, 0, 0, ?... }
728 // iovs --^ ^ ^ ^
729 // | | | |
730 // offset --+ length --+ offset --+ length --+
731 //
732 // If the contents of the `fd` parameter was "wazero" (6 bytes) and parameter
733 // resultNread=26, this function writes the below to api.Memory:
734 //
735 // iovs[0].length iovs[1].length
736 // +--------------+ +----+ uint32le
737 // | | | | +--------+
738 // []byte{ 0..16, ?, 'w', 'a', 'z', 'e', ?, 'r', 'o', ?, 6, 0, 0, 0 }
739 // iovs[0].offset --^ ^ ^
740 // iovs[1].offset --+ |
741 // resultNread --+
742 //
743 // Note: This is similar to `readv` in POSIX. https://linux.die.net/man/3/readv
744 //
745 // See fdWrite
746 // and https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_read
747 var fdRead = newHostFunc(
748 wasip1.FdReadName, fdReadFn,
749 []wasm.ValueType{i32, i32, i32, i32},
750 "fd", "iovs", "iovs_len", "result.nread",
751 )
752
753 // preader tracks an offset across multiple reads.
754 type preader struct {
755 f experimentalsys.File
756 offset int64
757 }
758
759 // Read implements the same function as documented on sys.File.
760 func (w *preader) Read(buf []byte) (n int, errno experimentalsys.Errno) {
761 if len(buf) == 0 {
762 return 0, 0 // less overhead on zero-length reads.
763 }
764
765 n, err := w.f.Pread(buf, w.offset)
766 w.offset += int64(n)
767 return n, err
768 }
769
770 func fdReadFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
771 return fdReadOrPread(mod, params, false)
772 }
773
774 func fdReadOrPread(mod api.Module, params []uint64, isPread bool) experimentalsys.Errno {
775 mem := mod.Memory()
776 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
777
778 fd := int32(params[0])
779 iovs := uint32(params[1])
780 iovsCount := uint32(params[2])
781
782 var resultNread uint32
783 var reader func(buf []byte) (n int, errno experimentalsys.Errno)
784 if f, ok := fsc.LookupFile(fd); !ok {
785 return experimentalsys.EBADF
786 } else if isPread {
787 offset := int64(params[3])
788 reader = (&preader{f: f.File, offset: offset}).Read
789 resultNread = uint32(params[4])
790 } else {
791 reader = f.File.Read
792 resultNread = uint32(params[3])
793 }
794
795 nread, errno := readv(mem, iovs, iovsCount, reader)
796 if errno != 0 {
797 return errno
798 }
799 if !mem.WriteUint32Le(resultNread, nread) {
800 return experimentalsys.EFAULT
801 } else {
802 return 0
803 }
804 }
805
806 func readv(mem api.Memory, iovs uint32, iovsCount uint32, reader func(buf []byte) (nread int, errno experimentalsys.Errno)) (uint32, experimentalsys.Errno) {
807 var nread uint32
808 iovsStop := iovsCount << 3 // iovsCount * 8
809 iovsBuf, ok := mem.Read(iovs, iovsStop)
810 if !ok {
811 return 0, experimentalsys.EFAULT
812 }
813
814 for iovsPos := uint32(0); iovsPos < iovsStop; iovsPos += 8 {
815 offset := le.Uint32(iovsBuf[iovsPos:])
816 l := le.Uint32(iovsBuf[iovsPos+4:])
817
818 if l == 0 { // A zero length iovec could be ahead of another.
819 continue
820 }
821
822 b, ok := mem.Read(offset, l)
823 if !ok {
824 return 0, experimentalsys.EFAULT
825 }
826
827 n, errno := reader(b)
828 nread += uint32(n)
829
830 if errno == experimentalsys.ENOSYS {
831 return 0, experimentalsys.EBADF // e.g. unimplemented for read
832 } else if errno != 0 {
833 return 0, errno
834 } else if n < int(l) {
835 break // stop when we read less than capacity.
836 }
837 }
838 return nread, 0
839 }
840
841 // fdReaddir is the WASI function named wasip1.FdReaddirName which reads
842 // directory entries from a directory. Special behaviors required by this
843 // function are implemented in sys.DirentCache.
844 //
845 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_readdirfd-fd-buf-pointeru8-buf_len-size-cookie-dircookie---errno-size
846 //
847 // # Result (Errno)
848 //
849 // The return value is 0 except the following known error conditions:
850 // - sys.ENOSYS: the implementation does not support this function.
851 // - sys.EBADF: the file was closed or not a directory.
852 // - sys.EFAULT: `buf` or `buf_len` point to an offset out of memory.
853 // - sys.ENOENT: `cookie` was invalid.
854 // - sys.EINVAL: `buf_len` was not large enough to write a dirent header.
855 //
856 // # End of Directory (EOF)
857 //
858 // More entries are available when `result.bufused` == `buf_len`. See
859 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_readdir
860 // https://github.com/WebAssembly/wasi-libc/blob/659ff414560721b1660a19685110e484a081c3d4/libc-bottom-half/cloudlibc/src/libc/dirent/readdir.c#L44
861 var fdReaddir = newHostFunc(
862 wasip1.FdReaddirName, fdReaddirFn,
863 []wasm.ValueType{i32, i32, i32, i64, i32},
864 "fd", "buf", "buf_len", "cookie", "result.bufused",
865 )
866
867 func fdReaddirFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
868 mem := mod.Memory()
869 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
870
871 fd := int32(params[0])
872 buf := uint32(params[1])
873 bufLen := uint32(params[2])
874 cookie := params[3]
875 resultBufused := uint32(params[4])
876
877 // The bufLen must be enough to write a dirent header.
878 if bufLen < wasip1.DirentSize {
879 // This is a bug in the caller, as unless `buf_len` is large enough to
880 // write a dirent, it can't read the `d_namlen` from it.
881 return experimentalsys.EINVAL
882 }
883
884 // Get or open a dirent cache for this file descriptor.
885 dir, errno := direntCache(fsc, fd)
886 if errno != 0 {
887 return errno
888 }
889
890 // First, determine the maximum directory entries that can be encoded as
891 // dirents. The total size is DirentSize(24) + nameSize, for each file.
892 // Since a zero-length file name is invalid, the minimum size entry is
893 // 25 (DirentSize + 1 character).
894 maxDirEntries := bufLen/wasip1.DirentSize + 1
895
896 // While unlikely maxDirEntries will fit into bufLen, add one more just in
897 // case, as we need to know if we hit the end of the directory or not to
898 // write the correct bufused (e.g. == bufLen unless EOF).
899 // >> If less than the size of the read buffer, the end of the
900 // >> directory has been reached.
901 maxDirEntries += 1
902
903 // Read up to max entries. The underlying implementation will cache these,
904 // starting at the current location, so that they can be re-read. This is
905 // important because even the first could end up larger than bufLen due to
906 // the size of its name.
907 dirents, errno := dir.Read(cookie, maxDirEntries)
908 if errno != 0 {
909 return errno
910 }
911
912 // Determine how many dirents we can write, including a potentially
913 // truncated last entry.
914 bufToWrite, direntCount, truncatedLen := maxDirents(dirents, bufLen)
915
916 // Now, write entries to the underlying buffer.
917 if bufToWrite > 0 {
918
919 // d_next is the index of the next file in the list, so it should
920 // always be one higher than the requested cookie.
921 d_next := cookie + 1
922 // ^^ yes this can overflow to negative, which means our implementation
923 // doesn't support writing greater than max int64 entries.
924
925 buf, ok := mem.Read(buf, bufToWrite)
926 if !ok {
927 return experimentalsys.EFAULT
928 }
929
930 writeDirents(buf, dirents, d_next, direntCount, truncatedLen)
931 }
932
933 // bufused == bufLen means more dirents exist, which is the case when one
934 // is truncated.
935 bufused := bufToWrite
936 if truncatedLen > 0 {
937 bufused = bufLen
938 }
939
940 if !mem.WriteUint32Le(resultBufused, bufused) {
941 return experimentalsys.EFAULT
942 }
943 return 0
944 }
945
946 const largestDirent = int64(math.MaxUint32 - wasip1.DirentSize)
947
948 // maxDirents returns the dirents to write.
949 //
950 // `bufToWrite` is the amount of memory needed to write direntCount, which
951 // includes up to wasip1.DirentSize of a last truncated entry.
952 func maxDirents(dirents []experimentalsys.Dirent, bufLen uint32) (bufToWrite uint32, direntCount int, truncatedLen uint32) {
953 lenRemaining := bufLen
954 for i := range dirents {
955 if lenRemaining == 0 {
956 break
957 }
958 d := dirents[i]
959 direntCount++
960
961 // use int64 to guard against huge filenames
962 nameLen := int64(len(d.Name))
963 var entryLen uint32
964
965 // Check to see if DirentSize + nameLen overflows, or if it would be
966 // larger than possible to encode.
967 if el := int64(wasip1.DirentSize) + nameLen; el < 0 || el > largestDirent {
968 // panic, as testing is difficult. ex we would have to extract a
969 // function to get size of a string or allocate a 2^32 size one!
970 panic("invalid filename: too large")
971 } else { // we know this can fit into a uint32
972 entryLen = uint32(el)
973 }
974
975 if entryLen > lenRemaining {
976 // We haven't room to write the entry, and docs say to write the
977 // header. This helps especially when there is an entry with a very
978 // long filename. Ex if bufLen is 4096 and the filename is 4096,
979 // we need to write DirentSize(24) + 4096 bytes to write the entry.
980 // In this case, we only write up to DirentSize(24) to allow the
981 // caller to resize.
982 if lenRemaining >= wasip1.DirentSize {
983 truncatedLen = wasip1.DirentSize
984 } else {
985 truncatedLen = lenRemaining
986 }
987 bufToWrite += truncatedLen
988 break
989 }
990
991 // This won't go negative because we checked entryLen <= lenRemaining.
992 lenRemaining -= entryLen
993 bufToWrite += entryLen
994 }
995 return
996 }
997
998 // writeDirents writes the directory entries to the buffer, which is pre-sized
999 // based on maxDirents. truncatedEntryLen means the last is written without its
1000 // name.
1001 func writeDirents(buf []byte, dirents []experimentalsys.Dirent, d_next uint64, direntCount int, truncatedLen uint32) {
1002 pos := uint32(0)
1003 skipNameI := -1
1004
1005 // If the last entry was truncated, we either skip it or write it without
1006 // its name, depending on the length.
1007 if truncatedLen > 0 {
1008 if truncatedLen < wasip1.DirentSize {
1009 direntCount-- // skip as too small to write the header.
1010 } else {
1011 skipNameI = direntCount - 1 // write the header, but not the name.
1012 }
1013 }
1014
1015 for i := 0; i < direntCount; i++ {
1016 e := dirents[i]
1017 nameLen := uint32(len(e.Name))
1018 writeDirent(buf[pos:], d_next, e.Ino, nameLen, e.Type)
1019 d_next++
1020 pos += wasip1.DirentSize
1021
1022 if i != skipNameI {
1023 copy(buf[pos:], e.Name)
1024 pos += nameLen
1025 }
1026 }
1027 }
1028
1029 // writeDirent writes DirentSize bytes
1030 func writeDirent(buf []byte, dNext uint64, ino sysapi.Inode, dNamlen uint32, dType fs.FileMode) {
1031 le.PutUint64(buf, dNext) // d_next
1032 le.PutUint64(buf[8:], ino) // d_ino
1033 le.PutUint32(buf[16:], dNamlen) // d_namlen
1034 filetype := getWasiFiletype(dType)
1035 le.PutUint32(buf[20:], uint32(filetype)) // d_type
1036 }
1037
1038 // direntCache lazy opens a sys.DirentCache for this directory or returns an
1039 // error.
1040 func direntCache(fsc *sys.FSContext, fd int32) (*sys.DirentCache, experimentalsys.Errno) {
1041 if f, ok := fsc.LookupFile(fd); !ok {
1042 return nil, experimentalsys.EBADF
1043 } else if dir, errno := f.DirentCache(); errno == 0 {
1044 return dir, 0
1045 } else if errno == experimentalsys.ENOTDIR {
1046 // fd_readdir docs don't indicate whether to return sys.ENOTDIR or
1047 // sys.EBADF. It has been noticed that rust will crash on sys.ENOTDIR,
1048 // and POSIX C ref seems to not return this, so we don't either.
1049 //
1050 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_readdir
1051 // and https://en.wikibooks.org/wiki/C_Programming/POSIX_Reference/dirent.h
1052 return nil, experimentalsys.EBADF
1053 } else {
1054 return nil, errno
1055 }
1056 }
1057
1058 // fdRenumber is the WASI function named FdRenumberName which atomically
1059 // replaces a file descriptor by renumbering another file descriptor.
1060 //
1061 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_renumberfd-fd-to-fd---errno
1062 var fdRenumber = newHostFunc(wasip1.FdRenumberName, fdRenumberFn, []wasm.ValueType{i32, i32}, "fd", "to")
1063
1064 func fdRenumberFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1065 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1066
1067 from := int32(params[0])
1068 to := int32(params[1])
1069
1070 if errno := fsc.Renumber(from, to); errno != 0 {
1071 return errno
1072 }
1073 return 0
1074 }
1075
1076 // fdSeek is the WASI function named FdSeekName which moves the offset of a
1077 // file descriptor.
1078 //
1079 // # Parameters
1080 //
1081 // - fd: file descriptor to move the offset of
1082 // - offset: signed int64, which is encoded as uint64, input argument to
1083 // `whence`, which results in a new offset
1084 // - whence: operator that creates the new offset, given `offset` bytes
1085 // - If io.SeekStart, new offset == `offset`.
1086 // - If io.SeekCurrent, new offset == existing offset + `offset`.
1087 // - If io.SeekEnd, new offset == file size of `fd` + `offset`.
1088 // - resultNewoffset: offset in api.Memory to write the new offset to,
1089 // relative to start of the file
1090 //
1091 // Result (Errno)
1092 //
1093 // The return value is 0 except the following error conditions:
1094 // - sys.EBADF: `fd` is invalid
1095 // - sys.EFAULT: `resultNewoffset` points to an offset out of memory
1096 // - sys.EINVAL: `whence` is an invalid value
1097 // - sys.EIO: a file system error
1098 // - sys.EISDIR: the file was a directory.
1099 //
1100 // For example, if fd 3 is a file with offset 0, and parameters fd=3, offset=4,
1101 // whence=0 (=io.SeekStart), resultNewOffset=1, this function writes the below
1102 // to api.Memory:
1103 //
1104 // uint64le
1105 // +--------------------+
1106 // | |
1107 // []byte{?, 4, 0, 0, 0, 0, 0, 0, 0, ? }
1108 // resultNewoffset --^
1109 //
1110 // Note: This is similar to `lseek` in POSIX. https://linux.die.net/man/3/lseek
1111 //
1112 // See io.Seeker
1113 // and https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_seek
1114 var fdSeek = newHostFunc(
1115 wasip1.FdSeekName, fdSeekFn,
1116 []wasm.ValueType{i32, i64, i32, i32},
1117 "fd", "offset", "whence", "result.newoffset",
1118 )
1119
1120 func fdSeekFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1121 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1122 fd := int32(params[0])
1123 offset := params[1]
1124 whence := uint32(params[2])
1125 resultNewoffset := uint32(params[3])
1126
1127 if f, ok := fsc.LookupFile(fd); !ok {
1128 return experimentalsys.EBADF
1129 } else if isDir, _ := f.File.IsDir(); isDir {
1130 return experimentalsys.EISDIR // POSIX doesn't forbid seeking a directory, but wasi-testsuite does.
1131 } else if newOffset, errno := f.File.Seek(int64(offset), int(whence)); errno != 0 {
1132 return errno
1133 } else if !mod.Memory().WriteUint64Le(resultNewoffset, uint64(newOffset)) {
1134 return experimentalsys.EFAULT
1135 }
1136 return 0
1137 }
1138
1139 // fdSync is the WASI function named FdSyncName which synchronizes the data
1140 // and metadata of a file to disk.
1141 //
1142 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_syncfd-fd---errno
1143 var fdSync = newHostFunc(wasip1.FdSyncName, fdSyncFn, []wasm.ValueType{i32}, "fd")
1144
1145 func fdSyncFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1146 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1147 fd := int32(params[0])
1148
1149 // Check to see if the file descriptor is available
1150 if f, ok := fsc.LookupFile(fd); !ok {
1151 return experimentalsys.EBADF
1152 } else {
1153 return f.File.Sync()
1154 }
1155 }
1156
1157 // fdTell is the WASI function named FdTellName which returns the current
1158 // offset of a file descriptor.
1159 //
1160 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-fd_tellfd-fd---errno-filesize
1161 var fdTell = newHostFunc(wasip1.FdTellName, fdTellFn, []wasm.ValueType{i32, i32}, "fd", "result.offset")
1162
1163 func fdTellFn(ctx context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1164 fd := params[0]
1165 offset := uint64(0)
1166 whence := uint64(io.SeekCurrent)
1167 resultNewoffset := params[1]
1168
1169 fdSeekParams := []uint64{fd, offset, whence, resultNewoffset}
1170 return fdSeekFn(ctx, mod, fdSeekParams)
1171 }
1172
1173 // fdWrite is the WASI function named FdWriteName which writes to a file
1174 // descriptor.
1175 //
1176 // # Parameters
1177 //
1178 // - fd: an opened file descriptor to write data to
1179 // - iovs: offset in api.Memory to read offset, size pairs representing the
1180 // data to write to `fd`
1181 // - Both offset and length are encoded as uint32le.
1182 // - iovsCount: count of memory offset, size pairs to read sequentially
1183 // starting at iovs
1184 // - resultNwritten: offset in api.Memory to write the number of bytes
1185 // written
1186 //
1187 // Result (Errno)
1188 //
1189 // The return value is 0 except the following error conditions:
1190 // - sys.EBADF: `fd` is invalid
1191 // - sys.EFAULT: `iovs` or `resultNwritten` point to an offset out of memory
1192 // - sys.EIO: a file system error
1193 //
1194 // For example, this function needs to first read `iovs` to determine what to
1195 // write to `fd`. If parameters iovs=1 iovsCount=2, this function reads two
1196 // offset/length pairs from api.Memory:
1197 //
1198 // iovs[0] iovs[1]
1199 // +---------------------+ +--------------------+
1200 // | uint32le uint32le| |uint32le uint32le|
1201 // +---------+ +--------+ +--------+ +--------+
1202 // | | | | | | | |
1203 // []byte{?, 18, 0, 0, 0, 4, 0, 0, 0, 23, 0, 0, 0, 2, 0, 0, 0, ?... }
1204 // iovs --^ ^ ^ ^
1205 // | | | |
1206 // offset --+ length --+ offset --+ length --+
1207 //
1208 // This function reads those chunks api.Memory into the `fd` sequentially.
1209 //
1210 // iovs[0].length iovs[1].length
1211 // +--------------+ +----+
1212 // | | | |
1213 // []byte{ 0..16, ?, 'w', 'a', 'z', 'e', ?, 'r', 'o', ? }
1214 // iovs[0].offset --^ ^
1215 // iovs[1].offset --+
1216 //
1217 // Since "wazero" was written, if parameter resultNwritten=26, this function
1218 // writes the below to api.Memory:
1219 //
1220 // uint32le
1221 // +--------+
1222 // | |
1223 // []byte{ 0..24, ?, 6, 0, 0, 0', ? }
1224 // resultNwritten --^
1225 //
1226 // Note: This is similar to `writev` in POSIX. https://linux.die.net/man/3/writev
1227 //
1228 // See fdRead
1229 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#ciovec
1230 // and https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#fd_write
1231 var fdWrite = newHostFunc(
1232 wasip1.FdWriteName, fdWriteFn,
1233 []wasm.ValueType{i32, i32, i32, i32},
1234 "fd", "iovs", "iovs_len", "result.nwritten",
1235 )
1236
1237 func fdWriteFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1238 return fdWriteOrPwrite(mod, params, false)
1239 }
1240
1241 // pwriter tracks an offset across multiple writes.
1242 type pwriter struct {
1243 f experimentalsys.File
1244 offset int64
1245 }
1246
1247 // Write implements the same function as documented on sys.File.
1248 func (w *pwriter) Write(buf []byte) (n int, errno experimentalsys.Errno) {
1249 if len(buf) == 0 {
1250 return 0, 0 // less overhead on zero-length writes.
1251 }
1252
1253 n, err := w.f.Pwrite(buf, w.offset)
1254 w.offset += int64(n)
1255 return n, err
1256 }
1257
1258 func fdWriteOrPwrite(mod api.Module, params []uint64, isPwrite bool) experimentalsys.Errno {
1259 mem := mod.Memory()
1260 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1261
1262 fd := int32(params[0])
1263 iovs := uint32(params[1])
1264 iovsCount := uint32(params[2])
1265
1266 var resultNwritten uint32
1267 var writer func(buf []byte) (n int, errno experimentalsys.Errno)
1268 if f, ok := fsc.LookupFile(fd); !ok {
1269 return experimentalsys.EBADF
1270 } else if isPwrite {
1271 offset := int64(params[3])
1272 writer = (&pwriter{f: f.File, offset: offset}).Write
1273 resultNwritten = uint32(params[4])
1274 } else {
1275 writer = f.File.Write
1276 resultNwritten = uint32(params[3])
1277 }
1278
1279 nwritten, errno := writev(mem, iovs, iovsCount, writer)
1280 if errno != 0 {
1281 return errno
1282 }
1283
1284 if !mod.Memory().WriteUint32Le(resultNwritten, nwritten) {
1285 return experimentalsys.EFAULT
1286 }
1287 return 0
1288 }
1289
1290 func writev(mem api.Memory, iovs uint32, iovsCount uint32, writer func(buf []byte) (n int, errno experimentalsys.Errno)) (uint32, experimentalsys.Errno) {
1291 var nwritten uint32
1292 iovsStop := iovsCount << 3 // iovsCount * 8
1293 iovsBuf, ok := mem.Read(iovs, iovsStop)
1294 if !ok {
1295 return 0, experimentalsys.EFAULT
1296 }
1297
1298 for iovsPos := uint32(0); iovsPos < iovsStop; iovsPos += 8 {
1299 offset := le.Uint32(iovsBuf[iovsPos:])
1300 l := le.Uint32(iovsBuf[iovsPos+4:])
1301
1302 b, ok := mem.Read(offset, l)
1303 if !ok {
1304 return 0, experimentalsys.EFAULT
1305 }
1306 n, errno := writer(b)
1307 nwritten += uint32(n)
1308 if errno == experimentalsys.ENOSYS {
1309 return 0, experimentalsys.EBADF // e.g. unimplemented for write
1310 } else if errno != 0 {
1311 return 0, errno
1312 }
1313 }
1314 return nwritten, 0
1315 }
1316
1317 // pathCreateDirectory is the WASI function named PathCreateDirectoryName which
1318 // creates a directory.
1319 //
1320 // # Parameters
1321 //
1322 // - fd: file descriptor of a directory that `path` is relative to
1323 // - path: offset in api.Memory to read the path string from
1324 // - pathLen: length of `path`
1325 //
1326 // # Result (Errno)
1327 //
1328 // The return value is 0 except the following error conditions:
1329 // - sys.EBADF: `fd` is invalid
1330 // - sys.ENOENT: `path` does not exist.
1331 // - sys.ENOTDIR: `path` is a file
1332 //
1333 // # Notes
1334 // - This is similar to mkdirat in POSIX.
1335 // See https://linux.die.net/man/2/mkdirat
1336 //
1337 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_create_directoryfd-fd-path-string---errno
1338 var pathCreateDirectory = newHostFunc(
1339 wasip1.PathCreateDirectoryName, pathCreateDirectoryFn,
1340 []wasm.ValueType{i32, i32, i32},
1341 "fd", "path", "path_len",
1342 )
1343
1344 func pathCreateDirectoryFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1345 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1346
1347 fd := int32(params[0])
1348 path := uint32(params[1])
1349 pathLen := uint32(params[2])
1350
1351 preopen, pathName, errno := atPath(fsc, mod.Memory(), fd, path, pathLen)
1352 if errno != 0 {
1353 return errno
1354 }
1355
1356 if errno = preopen.Mkdir(pathName, 0o700); errno != 0 {
1357 return errno
1358 }
1359
1360 return 0
1361 }
1362
1363 // pathFilestatGet is the WASI function named PathFilestatGetName which
1364 // returns the stat attributes of a file or directory.
1365 //
1366 // # Parameters
1367 //
1368 // - fd: file descriptor of the folder to look in for the path
1369 // - flags: flags determining the method of how paths are resolved
1370 // - path: path under fd to get the filestat attributes data for
1371 // - path_len: length of the path that was given
1372 // - resultFilestat: offset to write the result filestat data
1373 //
1374 // Result (Errno)
1375 //
1376 // The return value is 0 except the following error conditions:
1377 // - sys.EBADF: `fd` is invalid
1378 // - sys.ENOTDIR: `fd` points to a file not a directory
1379 // - sys.EIO: could not stat `fd` on filesystem
1380 // - sys.EINVAL: the path contained "../"
1381 // - sys.ENAMETOOLONG: `path` + `path_len` is out of memory
1382 // - sys.EFAULT: `resultFilestat` points to an offset out of memory
1383 // - sys.ENOENT: could not find the path
1384 //
1385 // The rest of this implementation matches that of fdFilestatGet, so is not
1386 // repeated here.
1387 //
1388 // Note: This is similar to `fstatat` in POSIX.
1389 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_filestat_getfd-fd-flags-lookupflags-path-string---errno-filestat
1390 // and https://linux.die.net/man/2/fstatat
1391 var pathFilestatGet = newHostFunc(
1392 wasip1.PathFilestatGetName, pathFilestatGetFn,
1393 []wasm.ValueType{i32, i32, i32, i32, i32},
1394 "fd", "flags", "path", "path_len", "result.filestat",
1395 )
1396
1397 func pathFilestatGetFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1398 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1399
1400 fd := int32(params[0])
1401 flags := uint16(params[1])
1402 path := uint32(params[2])
1403 pathLen := uint32(params[3])
1404
1405 preopen, pathName, errno := atPath(fsc, mod.Memory(), fd, path, pathLen)
1406 if errno != 0 {
1407 return errno
1408 }
1409
1410 // Stat the file without allocating a file descriptor.
1411 var st sysapi.Stat_t
1412
1413 if (flags & wasip1.LOOKUP_SYMLINK_FOLLOW) == 0 {
1414 st, errno = preopen.Lstat(pathName)
1415 } else {
1416 st, errno = preopen.Stat(pathName)
1417 }
1418 if errno != 0 {
1419 return errno
1420 }
1421
1422 // Write the stat result to memory
1423 resultBuf := uint32(params[4])
1424 buf, ok := mod.Memory().Read(resultBuf, 64)
1425 if !ok {
1426 return experimentalsys.EFAULT
1427 }
1428
1429 filetype := getWasiFiletype(st.Mode)
1430 return writeFilestat(buf, &st, filetype)
1431 }
1432
1433 // pathFilestatSetTimes is the WASI function named PathFilestatSetTimesName
1434 // which adjusts the timestamps of a file or directory.
1435 //
1436 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_filestat_set_timesfd-fd-flags-lookupflags-path-string-atim-timestamp-mtim-timestamp-fst_flags-fstflags---errno
1437 var pathFilestatSetTimes = newHostFunc(
1438 wasip1.PathFilestatSetTimesName, pathFilestatSetTimesFn,
1439 []wasm.ValueType{i32, i32, i32, i32, i64, i64, i32},
1440 "fd", "flags", "path", "path_len", "atim", "mtim", "fst_flags",
1441 )
1442
1443 func pathFilestatSetTimesFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1444 fd := int32(params[0])
1445 flags := uint16(params[1])
1446 path := uint32(params[2])
1447 pathLen := uint32(params[3])
1448 atim := int64(params[4])
1449 mtim := int64(params[5])
1450 fstFlags := uint16(params[6])
1451
1452 sys := mod.(*wasm.ModuleInstance).Sys
1453 fsc := sys.FS()
1454
1455 atim, mtim, errno := toTimes(sys.WalltimeNanos, atim, mtim, fstFlags)
1456 if errno != 0 {
1457 return errno
1458 }
1459
1460 preopen, pathName, errno := atPath(fsc, mod.Memory(), fd, path, pathLen)
1461 if errno != 0 {
1462 return errno
1463 }
1464
1465 symlinkFollow := flags&wasip1.LOOKUP_SYMLINK_FOLLOW != 0
1466 if symlinkFollow {
1467 return preopen.Utimens(pathName, atim, mtim)
1468 }
1469 // Otherwise, we need to emulate don't follow by opening the file by path.
1470 if f, errno := preopen.OpenFile(pathName, experimentalsys.O_WRONLY, 0); errno != 0 {
1471 return errno
1472 } else {
1473 defer f.Close()
1474 return f.Utimens(atim, mtim)
1475 }
1476 }
1477
1478 // pathLink is the WASI function named PathLinkName which adjusts the
1479 // timestamps of a file or directory.
1480 //
1481 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#path_link
1482 var pathLink = newHostFunc(
1483 wasip1.PathLinkName, pathLinkFn,
1484 []wasm.ValueType{i32, i32, i32, i32, i32, i32, i32},
1485 "old_fd", "old_flags", "old_path", "old_path_len", "new_fd", "new_path", "new_path_len",
1486 )
1487
1488 func pathLinkFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1489 mem := mod.Memory()
1490 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1491
1492 oldFD := int32(params[0])
1493 // TODO: use old_flags?
1494 _ = uint32(params[1])
1495 oldPath := uint32(params[2])
1496 oldPathLen := uint32(params[3])
1497
1498 oldFS, oldName, errno := atPath(fsc, mem, oldFD, oldPath, oldPathLen)
1499 if errno != 0 {
1500 return errno
1501 }
1502
1503 newFD := int32(params[4])
1504 newPath := uint32(params[5])
1505 newPathLen := uint32(params[6])
1506
1507 newFS, newName, errno := atPath(fsc, mem, newFD, newPath, newPathLen)
1508 if errno != 0 {
1509 return errno
1510 }
1511
1512 if oldFS != newFS { // TODO: handle link across filesystems
1513 return experimentalsys.ENOSYS
1514 }
1515
1516 return oldFS.Link(oldName, newName)
1517 }
1518
1519 // pathOpen is the WASI function named PathOpenName which opens a file or
1520 // directory. This returns sys.EBADF if the fd is invalid.
1521 //
1522 // # Parameters
1523 //
1524 // - fd: file descriptor of a directory that `path` is relative to
1525 // - dirflags: flags to indicate how to resolve `path`
1526 // - path: offset in api.Memory to read the path string from
1527 // - pathLen: length of `path`
1528 // - oFlags: open flags to indicate the method by which to open the file
1529 // - fsRightsBase: interpret RIGHT_FD_WRITE to set O_RDWR
1530 // - fsRightsInheriting: ignored as rights were removed from WASI.
1531 // created file descriptor for `path`
1532 // - fdFlags: file descriptor flags
1533 // - resultOpenedFD: offset in api.Memory to write the newly created file
1534 // descriptor to.
1535 // - The result FD value is guaranteed to be less than 2**31
1536 //
1537 // Result (Errno)
1538 //
1539 // The return value is 0 except the following error conditions:
1540 // - sys.EBADF: `fd` is invalid
1541 // - sys.EFAULT: `resultOpenedFD` points to an offset out of memory
1542 // - sys.ENOENT: `path` does not exist.
1543 // - sys.EEXIST: `path` exists, while `oFlags` requires that it must not.
1544 // - sys.ENOTDIR: `path` is not a directory, while `oFlags` requires it.
1545 // - sys.EIO: a file system error
1546 //
1547 // For example, this function needs to first read `path` to determine the file
1548 // to open. If parameters `path` = 1, `pathLen` = 6, and the path is "wazero",
1549 // pathOpen reads the path from api.Memory:
1550 //
1551 // pathLen
1552 // +------------------------+
1553 // | |
1554 // []byte{ ?, 'w', 'a', 'z', 'e', 'r', 'o', ?... }
1555 // path --^
1556 //
1557 // Then, if parameters resultOpenedFD = 8, and this function opened a new file
1558 // descriptor 5 with the given flags, this function writes the below to
1559 // api.Memory:
1560 //
1561 // uint32le
1562 // +--------+
1563 // | |
1564 // []byte{ 0..6, ?, 5, 0, 0, 0, ?}
1565 // resultOpenedFD --^
1566 //
1567 // # Notes
1568 // - This is similar to `openat` in POSIX. https://linux.die.net/man/3/openat
1569 // - The returned file descriptor is not guaranteed to be the lowest-number
1570 //
1571 // See https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#path_open
1572 var pathOpen = newHostFunc(
1573 wasip1.PathOpenName, pathOpenFn,
1574 []wasm.ValueType{i32, i32, i32, i32, i32, i64, i64, i32, i32},
1575 "fd", "dirflags", "path", "path_len", "oflags", "fs_rights_base", "fs_rights_inheriting", "fdflags", "result.opened_fd",
1576 )
1577
1578 func pathOpenFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1579 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1580
1581 preopenFD := int32(params[0])
1582
1583 // TODO: dirflags is a lookupflags, and it only has one bit: symlink_follow
1584 // https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#lookupflags
1585 dirflags := uint16(params[1])
1586
1587 path := uint32(params[2])
1588 pathLen := uint32(params[3])
1589
1590 oflags := uint16(params[4])
1591
1592 rights := uint32(params[5])
1593 // inherited rights aren't used
1594 _ = params[6]
1595
1596 fdflags := uint16(params[7])
1597 resultOpenedFD := uint32(params[8])
1598
1599 preopen, pathName, errno := atPath(fsc, mod.Memory(), preopenFD, path, pathLen)
1600 if errno != 0 {
1601 return errno
1602 }
1603
1604 if pathLen == 0 {
1605 return experimentalsys.EINVAL
1606 }
1607
1608 fileOpenFlags := openFlags(dirflags, oflags, fdflags, rights)
1609 isDir := fileOpenFlags&experimentalsys.O_DIRECTORY != 0
1610
1611 if isDir && oflags&wasip1.O_CREAT != 0 {
1612 return experimentalsys.EINVAL // use pathCreateDirectory!
1613 }
1614
1615 newFD, errno := fsc.OpenFile(preopen, pathName, fileOpenFlags, 0o600)
1616 if errno != 0 {
1617 return errno
1618 }
1619
1620 // Check any flags that require the file to evaluate.
1621 if isDir {
1622 if f, ok := fsc.LookupFile(newFD); !ok {
1623 return experimentalsys.EBADF // unexpected
1624 } else if isDir, errno := f.File.IsDir(); errno != 0 {
1625 _ = fsc.CloseFile(newFD)
1626 return errno
1627 } else if !isDir {
1628 _ = fsc.CloseFile(newFD)
1629 return experimentalsys.ENOTDIR
1630 }
1631 }
1632
1633 if !mod.Memory().WriteUint32Le(resultOpenedFD, uint32(newFD)) {
1634 _ = fsc.CloseFile(newFD)
1635 return experimentalsys.EFAULT
1636 }
1637 return 0
1638 }
1639
1640 // atPath returns the pre-open specific path after verifying it is a directory.
1641 //
1642 // # Notes
1643 //
1644 // Languages including Zig and Rust use only pre-opens for the FD because
1645 // wasi-libc `__wasilibc_find_relpath` will only return a preopen. That said,
1646 // our wasi.c example shows other languages act differently and can use a non
1647 // pre-opened file descriptor.
1648 //
1649 // We don't handle `AT_FDCWD`, as that's resolved in the compiler. There's no
1650 // working directory function in WASI, so most assume CWD is "/". Notably, Zig
1651 // has different behavior which assumes it is whatever the first pre-open name
1652 // is.
1653 //
1654 // See https://github.com/WebAssembly/wasi-libc/blob/659ff414560721b1660a19685110e484a081c3d4/libc-bottom-half/sources/at_fdcwd.c
1655 // See https://linux.die.net/man/2/openat
1656 func atPath(fsc *sys.FSContext, mem api.Memory, fd int32, p, pathLen uint32) (experimentalsys.FS, string, experimentalsys.Errno) {
1657 b, ok := mem.Read(p, pathLen)
1658 if !ok {
1659 return nil, "", experimentalsys.EFAULT
1660 }
1661 pathName := string(b)
1662
1663 // interesting_paths wants us to break on trailing slash if the input ends
1664 // up a file, not a directory!
1665 hasTrailingSlash := strings.HasSuffix(pathName, "/")
1666
1667 // interesting_paths includes paths that include relative links but end up
1668 // not escaping
1669 pathName = path.Clean(pathName)
1670
1671 // interesting_paths wants to break on root paths or anything that escapes.
1672 // This part is the same as fs.FS.Open()
1673 if !fs.ValidPath(pathName) {
1674 return nil, "", experimentalsys.EPERM
1675 }
1676
1677 // add the trailing slash back
1678 if hasTrailingSlash {
1679 pathName = pathName + "/"
1680 }
1681
1682 if f, ok := fsc.LookupFile(fd); !ok {
1683 return nil, "", experimentalsys.EBADF // closed or invalid
1684 } else if isDir, errno := f.File.IsDir(); errno != 0 {
1685 return nil, "", errno
1686 } else if !isDir {
1687 return nil, "", experimentalsys.ENOTDIR
1688 } else if f.IsPreopen { // don't append the pre-open name
1689 return f.FS, pathName, 0
1690 } else {
1691 // Join via concat to avoid name conflict on path.Join
1692 return f.FS, f.Name + "/" + pathName, 0
1693 }
1694 }
1695
1696 func preopenPath(fsc *sys.FSContext, fd int32) (string, experimentalsys.Errno) {
1697 if f, ok := fsc.LookupFile(fd); !ok {
1698 return "", experimentalsys.EBADF // closed
1699 } else if !f.IsPreopen {
1700 return "", experimentalsys.EBADF
1701 } else if isDir, errno := f.File.IsDir(); errno != 0 || !isDir {
1702 // In wasip1, only directories can be returned by fd_prestat_get as
1703 // there are no prestat types defined for files or sockets.
1704 return "", errno
1705 } else {
1706 return f.Name, 0
1707 }
1708 }
1709
1710 func openFlags(dirflags, oflags, fdflags uint16, rights uint32) (openFlags experimentalsys.Oflag) {
1711 if dirflags&wasip1.LOOKUP_SYMLINK_FOLLOW == 0 {
1712 openFlags |= experimentalsys.O_NOFOLLOW
1713 }
1714 if oflags&wasip1.O_DIRECTORY != 0 {
1715 openFlags |= experimentalsys.O_DIRECTORY
1716 } else if oflags&wasip1.O_EXCL != 0 {
1717 openFlags |= experimentalsys.O_EXCL
1718 }
1719 // Because we don't implement rights, we partially rely on the open flags
1720 // to determine the mode in which the file will be opened. This will create
1721 // divergent behavior compared to WASI runtimes which have a more strict
1722 // interpretation of the WASI capabilities model; for example, a program
1723 // which sets O_CREAT but does not give read or write permissions will
1724 // successfully create a file when running with wazero, but might get a
1725 // permission denied error on other runtimes.
1726 defaultMode := experimentalsys.O_RDONLY
1727 if oflags&wasip1.O_TRUNC != 0 {
1728 openFlags |= experimentalsys.O_TRUNC
1729 defaultMode = experimentalsys.O_RDWR
1730 }
1731 if oflags&wasip1.O_CREAT != 0 {
1732 openFlags |= experimentalsys.O_CREAT
1733 defaultMode = experimentalsys.O_RDWR
1734 }
1735 if fdflags&wasip1.FD_NONBLOCK != 0 {
1736 openFlags |= experimentalsys.O_NONBLOCK
1737 }
1738 if fdflags&wasip1.FD_APPEND != 0 {
1739 openFlags |= experimentalsys.O_APPEND
1740 defaultMode = experimentalsys.O_RDWR
1741 }
1742 if fdflags&wasip1.FD_DSYNC != 0 {
1743 openFlags |= experimentalsys.O_DSYNC
1744 }
1745 if fdflags&wasip1.FD_RSYNC != 0 {
1746 openFlags |= experimentalsys.O_RSYNC
1747 }
1748 if fdflags&wasip1.FD_SYNC != 0 {
1749 openFlags |= experimentalsys.O_SYNC
1750 }
1751
1752 // Since rights were discontinued in wasi, we only interpret RIGHT_FD_WRITE
1753 // because it is the only way to know that we need to set write permissions
1754 // on a file if the application did not pass any of O_CREAT, O_APPEND, nor
1755 // O_TRUNC.
1756 const r = wasip1.RIGHT_FD_READ
1757 const w = wasip1.RIGHT_FD_WRITE
1758 const rw = r | w
1759 switch {
1760 case (rights & rw) == rw:
1761 openFlags |= experimentalsys.O_RDWR
1762 case (rights & w) == w:
1763 openFlags |= experimentalsys.O_WRONLY
1764 case (rights & r) == r:
1765 openFlags |= experimentalsys.O_RDONLY
1766 default:
1767 openFlags |= defaultMode
1768 }
1769 return
1770 }
1771
1772 // pathReadlink is the WASI function named PathReadlinkName that reads the
1773 // contents of a symbolic link.
1774 //
1775 // See: https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_readlinkfd-fd-path-string-buf-pointeru8-buf_len-size---errno-size
1776 var pathReadlink = newHostFunc(
1777 wasip1.PathReadlinkName, pathReadlinkFn,
1778 []wasm.ValueType{i32, i32, i32, i32, i32, i32},
1779 "fd", "path", "path_len", "buf", "buf_len", "result.bufused",
1780 )
1781
1782 func pathReadlinkFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1783 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1784
1785 fd := int32(params[0])
1786 path := uint32(params[1])
1787 pathLen := uint32(params[2])
1788 buf := uint32(params[3])
1789 bufLen := uint32(params[4])
1790 resultBufused := uint32(params[5])
1791
1792 if pathLen == 0 || bufLen == 0 {
1793 return experimentalsys.EINVAL
1794 }
1795
1796 mem := mod.Memory()
1797 preopen, p, errno := atPath(fsc, mem, fd, path, pathLen)
1798 if errno != 0 {
1799 return errno
1800 }
1801
1802 dst, errno := preopen.Readlink(p)
1803 if errno != 0 {
1804 return errno
1805 }
1806
1807 if len(dst) > int(bufLen) {
1808 return experimentalsys.ERANGE
1809 }
1810
1811 if ok := mem.WriteString(buf, dst); !ok {
1812 return experimentalsys.EFAULT
1813 }
1814
1815 if !mem.WriteUint32Le(resultBufused, uint32(len(dst))) {
1816 return experimentalsys.EFAULT
1817 }
1818 return 0
1819 }
1820
1821 // pathRemoveDirectory is the WASI function named PathRemoveDirectoryName which
1822 // removes a directory.
1823 //
1824 // # Parameters
1825 //
1826 // - fd: file descriptor of a directory that `path` is relative to
1827 // - path: offset in api.Memory to read the path string from
1828 // - pathLen: length of `path`
1829 //
1830 // # Result (Errno)
1831 //
1832 // The return value is 0 except the following error conditions:
1833 // - sys.EBADF: `fd` is invalid
1834 // - sys.ENOENT: `path` does not exist.
1835 // - sys.ENOTEMPTY: `path` is not empty
1836 // - sys.ENOTDIR: `path` is a file
1837 //
1838 // # Notes
1839 // - This is similar to unlinkat with AT_REMOVEDIR in POSIX.
1840 // See https://linux.die.net/man/2/unlinkat
1841 //
1842 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_remove_directoryfd-fd-path-string---errno
1843 var pathRemoveDirectory = newHostFunc(
1844 wasip1.PathRemoveDirectoryName, pathRemoveDirectoryFn,
1845 []wasm.ValueType{i32, i32, i32},
1846 "fd", "path", "path_len",
1847 )
1848
1849 func pathRemoveDirectoryFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1850 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1851
1852 fd := int32(params[0])
1853 path := uint32(params[1])
1854 pathLen := uint32(params[2])
1855
1856 preopen, pathName, errno := atPath(fsc, mod.Memory(), fd, path, pathLen)
1857 if errno != 0 {
1858 return errno
1859 }
1860
1861 return preopen.Rmdir(pathName)
1862 }
1863
1864 // pathRename is the WASI function named PathRenameName which renames a file or
1865 // directory.
1866 //
1867 // # Parameters
1868 //
1869 // - fd: file descriptor of a directory that `old_path` is relative to
1870 // - old_path: offset in api.Memory to read the old path string from
1871 // - old_path_len: length of `old_path`
1872 // - new_fd: file descriptor of a directory that `new_path` is relative to
1873 // - new_path: offset in api.Memory to read the new path string from
1874 // - new_path_len: length of `new_path`
1875 //
1876 // # Result (Errno)
1877 //
1878 // The return value is 0 except the following error conditions:
1879 // - sys.EBADF: `fd` or `new_fd` are invalid
1880 // - sys.ENOENT: `old_path` does not exist.
1881 // - sys.ENOTDIR: `old` is a directory and `new` exists, but is a file.
1882 // - sys.EISDIR: `old` is a file and `new` exists, but is a directory.
1883 //
1884 // # Notes
1885 // - This is similar to unlinkat in POSIX.
1886 // See https://linux.die.net/man/2/renameat
1887 //
1888 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_renamefd-fd-old_path-string-new_fd-fd-new_path-string---errno
1889 var pathRename = newHostFunc(
1890 wasip1.PathRenameName, pathRenameFn,
1891 []wasm.ValueType{i32, i32, i32, i32, i32, i32},
1892 "fd", "old_path", "old_path_len", "new_fd", "new_path", "new_path_len",
1893 )
1894
1895 func pathRenameFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1896 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1897
1898 fd := int32(params[0])
1899 oldPath := uint32(params[1])
1900 oldPathLen := uint32(params[2])
1901
1902 newFD := int32(params[3])
1903 newPath := uint32(params[4])
1904 newPathLen := uint32(params[5])
1905
1906 oldFS, oldPathName, errno := atPath(fsc, mod.Memory(), fd, oldPath, oldPathLen)
1907 if errno != 0 {
1908 return errno
1909 }
1910
1911 newFS, newPathName, errno := atPath(fsc, mod.Memory(), newFD, newPath, newPathLen)
1912 if errno != 0 {
1913 return errno
1914 }
1915
1916 if oldFS != newFS { // TODO: handle renames across filesystems
1917 return experimentalsys.ENOSYS
1918 }
1919
1920 return oldFS.Rename(oldPathName, newPathName)
1921 }
1922
1923 // pathSymlink is the WASI function named PathSymlinkName which creates a
1924 // symbolic link.
1925 //
1926 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#path_symlink
1927 var pathSymlink = newHostFunc(
1928 wasip1.PathSymlinkName, pathSymlinkFn,
1929 []wasm.ValueType{i32, i32, i32, i32, i32},
1930 "old_path", "old_path_len", "fd", "new_path", "new_path_len",
1931 )
1932
1933 func pathSymlinkFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
1934 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
1935
1936 oldPath := uint32(params[0])
1937 oldPathLen := uint32(params[1])
1938 fd := int32(params[2])
1939 newPath := uint32(params[3])
1940 newPathLen := uint32(params[4])
1941
1942 mem := mod.Memory()
1943
1944 dir, ok := fsc.LookupFile(fd)
1945 if !ok {
1946 return experimentalsys.EBADF // closed
1947 } else if isDir, errno := dir.File.IsDir(); errno != 0 {
1948 return errno
1949 } else if !isDir {
1950 return experimentalsys.ENOTDIR
1951 }
1952
1953 if oldPathLen == 0 || newPathLen == 0 {
1954 return experimentalsys.EINVAL
1955 }
1956
1957 oldPathBuf, ok := mem.Read(oldPath, oldPathLen)
1958 if !ok {
1959 return experimentalsys.EFAULT
1960 }
1961
1962 _, newPathName, errno := atPath(fsc, mod.Memory(), fd, newPath, newPathLen)
1963 if errno != 0 {
1964 return errno
1965 }
1966
1967 return dir.FS.Symlink(
1968 // Do not join old path since it's only resolved when dereference the link created here.
1969 // And the dereference result depends on the opening directory's file descriptor at that point.
1970 unsafe.String(&oldPathBuf[0], int(oldPathLen)),
1971 newPathName,
1972 )
1973 }
1974
1975 // pathUnlinkFile is the WASI function named PathUnlinkFileName which unlinks a
1976 // file.
1977 //
1978 // # Parameters
1979 //
1980 // - fd: file descriptor of a directory that `path` is relative to
1981 // - path: offset in api.Memory to read the path string from
1982 // - pathLen: length of `path`
1983 //
1984 // # Result (Errno)
1985 //
1986 // The return value is 0 except the following error conditions:
1987 // - sys.EBADF: `fd` is invalid
1988 // - sys.ENOENT: `path` does not exist.
1989 // - sys.EISDIR: `path` is a directory
1990 //
1991 // # Notes
1992 // - This is similar to unlinkat without AT_REMOVEDIR in POSIX.
1993 // See https://linux.die.net/man/2/unlinkat
1994 //
1995 // See https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-path_unlink_filefd-fd-path-string---errno
1996 var pathUnlinkFile = newHostFunc(
1997 wasip1.PathUnlinkFileName, pathUnlinkFileFn,
1998 []wasm.ValueType{i32, i32, i32},
1999 "fd", "path", "path_len",
2000 )
2001
2002 func pathUnlinkFileFn(_ context.Context, mod api.Module, params []uint64) experimentalsys.Errno {
2003 fsc := mod.(*wasm.ModuleInstance).Sys.FS()
2004
2005 fd := int32(params[0])
2006 path := uint32(params[1])
2007 pathLen := uint32(params[2])
2008
2009 preopen, pathName, errno := atPath(fsc, mod.Memory(), fd, path, pathLen)
2010 if errno != 0 {
2011 return errno
2012 }
2013
2014 return preopen.Unlink(pathName)
2015 }