kobako 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +552 -10
  4. data/Cargo.lock +595 -139
  5. data/README.md +126 -564
  6. data/ROADMAP.md +3 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +488 -1
  8. data/crates/kobako-runtime/Cargo.toml +73 -15
  9. data/crates/kobako-runtime/README.md +11 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +5 -6
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +301 -0
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +292 -0
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +181 -0
  15. data/crates/kobako-runtime/src/endpoint.rs +267 -0
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +82 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +274 -0
  21. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +248 -0
  22. data/crates/kobako-runtime/src/filesystem/bind.rs +2857 -0
  23. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +89 -0
  24. data/crates/kobako-runtime/src/filesystem/overlay/inode.rs +106 -0
  25. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +263 -0
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +128 -0
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +238 -0
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +135 -0
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +54 -0
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +316 -739
  31. data/crates/kobako-runtime/src/filesystem/overlay.rs +2627 -1154
  32. data/crates/kobako-runtime/src/filesystem/pipe.rs +224 -0
  33. data/crates/kobako-runtime/src/filesystem/rdir.rs +84 -0
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +32 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +107 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +22 -0
  38. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +1997 -0
  39. data/crates/kobako-runtime/src/filesystem/wrap.rs +208 -0
  40. data/crates/kobako-runtime/src/filesystem.rs +25 -388
  41. data/crates/kobako-runtime/src/fork.rs +96 -0
  42. data/crates/kobako-runtime/src/grant.rs +3 -0
  43. data/crates/kobako-runtime/src/hashtable.rs +46 -0
  44. data/crates/kobako-runtime/src/lib.rs +27 -11
  45. data/crates/kobako-runtime/src/limits.rs +195 -0
  46. data/crates/kobako-runtime/src/locking/seqlock.rs +66 -0
  47. data/crates/kobako-runtime/src/locking.rs +228 -0
  48. data/crates/kobako-runtime/src/memcg.rs +383 -0
  49. data/crates/kobako-runtime/src/mount.rs +86 -101
  50. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  51. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  52. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  53. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  54. data/crates/kobako-runtime/src/net/family.rs +181 -0
  55. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  56. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  57. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  58. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  59. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  60. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  61. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  62. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  63. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  64. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  65. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  66. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  67. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  68. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  69. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  70. data/crates/kobako-runtime/src/net.rs +42 -0
  71. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  72. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  73. data/crates/kobako-runtime/src/network.rs +551 -0
  74. data/crates/kobako-runtime/src/policy.rs +16 -0
  75. data/crates/kobako-runtime/src/profile.rs +37 -16
  76. data/crates/kobako-runtime/src/runtime.rs +3 -5
  77. data/crates/kobako-runtime/src/sched.rs +311 -0
  78. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  79. data/crates/kobako-runtime/src/security/hooks.rs +242 -0
  80. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  81. data/crates/kobako-runtime/src/security.rs +601 -0
  82. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  83. data/crates/kobako-runtime/src/vfs/attr.rs +162 -0
  84. data/crates/kobako-runtime/src/vfs/dentry.rs +1466 -0
  85. data/crates/kobako-runtime/src/vfs/file.rs +1911 -0
  86. data/crates/kobako-runtime/src/vfs/inode.rs +425 -0
  87. data/crates/kobako-runtime/src/vfs/kern_path.rs +213 -0
  88. data/crates/kobako-runtime/src/vfs/mount.rs +60 -0
  89. data/crates/kobako-runtime/src/vfs/namei.rs +5837 -0
  90. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  91. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  92. data/crates/kobako-runtime/src/vfs/openat2.rs +116 -0
  93. data/crates/kobako-runtime/src/vfs/path.rs +64 -0
  94. data/crates/kobako-runtime/src/vfs/readdir.rs +163 -0
  95. data/crates/kobako-runtime/src/vfs/stat.rs +293 -0
  96. data/crates/kobako-runtime/src/vfs/super_block.rs +126 -0
  97. data/crates/kobako-runtime/src/vfs/utimes.rs +299 -0
  98. data/crates/kobako-runtime/src/vfs.rs +63 -0
  99. data/crates/kobako-runtime/src/wait.rs +356 -0
  100. data/crates/kobako-transport/CHANGELOG.md +39 -2
  101. data/crates/kobako-transport/Cargo.toml +3 -3
  102. data/crates/kobako-transport/README.md +8 -8
  103. data/crates/kobako-transport/src/abi.rs +78 -72
  104. data/crates/kobako-transport/src/envelope/bytes.rs +49 -30
  105. data/crates/kobako-transport/src/envelope/call.rs +37 -9
  106. data/crates/kobako-transport/src/envelope/compile_reply.rs +2 -2
  107. data/crates/kobako-transport/src/envelope/error_record.rs +24 -3
  108. data/crates/kobako-transport/src/envelope/fault.rs +2 -2
  109. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  110. data/crates/kobako-transport/src/envelope/outcome.rs +11 -11
  111. data/crates/kobako-transport/src/envelope/preamble.rs +34 -31
  112. data/crates/kobako-transport/src/envelope/reply.rs +29 -29
  113. data/crates/kobako-transport/src/envelope/request.rs +2 -2
  114. data/crates/kobako-transport/src/envelope/run.rs +1 -1
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +12 -12
  116. data/crates/kobako-transport/src/envelope.rs +15 -10
  117. data/crates/kobako-wasmtime/CHANGELOG.md +315 -8
  118. data/crates/kobako-wasmtime/Cargo.toml +35 -15
  119. data/crates/kobako-wasmtime/README.md +11 -6
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +19 -47
  123. data/crates/kobako-wasmtime/src/ambient.rs +33 -19
  124. data/crates/kobako-wasmtime/src/cache.rs +28 -20
  125. data/crates/kobako-wasmtime/src/config.rs +59 -60
  126. data/crates/kobako-wasmtime/src/driver.rs +63 -145
  127. data/crates/kobako-wasmtime/src/exports.rs +147 -32
  128. data/crates/kobako-wasmtime/src/guest.rs +44 -0
  129. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  130. data/crates/kobako-wasmtime/src/imports.rs +48 -18
  131. data/crates/kobako-wasmtime/src/instance_pre.rs +7 -7
  132. data/crates/kobako-wasmtime/src/invocation.rs +93 -51
  133. data/crates/kobako-wasmtime/src/lib.rs +6 -7
  134. data/crates/kobako-wasmtime/src/limiter.rs +52 -211
  135. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  136. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +70 -57
  137. data/crates/kobako-wasmtime/src/preview1/differential.rs +137 -27
  138. data/crates/kobako-wasmtime/src/preview1/errno.rs +90 -233
  139. data/crates/kobako-wasmtime/src/preview1/fd.rs +1301 -522
  140. data/crates/kobako-wasmtime/src/preview1/memory.rs +126 -150
  141. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +192 -0
  142. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +1989 -708
  143. data/crates/kobako-wasmtime/src/preview1/path.rs +181 -365
  144. data/crates/kobako-wasmtime/src/preview1/poll.rs +345 -173
  145. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -25
  146. data/crates/kobako-wasmtime/src/preview1/testsuite-expected.txt +6 -0
  147. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +147 -0
  148. data/crates/kobako-wasmtime/src/preview1.rs +471 -416
  149. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  150. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  151. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  152. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  153. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  154. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  155. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  156. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  157. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  158. data/crates/kobako-wasmtime/src/trap.rs +31 -16
  159. data/crates/kobako-wasmtime/src/wasi.rs +238 -93
  160. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  161. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  162. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  163. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  164. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  165. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  166. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  167. data/crates/kobako-wasmtime/witx/typenames.witx +750 -0
  168. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +441 -0
  169. data/data/kobako.wasm +0 -0
  170. data/ext/kobako/Cargo.toml +1 -1
  171. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +35 -27
  172. data/ext/kobako/src/escape.rs +98 -0
  173. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +36 -16
  174. data/ext/kobako/src/filesystem/ruby.rs +689 -0
  175. data/ext/kobako/src/filesystem.rs +217 -0
  176. data/ext/kobako/src/gvl.rs +306 -0
  177. data/ext/kobako/src/lib.rs +64 -3
  178. data/ext/kobako/src/network/mock.rs +187 -0
  179. data/ext/kobako/src/network.rs +591 -0
  180. data/ext/kobako/src/runtime/bridge.rs +31 -30
  181. data/ext/kobako/src/runtime/snapshot.rs +5 -5
  182. data/ext/kobako/src/runtime.rs +221 -138
  183. data/ext/kobako/src/wire.rs +42 -0
  184. data/lib/kobako/catalog/extensions.rb +19 -7
  185. data/lib/kobako/catalog/flags.rb +4 -6
  186. data/lib/kobako/catalog/grants.rb +5 -4
  187. data/lib/kobako/catalog/handles.rb +9 -31
  188. data/lib/kobako/catalog/mount.rb +12 -12
  189. data/lib/kobako/catalog/network.rb +35 -0
  190. data/lib/kobako/catalog/replacements.rb +28 -0
  191. data/lib/kobako/catalog/services.rb +7 -21
  192. data/lib/kobako/catalog/snippets.rb +10 -25
  193. data/lib/kobako/catalog.rb +4 -1
  194. data/lib/kobako/codec/{utils.rb → boundary.rb} +5 -3
  195. data/lib/kobako/codec/decoder.rb +12 -12
  196. data/lib/kobako/codec/ext_types.rb +5 -7
  197. data/lib/kobako/codec/handle_walk.rb +5 -47
  198. data/lib/kobako/codec/nesting.rb +7 -7
  199. data/lib/kobako/codec/value_budget.rb +134 -42
  200. data/lib/kobako/codec.rb +1 -1
  201. data/lib/kobako/context.rb +28 -15
  202. data/lib/kobako/errors.rb +15 -12
  203. data/lib/kobako/extension.rb +3 -2
  204. data/lib/kobako/filesystem.rb +53 -15
  205. data/lib/kobako/handle.rb +2 -2
  206. data/lib/kobako/names.rb +28 -0
  207. data/lib/kobako/network.rb +210 -0
  208. data/lib/kobako/outcome.rb +7 -7
  209. data/lib/kobako/payload/arguments.rb +2 -2
  210. data/lib/kobako/pool.rb +47 -25
  211. data/lib/kobako/runtime.rb +3 -2
  212. data/lib/kobako/sandbox.rb +113 -56
  213. data/lib/kobako/sandbox_options.rb +41 -107
  214. data/lib/kobako/snippet/bytecode.rb +1 -1
  215. data/lib/kobako/snippet/source.rb +1 -1
  216. data/lib/kobako/transport/argument_wrap.rb +64 -0
  217. data/lib/kobako/transport/block_failure.rb +1 -1
  218. data/lib/kobako/transport/dispatcher.rb +10 -10
  219. data/lib/kobako/transport/exposure.rb +28 -17
  220. data/lib/kobako/transport/reflection.rb +28 -11
  221. data/lib/kobako/transport/run.rb +13 -28
  222. data/lib/kobako/transport/yielder.rb +3 -10
  223. data/lib/kobako/transport.rb +1 -0
  224. data/lib/kobako/version.rb +1 -1
  225. data/lib/kobako.rb +38 -0
  226. data/release-please-config.json +16 -0
  227. data/sig/core/thread.rbs +6 -0
  228. data/sig/kobako/catalog/extensions.rbs +5 -3
  229. data/sig/kobako/catalog/grants.rbs +7 -4
  230. data/sig/kobako/catalog/handles.rbs +2 -4
  231. data/sig/kobako/catalog/mount.rbs +3 -5
  232. data/sig/kobako/catalog/network.rbs +20 -0
  233. data/sig/kobako/catalog/replacements.rbs +14 -0
  234. data/sig/kobako/catalog/services.rbs +1 -5
  235. data/sig/kobako/catalog/snippets.rbs +3 -5
  236. data/sig/kobako/catalog.rbs +1 -1
  237. data/sig/kobako/codec/boundary.rbs +9 -0
  238. data/sig/kobako/codec/decoder.rbs +1 -1
  239. data/sig/kobako/codec/handle_walk.rbs +0 -6
  240. data/sig/kobako/codec/nesting.rbs +2 -2
  241. data/sig/kobako/codec/value_budget.rbs +48 -5
  242. data/sig/kobako/codec.rbs +1 -2
  243. data/sig/kobako/context.rbs +4 -2
  244. data/sig/kobako/errors.rbs +4 -4
  245. data/sig/kobako/filesystem.rbs +38 -15
  246. data/sig/kobako/guest_yielder.rbs +1 -1
  247. data/sig/kobako/network.rbs +115 -0
  248. data/sig/kobako/outcome.rbs +1 -1
  249. data/sig/kobako/payload/arguments.rbs +1 -1
  250. data/sig/kobako/pool.rbs +8 -4
  251. data/sig/kobako/runtime.rbs +32 -3
  252. data/sig/kobako/sandbox.rbs +22 -7
  253. data/sig/kobako/sandbox_options.rbs +29 -38
  254. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  255. data/sig/kobako/transport/dispatcher.rbs +2 -2
  256. data/sig/kobako/transport/error.rbs +1 -1
  257. data/sig/kobako/transport/exposure.rbs +3 -5
  258. data/sig/kobako/transport/reflection.rbs +12 -2
  259. data/sig/kobako/transport/run.rbs +3 -5
  260. data/sig/kobako/transport/yielder.rbs +0 -3
  261. data/sig/kobako/transport.rbs +2 -2
  262. data/sig/kobako.rbs +13 -0
  263. metadata +131 -34
  264. data/crates/kobako-runtime/src/filesystem/directory/spelling.rs +0 -194
  265. data/crates/kobako-runtime/src/filesystem/directory.rs +0 -1082
  266. data/crates/kobako-runtime/src/filesystem/memory.rs +0 -1100
  267. data/crates/kobako-runtime/src/filesystem/overlay/exclusive.rs +0 -88
  268. data/crates/kobako-runtime/src/filesystem/path.rs +0 -60
  269. data/crates/kobako-runtime/src/filesystem/temporary.rs +0 -167
  270. data/crates/kobako-wasmtime/src/capture.rs +0 -96
  271. data/crates/kobako-wasmtime/src/descriptors.rs +0 -167
  272. data/crates/kobako-wasmtime/src/dispatch.rs +0 -125
  273. data/crates/kobako-wasmtime/src/guest_mem.rs +0 -271
  274. data/crates/kobako-wasmtime/src/io.rs +0 -89
  275. data/crates/kobako-wasmtime/src/preview1/args.rs +0 -60
  276. data/crates/kobako-wasmtime/src/preview1/beneath.rs +0 -188
  277. data/crates/kobako-wasmtime/tests/compile_posture.rs +0 -43
  278. data/crates/kobako-wasmtime/tests/guest_file.rs +0 -1054
  279. data/crates/kobako-wasmtime/tests/preamble_flags.rs +0 -70
  280. data/crates/kobako-wasmtime/tests/snippet_compile.rs +0 -95
  281. data/crates/kobako-wasmtime/tests/support/mod.rs +0 -30
  282. data/crates/kobako-wasmtime/tests/unanswered_call.rs +0 -86
  283. data/crates/kobako-wasmtime/tests/unsupported_call.rs +0 -51
  284. data/ext/kobako/src/runtime/escape.rs +0 -53
  285. data/ext/kobako/src/runtime/filesystem/ruby.rs +0 -400
  286. data/ext/kobako/src/runtime/filesystem.rs +0 -236
  287. data/ext/kobako/src/runtime/gvl.rs +0 -112
  288. data/lib/kobako/constant_name.rb +0 -8
  289. data/sig/kobako/codec/utils.rbs +0 -9
  290. data/sig/kobako/constant_name.rbs +0 -3
  291. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -1,591 +1,517 @@
1
1
  //! The 21 `fd_*` calls over kobako's descriptor table.
2
2
  //!
3
- //! For stdio each answers what wasmtime-wasi's preview1 answers for the
4
- //! same descriptor; the differential probe in `preview1` holds that. For a
5
- //! directory or a file beneath a Mount, the Filesystem answers
6
- //! and the descriptor's position and rights stay here.
7
-
8
- use bytes::Bytes;
9
- use kobako_runtime::filesystem::{FileType, Metadata};
10
- use wasmtime_wasi::p2::pipe::{MemoryInputPipe, MemoryOutputPipe};
11
- use wasmtime_wasi::p2::{InputStream, OutputStream, StreamError};
12
-
13
- use super::args::{
14
- self, FDFLAGS_APPEND, FDFLAGS_NONBLOCK, FDFLAGS_SYNCHRONIZED, RIGHTS_FD_READ, RIGHTS_FD_WRITE,
15
- };
16
- use super::beneath::confirm;
3
+ //! The runtime's open file decides each answer, so this keeps only what
4
+ //! preview1 itself defines: which file a number stands for, its rights, a
5
+ //! preopen's name, and what wasi-testsuite asks of a directory's position.
6
+ //! It also keeps what a Linux syscall entry checks before the VFS: which
7
+ //! descriptor a call takes, the order of its errors, and the caller's buffer.
8
+
9
+ use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
+
11
+ use kobako_runtime::cred::Cred;
12
+ use kobako_runtime::filesystem::{FileType, Iattr, Kstat, SetTime};
13
+ use kobako_runtime::vfs::{self, verify_dirent_name, DirContext, DirEmit, File, Whence};
14
+ use wiggle::{GuestMemory as WitxMemory, GuestPtr, GuestType};
15
+
16
+ use super::descriptors::{Descriptor, FileRef, FileRefMut};
17
17
  use super::errno::{Answer, Errno};
18
18
  use super::memory::GuestMemory;
19
- use crate::descriptors::{Descriptor, Descriptors, OpenFile};
20
-
21
- /// `fdstat` / `filestat` filetypes.
22
- const FILETYPE_UNKNOWN: u8 = 0;
23
- const FILETYPE_DIRECTORY: u8 = 3;
24
- const FILETYPE_REGULAR_FILE: u8 = 4;
25
- const FILETYPE_SYMBOLIC_LINK: u8 = 7;
26
-
27
- const RIGHTS_FD_DATASYNC: u64 = 1 << 0;
28
- const RIGHTS_FD_SEEK: u64 = 1 << 2;
29
- const RIGHTS_FD_FDSTAT_SET_FLAGS: u64 = 1 << 3;
30
- const RIGHTS_FD_SYNC: u64 = 1 << 4;
31
- const RIGHTS_FD_TELL: u64 = 1 << 5;
32
- const RIGHTS_FD_ADVISE: u64 = 1 << 7;
33
- const RIGHTS_FD_ALLOCATE: u64 = 1 << 8;
34
- const RIGHTS_FD_READDIR: u64 = 1 << 14;
35
- const RIGHTS_PATH_FILESTAT_SET_SIZE: u64 = 1 << 19;
36
- const RIGHTS_FD_FILESTAT_GET: u64 = 1 << 21;
37
- const RIGHTS_FD_FILESTAT_SET_SIZE: u64 = 1 << 22;
38
- const RIGHTS_FD_FILESTAT_SET_TIMES: u64 = 1 << 23;
39
- const RIGHTS_POLL_FD_READWRITE: u64 = 1 << 27;
19
+ use super::types::{self, Fdflags, Filetype, Fstflags, Rights};
20
+ use crate::preview2::{filesystem, try_to_nanos};
21
+ use crate::wasi::Wasi;
40
22
 
41
23
  /// What a preopen allows itself: every path call, as wasmtime-wasi hands
42
24
  /// most userlands.
43
- const PREOPEN_RIGHTS: u64 = (1 << 9)
44
- | (1 << 10)
45
- | (1 << 11)
46
- | (1 << 12)
47
- | (1 << 13)
48
- | RIGHTS_FD_READDIR
49
- | (1 << 15)
50
- | (1 << 16)
51
- | (1 << 17)
52
- | (1 << 18)
53
- | (1 << 20)
54
- | RIGHTS_FD_FILESTAT_GET
55
- | RIGHTS_FD_FILESTAT_SET_TIMES
56
- | (1 << 24)
57
- | (1 << 25)
58
- | (1 << 26);
59
-
60
- /// What a file opened beneath a preopen may hold. Reading and writing are
61
- /// both inherited whatever the Mount's access, since wasi-libc intersects
62
- /// them before asking: a read-only Mount answers a write itself, as `ROFS`.
63
- const PREOPEN_INHERITING: u64 = PREOPEN_RIGHTS
64
- | RIGHTS_FD_DATASYNC
65
- | RIGHTS_FD_READ
66
- | RIGHTS_FD_SEEK
67
- | RIGHTS_FD_FDSTAT_SET_FLAGS
68
- | RIGHTS_FD_SYNC
69
- | RIGHTS_FD_TELL
70
- | RIGHTS_FD_WRITE
71
- | RIGHTS_FD_ADVISE
72
- | RIGHTS_FD_ALLOCATE
73
- | RIGHTS_FD_FILESTAT_SET_SIZE
74
- | RIGHTS_POLL_FD_READWRITE;
75
-
76
- /// The most bytes one write moves into a capture pipe at a time, the
77
- /// preview2 `blocking-write-and-flush` limit wasmtime-wasi writes under.
78
- const WRITE_CHUNK: usize = 4096;
79
-
80
- /// The size of one `dirent` header ahead of its name.
81
- const DIRENT_SIZE: u32 = 24;
82
-
83
- fn descriptor(table: &Descriptors, fd: u32) -> Answer<&Descriptor> {
84
- table.get(fd).ok_or_else(|| Errno::Badf.into())
85
- }
86
-
87
- fn descriptor_mut(table: &mut Descriptors, fd: u32) -> Answer<&mut Descriptor> {
88
- table.get_mut(fd).ok_or_else(|| Errno::Badf.into())
89
- }
90
-
91
- /// The open file `fd` stands for; any other descriptor is `BADF`.
92
- fn file(table: &mut Descriptors, fd: u32) -> Answer<&mut OpenFile> {
93
- match descriptor_mut(table, fd)? {
94
- Descriptor::File(file) => Ok(file),
95
- Descriptor::Stdin(_) | Descriptor::Channel(_) | Descriptor::Directory(_) => {
96
- Err(Errno::Badf.into())
97
- }
98
- }
25
+ fn preopen_rights() -> Rights {
26
+ Rights::PATH_CREATE_DIRECTORY
27
+ | Rights::PATH_CREATE_FILE
28
+ | Rights::PATH_LINK_SOURCE
29
+ | Rights::PATH_LINK_TARGET
30
+ | Rights::PATH_OPEN
31
+ | Rights::FD_READDIR
32
+ | Rights::PATH_READLINK
33
+ | Rights::PATH_RENAME_SOURCE
34
+ | Rights::PATH_RENAME_TARGET
35
+ | Rights::PATH_FILESTAT_GET
36
+ | Rights::PATH_FILESTAT_SET_TIMES
37
+ | Rights::FD_FILESTAT_GET
38
+ | Rights::FD_FILESTAT_SET_TIMES
39
+ | Rights::PATH_SYMLINK
40
+ | Rights::PATH_REMOVE_DIRECTORY
41
+ | Rights::PATH_UNLINK_FILE
99
42
  }
100
43
 
101
- /// A call that moves a stream position: a file has one, stdio is a pipe
102
- /// with none, and a directory is no stream at all.
103
- fn seekable(table: &mut Descriptors, fd: u32) -> Answer<&mut OpenFile> {
104
- match descriptor_mut(table, fd)? {
105
- Descriptor::File(file) => Ok(file),
106
- Descriptor::Stdin(_) | Descriptor::Channel(_) => Err(Errno::Spipe.into()),
107
- Descriptor::Directory(_) => Err(Errno::Badf.into()),
108
- }
44
+ /// What a file opened beneath a directory may hold. Reading and writing are
45
+ /// both inherited whatever the Mount's access or the directory's own mode,
46
+ /// since wasi-libc intersects them before asking and Linux takes an open's
47
+ /// mode from its flags alone: a read-only Mount answers a write itself, as
48
+ /// `ROFS`.
49
+ fn directory_rights_inheriting() -> Rights {
50
+ preopen_rights()
51
+ | Rights::FD_DATASYNC
52
+ | Rights::FD_READ
53
+ | Rights::FD_SEEK
54
+ | Rights::FD_FDSTAT_SET_FLAGS
55
+ | Rights::FD_SYNC
56
+ | Rights::FD_TELL
57
+ | Rights::FD_WRITE
58
+ | Rights::FD_ADVISE
59
+ | Rights::FD_ALLOCATE
60
+ | Rights::FD_FILESTAT_SET_SIZE
61
+ | Rights::POLL_FD_READWRITE
62
+ }
63
+
64
+ /// What `fd` stands for, a file that stands only for its path included, as
65
+ /// `fdget_raw` takes one.
66
+ fn get_descriptor(wasi: &Wasi, fd: u32) -> Answer<&Descriptor> {
67
+ wasi.descriptors().get(fd).ok_or_else(|| Errno::Badf.into())
109
68
  }
110
69
 
111
- /// An offset or size `pread`, `pwrite`, or `ftruncate` names, which Linux
112
- /// reads as a signed `off_t` and refuses once negative.
113
- fn refuse_negative(offset: u64) -> Answer<u64> {
114
- if offset > i64::MAX as u64 {
115
- return Err(Errno::Inval.into());
70
+ /// The file `fd` stands for, one that stands only for its path included, as
71
+ /// `fdget_raw` takes one.
72
+ fn get_raw_file(wasi: &Wasi, fd: u32) -> Answer<FileRef<'_>> {
73
+ wasi.file(fd).ok_or_else(|| Errno::Badf.into())
74
+ }
75
+
76
+ /// The open file `fd` stands for, refusing one that stands only for its path,
77
+ /// as `fdget` does.
78
+ pub(crate) fn get_file(wasi: &Wasi, fd: u32) -> Answer<FileRef<'_>> {
79
+ match wasi.file(fd) {
80
+ Some(file) if !file.is_path() => Ok(file),
81
+ _ => Err(Errno::Badf.into()),
116
82
  }
117
- Ok(offset)
118
83
  }
119
84
 
120
- /// A read of `len` bytes from `offset`, refused as Linux refuses one whose
121
- /// end would pass the largest signed offset.
122
- fn refuse_reading_past_largest_offset(offset: u64, len: u32) -> Answer<u64> {
123
- if offset.saturating_add(u64::from(len)) > i64::MAX as u64 {
124
- return Err(Errno::Inval.into());
85
+ /// The open file `fd` stands for, to change, refusing one that stands only for
86
+ /// its path, as `fdget` does.
87
+ fn get_file_mut(wasi: &mut Wasi, fd: u32) -> Answer<FileRefMut<'_>> {
88
+ match wasi.file_mut(fd) {
89
+ Some(file) if !file.is_path() => Ok(file),
90
+ _ => Err(Errno::Badf.into()),
125
91
  }
126
- Ok(offset)
127
92
  }
128
93
 
129
- /// The part of `buf` a write at `offset` lands, as Linux cuts a write
130
- /// short at the largest signed offset and refuses one starting there as
131
- /// too large.
132
- fn trim_to_largest_offset(buf: &[u8], offset: u64) -> Answer<&[u8]> {
133
- let room = (i64::MAX as u64).saturating_sub(offset);
134
- if room == 0 && !buf.is_empty() {
135
- return Err(Errno::Fbig.into());
94
+ /// The open file `fd` stands for, in a call about its position. wasi-testsuite
95
+ /// has a directory refuse one, where Linux would seek it.
96
+ fn get_seekable(wasi: &mut Wasi, fd: u32) -> Answer<FileRefMut<'_>> {
97
+ match get_file_mut(wasi, fd)? {
98
+ file if file.is_directory() => Err(Errno::Badf.into()),
99
+ file => Ok(file),
136
100
  }
137
- Ok(&buf[..buf.len().min(usize::try_from(room).unwrap_or(usize::MAX))])
138
101
  }
139
102
 
140
103
  /// A call any file or directory answers, which preview1 refuses for
141
104
  /// stdio.
142
- fn file_or_directory(table: &Descriptors, fd: u32) -> Answer {
143
- match descriptor(table, fd)? {
144
- Descriptor::Directory(_) | Descriptor::File(_) => Ok(()),
145
- Descriptor::Stdin(_) | Descriptor::Channel(_) => Err(Errno::Badf.into()),
105
+ fn refuse_stream(wasi: &Wasi, fd: u32) -> Answer {
106
+ match get_raw_file(wasi, fd)?.is_stream() {
107
+ true => Err(Errno::Badf.into()),
108
+ false => Ok(()),
146
109
  }
147
110
  }
148
111
 
149
- /// A `filestat` of `filetype`, named `nlink` times and `size` bytes long.
150
- fn write_filestat(mem: &mut GuestMemory, out: u32, filetype: u8, nlink: u64, size: u64) -> Answer {
151
- GuestMemory::check_aligned(out, 8)?;
152
- mem.write(out, &[0; 64])?;
153
- mem.write_u8(GuestMemory::field(out, 16)?, filetype)?;
154
- mem.write_u64(GuestMemory::field(out, 24)?, nlink)?;
155
- mem.write_u64(GuestMemory::field(out, 32)?, size)
156
- }
157
-
158
- fn to_filetype(file_type: FileType) -> u8 {
112
+ /// `file_type` as a preview1 `filetype`, which has no code for a FIFO and two
113
+ /// for the one kind `st_mode` names a socket.
114
+ fn to_filetype(file_type: FileType) -> Filetype {
159
115
  match file_type {
160
- FileType::Directory => FILETYPE_DIRECTORY,
161
- FileType::Symlink => FILETYPE_SYMBOLIC_LINK,
162
- FileType::File => FILETYPE_REGULAR_FILE,
163
- _ => FILETYPE_UNKNOWN,
116
+ FileType::Dir => Filetype::Directory,
117
+ FileType::Symlink => Filetype::SymbolicLink,
118
+ FileType::RegFile => Filetype::RegularFile,
119
+ FileType::Sock => Filetype::SocketStream,
120
+ FileType::Blkdev => Filetype::BlockDevice,
121
+ FileType::Chrdev => Filetype::CharacterDevice,
122
+ _ => Filetype::Unknown,
164
123
  }
165
124
  }
166
125
 
167
- /// A `filestat` for what a Filesystem reports a path names, named once
168
- /// since `Metadata` carries no count of names.
169
- pub(crate) fn write_metadata(mem: &mut GuestMemory, out: u32, metadata: Metadata) -> Answer {
170
- write_filestat(mem, out, to_filetype(metadata.file_type), 1, metadata.len)
126
+ /// A `filestat` for what a Filesystem reports a path names, as `cred` sees
127
+ /// it, at time zero where it keeps no time.
128
+ pub(crate) fn to_filestat(cred: &Cred, stat: Kstat) -> Answer<types::Filestat> {
129
+ let stat = vfs::cp_new_stat(cred, stat);
130
+ Ok(types::Filestat {
131
+ dev: stat.dev,
132
+ ino: stat.ino,
133
+ filetype: to_filetype(stat.file_type),
134
+ nlink: stat.nlink,
135
+ size: stat.size,
136
+ atim: to_timestamp(stat.atime)?,
137
+ mtim: to_timestamp(stat.mtime)?,
138
+ ctim: to_timestamp(stat.ctime)?,
139
+ })
171
140
  }
172
141
 
173
- /// The hints preview1 offers about a file. A Filesystem that ignores them
174
- /// is still correct, so they succeed over a range Linux takes.
175
- pub(crate) fn advise(
176
- table: &mut Descriptors,
177
- fd: u32,
178
- offset: u64,
179
- len: u64,
180
- advice: u32,
142
+ /// `time` as a preview1 `timestamp`, nanoseconds since the Unix epoch, and
143
+ /// zero for none or one before it. One past what the `u64` holds answers
144
+ /// `OVERFLOW`, as wasmtime-wasi's conversion from a `datetime` does.
145
+ fn to_timestamp(time: Option<SystemTime>) -> Answer<u64> {
146
+ let Some(since) = time.and_then(|time| time.duration_since(UNIX_EPOCH).ok()) else {
147
+ return Ok(0);
148
+ };
149
+ try_to_nanos(since).map_err(|_| Errno::Overflow.into())
150
+ }
151
+
152
+ /// Set the times `flags` ask through `call`, answering before it looks at the
153
+ /// name or the descriptor where they ask none, as Linux's `utimensat` does
154
+ /// for both. Setting a timestamp and setting it to now are exclusive: asking
155
+ /// both is `INVAL`.
156
+ pub(crate) fn utimensat(
157
+ atim: types::Timestamp,
158
+ mtim: types::Timestamp,
159
+ flags: Fstflags,
160
+ call: impl FnOnce(&Iattr) -> Answer,
181
161
  ) -> Answer {
182
- args::variant(advice, args::ADVICE_MAX)?;
183
- file(table, fd)?;
184
- refuse_negative(offset)?;
185
- refuse_negative(len).map(drop)
162
+ match to_iattr(atim, mtim, flags)? {
163
+ Some(times) => call(&times),
164
+ None => Ok(()),
165
+ }
186
166
  }
187
167
 
188
- /// A Filesystem has no room to reserve ahead of a write, so allocating it
189
- /// is unsupported rather than answered as done.
190
- pub(crate) fn allocate(table: &mut Descriptors, fd: u32) -> Answer {
191
- file(table, fd)?;
192
- Err(Errno::Notsup.into())
168
+ /// The times `flags` ask to set, `None` where they ask none.
169
+ fn to_iattr(
170
+ atim: types::Timestamp,
171
+ mtim: types::Timestamp,
172
+ flags: Fstflags,
173
+ ) -> Answer<Option<Iattr<'static>>> {
174
+ let time = |at, set, now| match (flags.contains(set), flags.contains(now)) {
175
+ (true, true) => Err(Errno::Inval),
176
+ (true, false) => Ok(Some(SetTime::At(UNIX_EPOCH + Duration::from_nanos(at)))),
177
+ (false, true) => Ok(Some(SetTime::Now)),
178
+ (false, false) => Ok(None),
179
+ };
180
+ let atime = time(atim, Fstflags::ATIM, Fstflags::ATIM_NOW)?;
181
+ let mtime = time(mtim, Fstflags::MTIM, Fstflags::MTIM_NOW)?;
182
+ Ok((atime.is_some() || mtime.is_some()).then(|| Iattr::for_times(atime, mtime)))
183
+ }
184
+
185
+ pub(crate) fn advise(wasi: &mut Wasi, fd: u32, offset: u64, len: u64) -> Answer {
186
+ Ok(get_file_mut(wasi, fd)?.fadvise(offset, len)?)
187
+ }
188
+
189
+ pub(crate) fn allocate(wasi: &mut Wasi, fd: u32, offset: u64, len: u64) -> Answer {
190
+ Ok(get_file_mut(wasi, fd)?.fallocate(offset, len)?)
193
191
  }
194
192
 
195
- pub(crate) fn close(table: &mut Descriptors, fd: u32) -> Answer {
196
- match table.remove(fd).ok_or(Errno::Badf)? {
197
- Descriptor::File(open) => Ok(open.file.close()?),
198
- _ => Ok(()),
193
+ pub(crate) fn close(wasi: &mut Wasi, fd: u32) -> Answer {
194
+ match wasi.take(fd).ok_or(Errno::Badf)? {
195
+ Some(file) => Ok(file.close()?),
196
+ None => Ok(()),
199
197
  }
200
198
  }
201
199
 
202
- pub(crate) fn sync(table: &mut Descriptors, fd: u32) -> Answer {
203
- Ok(file(table, fd)?.file.sync()?)
200
+ pub(crate) fn sync(wasi: &mut Wasi, fd: u32, datasync: bool) -> Answer {
201
+ Ok(get_file_mut(wasi, fd)?.fsync(datasync)?)
204
202
  }
205
203
 
206
- pub(crate) fn fdstat_get(table: &Descriptors, mem: &mut GuestMemory, fd: u32, out: u32) -> Answer {
207
- let (filetype, flags, base, inheriting) = match descriptor(table, fd)? {
208
- Descriptor::Stdin(_) => (FILETYPE_UNKNOWN, 0, RIGHTS_FD_READ, RIGHTS_FD_READ),
209
- Descriptor::Channel(_) => (FILETYPE_UNKNOWN, 0, RIGHTS_FD_WRITE, RIGHTS_FD_WRITE),
210
- Descriptor::Directory(dir) if dir.preopen => {
211
- (FILETYPE_DIRECTORY, 0, PREOPEN_RIGHTS, PREOPEN_INHERITING)
204
+ pub(crate) fn fdstat_get(wasi: &Wasi, fd: u32) -> Answer<types::Fdstat> {
205
+ let preopen = get_descriptor(wasi, fd)?.preopen_path.is_some();
206
+ Ok(to_fdstat(&*get_raw_file(wasi, fd)?, preopen))
207
+ }
208
+
209
+ /// What `fd_fdstat_get` reports of `file`, a preopen's root when `preopen`.
210
+ fn to_fdstat(file: &File, preopen: bool) -> types::Fdstat {
211
+ let mut fs_flags = Fdflags::empty();
212
+ fs_flags.set(Fdflags::APPEND, file.is_append());
213
+ fs_flags.set(Fdflags::NONBLOCK, file.is_nonblock());
214
+ fs_flags.set(Fdflags::DSYNC, file.is_dsync());
215
+ // Linux's `O_RSYNC` is `O_SYNC`, so a file opened to sync holds both.
216
+ fs_flags.set(Fdflags::SYNC | Fdflags::RSYNC, file.is_sync());
217
+ let (fs_rights_base, fs_rights_inheriting) = if file.is_stream() {
218
+ let mut rights = Rights::empty();
219
+ rights.set(Rights::FD_READ, file.is_readable());
220
+ rights.set(Rights::FD_WRITE, file.is_writable());
221
+ (rights, rights)
222
+ } else if preopen {
223
+ (preopen_rights(), directory_rights_inheriting())
224
+ } else {
225
+ let mut rights = Rights::all();
226
+ if file.is_directory() {
227
+ rights -=
228
+ Rights::FD_SEEK | Rights::FD_FILESTAT_SET_SIZE | Rights::PATH_FILESTAT_SET_SIZE;
212
229
  }
213
- Descriptor::Directory(_) => {
214
- let rights = args::RIGHTS
215
- & !RIGHTS_FD_WRITE
216
- & !RIGHTS_FD_SEEK
217
- & !RIGHTS_FD_FILESTAT_SET_SIZE
218
- & !RIGHTS_PATH_FILESTAT_SET_SIZE;
219
- (FILETYPE_DIRECTORY, 0, rights, rights)
230
+ if !file.is_readable() {
231
+ rights -= Rights::FD_READ | Rights::FD_READDIR;
220
232
  }
221
- Descriptor::File(file) => {
222
- let mut rights = args::RIGHTS;
223
- if !file.readable {
224
- rights &= !RIGHTS_FD_READ & !RIGHTS_FD_READDIR;
225
- }
226
- if !file.writable {
227
- rights &= !RIGHTS_FD_WRITE;
228
- }
229
- let flags = if file.append {
230
- FDFLAGS_APPEND as u16
231
- } else {
232
- 0
233
- };
234
- (FILETYPE_REGULAR_FILE, flags, rights, rights)
233
+ if !file.is_writable() {
234
+ rights -= Rights::FD_WRITE;
235
+ }
236
+ match file.is_directory() {
237
+ true => (rights, directory_rights_inheriting()),
238
+ false => (rights, rights),
235
239
  }
236
240
  };
237
- GuestMemory::check_aligned(out, 8)?;
238
- mem.write_u8(out, filetype)?;
239
- mem.write_u16(GuestMemory::field(out, 2)?, flags)?;
240
- mem.write_u64(GuestMemory::field(out, 8)?, base)?;
241
- mem.write_u64(GuestMemory::field(out, 16)?, inheriting)
242
- }
243
-
244
- /// Only appending can change once a file is open; the sync flags are
245
- /// `INVAL`, as in wasmtime-wasi, and a file never stops blocking, so
246
- /// asking it to is unsupported.
247
- pub(crate) fn fdstat_set_flags(table: &mut Descriptors, fd: u32, flags: u32) -> Answer {
248
- args::flags(flags, args::FDFLAGS)?;
249
- let file = file(table, fd)?;
250
- if flags & FDFLAGS_SYNCHRONIZED != 0 {
251
- return Err(Errno::Inval.into());
252
- }
253
- if flags & FDFLAGS_NONBLOCK != 0 {
254
- return Err(Errno::Notsup.into());
255
- }
256
- file.append = flags & FDFLAGS_APPEND != 0;
241
+ types::Fdstat {
242
+ fs_filetype: to_filetype(file.file_type()),
243
+ fs_flags,
244
+ fs_rights_base,
245
+ fs_rights_inheriting,
246
+ }
247
+ }
248
+
249
+ pub(crate) fn fdstat_set_flags(wasi: &mut Wasi, fd: u32, flags: Fdflags) -> Answer {
250
+ get_file_mut(wasi, fd)?.setfl(
251
+ flags.contains(Fdflags::APPEND),
252
+ flags.contains(Fdflags::NONBLOCK),
253
+ );
257
254
  Ok(())
258
255
  }
259
256
 
260
257
  /// Rights only narrow at open, so a later change is unsupported.
261
- pub(crate) fn fdstat_set_rights(
262
- table: &Descriptors,
263
- fd: u32,
264
- base: u64,
265
- inheriting: u64,
266
- ) -> Answer {
267
- args::flags(base, args::RIGHTS)?;
268
- args::flags(inheriting, args::RIGHTS)?;
269
- file_or_directory(table, fd)?;
258
+ pub(crate) fn fdstat_set_rights(wasi: &Wasi, fd: u32) -> Answer {
259
+ refuse_stream(wasi, fd)?;
270
260
  Err(Errno::Notsup.into())
271
261
  }
272
262
 
273
- pub(crate) fn filestat_get(
274
- table: &Descriptors,
275
- mem: &mut GuestMemory,
276
- fd: u32,
277
- out: u32,
278
- ) -> Answer {
279
- match descriptor(table, fd)? {
280
- Descriptor::Stdin(_) | Descriptor::Channel(_) => {
281
- write_filestat(mem, out, FILETYPE_UNKNOWN, 0, 0)
282
- }
283
- Descriptor::Directory(dir) => {
284
- confirm(dir)?;
285
- write_metadata(mem, out, dir.mount.filesystem().metadata(&dir.path)?)
286
- }
287
- Descriptor::File(file) => write_metadata(mem, out, file.file.metadata()?),
288
- }
263
+ pub(crate) fn filestat_get(wasi: &Wasi, fd: u32) -> Answer<types::Filestat> {
264
+ let stat = get_raw_file(wasi, fd)?.getattr()?;
265
+ to_filestat(wasi.cred(), stat)
289
266
  }
290
267
 
291
- /// A Mount that refuses the write answers first, as wasmtime-wasi answers
292
- /// by its preopen; a file opened only to read then answers as Linux's
293
- /// `ftruncate` does.
294
- pub(crate) fn filestat_set_size(table: &mut Descriptors, fd: u32, size: u64) -> Answer {
295
- let file = file(table, fd)?;
296
- if !file.mount.allows_writes() {
297
- return Err(Errno::Perm.into());
298
- }
299
- if !file.writable {
300
- return Err(Errno::Inval.into());
268
+ /// Refuse a size or offset Linux's signed `loff_t` reads as negative, before
269
+ /// the descriptor is looked for, as `ksys_ftruncate`, `ksys_pread64`, and
270
+ /// `ksys_pwrite64` check it before `fdget`.
271
+ fn ensure_offset(at: u64) -> Answer {
272
+ match at > vfs::OFFSET_MAX {
273
+ true => Err(Errno::Inval.into()),
274
+ false => Ok(()),
301
275
  }
302
- Ok(file.file.set_len(refuse_negative(size)?)?)
303
276
  }
304
277
 
305
- /// A Filesystem keeps no timestamps of the guest's choosing, so setting
306
- /// them is unsupported rather than silently ignored.
307
- pub(crate) fn filestat_set_times(table: &Descriptors, fd: u32, fst_flags: u32) -> Answer {
308
- args::fstflags(fst_flags)?;
309
- file_or_directory(table, fd)?;
310
- Err(Errno::Notsup.into())
278
+ pub(crate) fn filestat_set_size(wasi: &mut Wasi, fd: u32, size: u64) -> Answer {
279
+ ensure_offset(size)?;
280
+ Ok(get_file_mut(wasi, fd)?.truncate(size)?)
281
+ }
282
+
283
+ pub(crate) fn filestat_set_times(wasi: &Wasi, fd: u32, times: &Iattr) -> Answer {
284
+ let file = get_file(wasi, fd)?;
285
+ Ok(filesystem::set_times(
286
+ wasi.cred(),
287
+ wasi.walk_guard(),
288
+ &file,
289
+ times,
290
+ )?)
311
291
  }
312
292
 
313
293
  pub(crate) fn pread(
314
- table: &mut Descriptors,
315
- mem: &mut GuestMemory,
294
+ wasi: &mut Wasi,
295
+ mem: &mut GuestMemory<'_, '_>,
316
296
  fd: u32,
317
- iovs: (u32, u32),
297
+ iovs: types::IovecArray,
318
298
  offset: u64,
319
- nread: u32,
320
- ) -> Answer {
321
- let (ptr, len) = mem.first_non_empty_buffer(iovs.0, iovs.1)?;
322
- let file = match descriptor_mut(table, fd)? {
323
- Descriptor::Stdin(_) => return Err(Errno::Spipe.into()),
324
- Descriptor::Channel(_) | Descriptor::Directory(_) => return Err(Errno::Badf.into()),
325
- Descriptor::File(file) => file,
326
- };
327
- if !file.readable {
328
- return Err(Errno::Badf.into());
329
- }
330
- let offset = refuse_reading_past_largest_offset(refuse_negative(offset)?, len)?;
331
- let read = file.file.read_at(mem.bytes_mut(ptr, len)?, offset)?;
332
- mem.write_u32(nread, read as u32)
299
+ ) -> Answer<types::Size> {
300
+ ensure_offset(offset)?;
301
+ let buf = mem.read_first_non_empty_iovec(iovs)?;
302
+ let mut file = get_file_mut(wasi, fd)?;
303
+ file.may_pread(offset)?;
304
+ Ok(file.pread(mem.bytes_mut(buf)?, offset)? as u32)
333
305
  }
334
306
 
335
- pub(crate) fn prestat_get(table: &Descriptors, mem: &mut GuestMemory, fd: u32, out: u32) -> Answer {
336
- match descriptor(table, fd)? {
337
- Descriptor::Directory(dir) if dir.preopen => {
338
- GuestMemory::check_aligned(out, 4)?;
339
- mem.write_u8(out, 0)?;
340
- mem.write_u32(GuestMemory::field(out, 4)?, dir.mount.at().len() as u32)
341
- }
342
- _ => Err(Errno::Badf.into()),
307
+ pub(crate) fn prestat_get(wasi: &Wasi, fd: u32) -> Answer<types::Prestat> {
308
+ match &get_descriptor(wasi, fd)?.preopen_path {
309
+ Some(at) => Ok(types::Prestat::Dir(types::PrestatDir {
310
+ pr_name_len: at.len() as u32,
311
+ })),
312
+ None => Err(Errno::Badf.into()),
343
313
  }
344
314
  }
345
315
 
346
316
  pub(crate) fn prestat_dir_name(
347
- table: &Descriptors,
348
- mem: &mut GuestMemory,
317
+ wasi: &Wasi,
318
+ mem: &mut GuestMemory<'_, '_>,
349
319
  fd: u32,
350
- path: u32,
320
+ path: GuestPtr<u8>,
351
321
  path_len: u32,
352
322
  ) -> Answer {
353
- match descriptor(table, fd)? {
354
- Descriptor::Directory(dir) if dir.preopen => {
355
- let name = dir.mount.at().as_bytes();
323
+ match &get_descriptor(wasi, fd)?.preopen_path {
324
+ Some(at) => {
325
+ let name = at.as_bytes();
356
326
  if name.len() > path_len as usize {
357
327
  return Err(Errno::Nametoolong.into());
358
328
  }
359
- mem.write(path, name)
329
+ mem.write_bytes(path, name)
360
330
  }
361
- _ => Err(Errno::Notdir.into()),
331
+ None => Err(Errno::Notdir.into()),
362
332
  }
363
333
  }
364
334
 
365
335
  pub(crate) fn pwrite(
366
- table: &mut Descriptors,
367
- mem: &mut GuestMemory,
336
+ wasi: &mut Wasi,
337
+ mem: &mut GuestMemory<'_, '_>,
368
338
  fd: u32,
369
- ciovs: (u32, u32),
339
+ ciovs: types::CiovecArray,
370
340
  offset: u64,
371
- nwritten: u32,
372
- ) -> Answer {
373
- let (ptr, len) = mem.first_non_empty_buffer(ciovs.0, ciovs.1)?;
374
- let file = match descriptor_mut(table, fd)? {
375
- Descriptor::Channel(_) => return Err(Errno::Spipe.into()),
376
- Descriptor::Stdin(_) | Descriptor::Directory(_) => return Err(Errno::Badf.into()),
377
- Descriptor::File(file) => file,
378
- };
379
- // The buffer is bounded before the access is checked, as wasmtime-wasi
380
- // bounds it before the host refuses the write.
381
- let buf = mem.bytes(ptr, len)?;
382
- if !file.writable {
383
- return Err(Errno::Badf.into());
384
- }
385
- let offset = refuse_negative(offset)?;
386
- // Linux's `pwrite` ignores the offset of a file opened to append.
387
- let written = if file.append {
388
- file.file.append(buf)?.1
389
- } else {
390
- file.file
391
- .write_at(trim_to_largest_offset(buf, offset)?, offset)?
392
- };
393
- mem.write_u32(nwritten, written as u32)
341
+ ) -> Answer<types::Size> {
342
+ ensure_offset(offset)?;
343
+ let buf = mem.read_first_non_empty_ciovec(ciovs)?;
344
+ let mut file = get_file_mut(wasi, fd)?;
345
+ file.may_pwrite(offset)?;
346
+ Ok(file.pwrite(mem.bytes(buf)?, offset)? as u32)
394
347
  }
395
348
 
396
349
  pub(crate) fn read(
397
- table: &mut Descriptors,
398
- mem: &mut GuestMemory,
350
+ wasi: &mut Wasi,
351
+ mem: &mut GuestMemory<'_, '_>,
399
352
  fd: u32,
400
- iovs: (u32, u32),
401
- nread: u32,
402
- ) -> Answer {
403
- let (ptr, len) = mem.first_non_empty_buffer(iovs.0, iovs.1)?;
404
- let read = match descriptor_mut(table, fd)? {
405
- Descriptor::Stdin(pipe) => {
406
- // Bounded before stdin is drained, so a trap takes no bytes.
407
- mem.bytes(ptr, len)?;
408
- let bytes = read_stdin(pipe, len as usize)?;
409
- mem.write(ptr, &bytes)?;
410
- bytes.len()
411
- }
412
- Descriptor::File(file) => {
413
- // Bounded before the access is checked, as wasmtime-wasi bounds
414
- // it before the host refuses the read.
415
- let buf = mem.bytes_mut(ptr, len)?;
416
- if !file.readable {
417
- return Err(Errno::Badf.into());
418
- }
419
- let at = refuse_reading_past_largest_offset(file.position, len)?;
420
- let read = file.file.read_at(buf, at)?;
421
- file.position += read as u64;
422
- read
353
+ iovs: types::IovecArray,
354
+ ) -> Answer<types::Size> {
355
+ let buf = mem.read_first_non_empty_iovec(iovs)?;
356
+ let mut file = get_file_mut(wasi, fd)?;
357
+ file.may_read()?;
358
+ // Bounded before the file is asked, as a trap takes no bytes from a pipe.
359
+ Ok(file.read(mem.bytes_mut(buf)?)? as u32)
360
+ }
361
+
362
+ /// The `dirent` header ahead of one entry's name, its `d_next` left for the
363
+ /// listing to fill in once it knows it.
364
+ fn to_dirent_header(emit: &DirEmit<'_>, d_ino: u64) -> Answer<Vec<u8>> {
365
+ let mut header = vec![0; types::Dirent::guest_size() as usize];
366
+ WitxMemory::Unshared(&mut header).write(
367
+ GuestPtr::new(0),
368
+ types::Dirent {
369
+ d_next: 0,
370
+ d_ino,
371
+ d_namlen: emit.name.len() as u32,
372
+ d_type: to_filetype(emit.file_type),
373
+ },
374
+ )?;
375
+ Ok(header)
376
+ }
377
+
378
+ /// One entry as a preview1 `dirent` at `used` bytes into the buffer, cut off
379
+ /// where it ends, answering where its header stands when it fit whole.
380
+ fn write_dirent(
381
+ mem: &mut GuestMemory<'_, '_>,
382
+ buf: (GuestPtr<u8>, u32),
383
+ used: &mut u32,
384
+ cred: &Cred,
385
+ emit: &DirEmit<'_>,
386
+ ) -> Answer<Option<u32>> {
387
+ let (start, capacity) = buf;
388
+ let at = *used;
389
+ let header = to_dirent_header(emit, vfs::ino_of(cred, emit.identity))?;
390
+ let mut whole = true;
391
+ for part in [&header[..], emit.name.as_bytes()] {
392
+ let room = (capacity - *used) as usize;
393
+ let take = part.len().min(room);
394
+ if take > 0 {
395
+ mem.write_bytes(start.add(*used)?, &part[..take])?;
423
396
  }
424
- Descriptor::Channel(_) | Descriptor::Directory(_) => return Err(Errno::Badf.into()),
425
- };
426
- mem.write_u32(nread, read as u32)
397
+ *used += take as u32;
398
+ whole &= take == part.len();
399
+ }
400
+ Ok(whole.then_some(at))
427
401
  }
428
402
 
429
- /// A directory's entries as preview1 `dirent`s, `.` and `..` first, from
430
- /// the `cookie`th on, cut off where the buffer ends. A listing from the
431
- /// start reads the directory; one going on reads the entries that listing
432
- /// began with, so a guest reading in small steps costs one listing, not one
433
- /// per step.
403
+ /// Where a listing goes on from past the entry whose header stands at `at`,
404
+ /// as `filldir64` writes `prev->d_off` once the next entry or the listing's end
405
+ /// says, `d_next` leading each header.
406
+ fn write_d_next(
407
+ mem: &mut GuestMemory<'_, '_>,
408
+ start: GuestPtr<u8>,
409
+ at: u32,
410
+ d_next: u64,
411
+ ) -> Answer {
412
+ mem.write_bytes(start.add(at)?, &d_next.to_le_bytes())?;
413
+ Ok(())
414
+ }
415
+
416
+ /// A directory's entries from the `cookie`th on, cut off where the buffer
417
+ /// ends.
434
418
  pub(crate) fn readdir(
435
- table: &mut Descriptors,
436
- mem: &mut GuestMemory,
419
+ wasi: &mut Wasi,
420
+ mem: &mut GuestMemory<'_, '_>,
437
421
  fd: u32,
438
- buf: (u32, u32),
422
+ start: GuestPtr<u8>,
423
+ capacity: u32,
439
424
  cookie: u64,
440
- bufused: u32,
441
- ) -> Answer {
442
- let dir = match descriptor_mut(table, fd)? {
443
- Descriptor::Directory(dir) => dir,
444
- _ => return Err(Errno::Badf.into()),
445
- };
446
- let skip = usize::try_from(cookie).map_err(|_| Errno::Overflow)?;
447
- confirm(dir)?;
448
- let listing = match dir.listing.take() {
449
- Some(listing) if cookie != 0 => listing,
450
- _ => dir.mount.filesystem().read_dir(&dir.path)?,
451
- };
452
- let entries = [(".", FILETYPE_DIRECTORY), ("..", FILETYPE_DIRECTORY)]
453
- .into_iter()
454
- .chain(
455
- listing
456
- .iter()
457
- .map(|entry| (entry.name.as_str(), to_filetype(entry.file_type))),
458
- );
459
- let (start, capacity) = buf;
425
+ ) -> Answer<types::Size> {
426
+ let cred = wasi.cred().clone();
427
+ let mut dir = get_file_mut(wasi, fd)?;
428
+ // preview1 names where a listing goes on by its cookie, as wasi-libc's
429
+ // `seekdir` moves a directory's position before `getdents`; a listing going
430
+ // on from where the last one stopped needs no seek.
431
+ if cookie != dir.pos() {
432
+ let cookie = i64::try_from(cookie).map_err(|_| kobako_runtime::Errno::InvalidInput)?;
433
+ dir.llseek(cookie, Whence::Set)?;
434
+ }
460
435
  let mut used: u32 = 0;
461
- let mut full = false;
462
- 'entries: for (index, (name, filetype)) in entries.enumerate().skip(skip) {
463
- let mut dirent = [0u8; DIRENT_SIZE as usize];
464
- dirent[0..8].copy_from_slice(&(index as u64 + 1).to_le_bytes());
465
- dirent[16..20].copy_from_slice(&(name.len() as u32).to_le_bytes());
466
- dirent[20] = filetype;
467
- for part in [&dirent[..], name.as_bytes()] {
468
- let room = (capacity - used) as usize;
469
- let take = part.len().min(room);
470
- if take > 0 {
471
- mem.write(GuestMemory::field(start, used)?, &part[..take])?;
436
+ let mut failed = None;
437
+ let mut last_whole = None;
438
+ let mut actor = |emit: &DirEmit<'_>| {
439
+ let written = verify_dirent_name(emit.name)
440
+ .map_err(Into::into)
441
+ .and_then(|()| match last_whole.take() {
442
+ Some(at) => write_d_next(mem, start, at, emit.offset),
443
+ None => Ok(()),
444
+ })
445
+ .and_then(|()| write_dirent(mem, (start, capacity), &mut used, &cred, emit));
446
+ match written {
447
+ Ok(whole) => {
448
+ last_whole = whole;
449
+ whole.is_some()
472
450
  }
473
- used += take as u32;
474
- if used == capacity {
475
- full = true;
476
- break 'entries;
451
+ Err(error) => {
452
+ failed = Some(error);
453
+ false
477
454
  }
478
455
  }
456
+ };
457
+ let listed = dir.iterate_dir(&mut DirContext::new(0, &mut actor));
458
+ // The last entry written whole goes on from where the listing stopped,
459
+ // as `getdents64` sets the last `d_off` from `f_pos`.
460
+ if let Some(at) = last_whole {
461
+ write_d_next(mem, start, at, dir.pos())?;
479
462
  }
480
- if full {
481
- dir.listing = Some(listing);
463
+ // What was listed answers before what stopped the listing, which the next
464
+ // call meets first, as Linux's `getdents64` answers the bytes it wrote over
465
+ // `iterate_dir`'s error and `buf.error`.
466
+ match listed.err().map(Into::into).or(failed) {
467
+ Some(error) if used == 0 => Err(error),
468
+ _ => Ok(used),
482
469
  }
483
- mem.write_u32(bufused, used)
484
470
  }
485
471
 
486
- /// preview1 renumbering closes `to` as `fd_close` does, answering a close
487
- /// its Filesystem refuses, and moves `from` onto its number; both must
488
- /// already be open.
489
- pub(crate) fn renumber(table: &mut Descriptors, from: u32, to: u32) -> Answer {
490
- if table.get(from).is_none() || table.get(to).is_none() {
472
+ /// preview1 renumbering moves `from` onto `to`, both already open, then
473
+ /// closes what stood at `to`, ignoring how its close answers, as Linux's
474
+ /// `do_dup2` installs the file before `filp_close` of the one it replaced.
475
+ pub(crate) fn renumber(wasi: &mut Wasi, from: u32, to: u32) -> Answer {
476
+ if wasi.descriptors().get(from).is_none() || wasi.descriptors().get(to).is_none() {
491
477
  return Err(Errno::Badf.into());
492
478
  }
493
479
  if from == to {
494
480
  return Ok(());
495
481
  }
496
- close(table, to)?;
497
- let moved = table.remove(from).ok_or(Errno::Badf)?;
498
- table.place(to, moved);
482
+ let replaced = wasi.take(to).expect("found open above");
483
+ let descriptors = wasi.descriptors_mut();
484
+ let moved = descriptors.remove(from).expect("found open above");
485
+ descriptors.place(to, moved);
486
+ if let Some(file) = replaced {
487
+ let _ = file.close();
488
+ }
499
489
  Ok(())
500
490
  }
501
491
 
502
- pub(crate) fn seek(
503
- table: &mut Descriptors,
504
- mem: &mut GuestMemory,
505
- fd: u32,
506
- offset: i64,
507
- whence: u32,
508
- out: u32,
509
- ) -> Answer {
510
- args::variant(whence, args::WHENCE_MAX)?;
511
- let file = seekable(table, fd)?;
512
- let base = match whence {
513
- 0 => 0,
514
- 1 => file.position,
515
- _ => file.file.metadata()?.len,
492
+ pub(crate) fn seek(wasi: &mut Wasi, fd: u32, offset: i64, whence: types::Whence) -> Answer<u64> {
493
+ let whence = match whence {
494
+ types::Whence::Set => Whence::Set,
495
+ types::Whence::Cur => Whence::Cur,
496
+ types::Whence::End => Whence::End,
516
497
  };
517
- // Linux holds an offset in a signed 64-bit `off_t`, past which a seek
518
- // is `OVERFLOW` rather than a position a write could wrap around.
519
- let position = base.checked_add_signed(offset).ok_or(Errno::Inval)?;
520
- if position > i64::MAX as u64 {
521
- return Err(Errno::Overflow.into());
522
- }
523
- file.position = position;
524
- mem.write_u64(out, position)
498
+ Ok(get_seekable(wasi, fd)?.llseek(offset, whence)?)
525
499
  }
526
500
 
527
- pub(crate) fn tell(table: &mut Descriptors, mem: &mut GuestMemory, fd: u32, out: u32) -> Answer {
528
- let position = seekable(table, fd)?.position;
529
- mem.write_u64(out, position)
501
+ pub(crate) fn tell(wasi: &mut Wasi, fd: u32) -> Answer<u64> {
502
+ seek(wasi, fd, 0, types::Whence::Cur)
530
503
  }
531
504
 
532
505
  pub(crate) fn write(
533
- table: &mut Descriptors,
534
- mem: &mut GuestMemory,
506
+ wasi: &mut Wasi,
507
+ mem: &mut GuestMemory<'_, '_>,
535
508
  fd: u32,
536
- ciovs: (u32, u32),
537
- nwritten: u32,
538
- ) -> Answer {
539
- let (ptr, len) = mem.first_non_empty_buffer(ciovs.0, ciovs.1)?;
540
- let written = match descriptor_mut(table, fd)? {
541
- Descriptor::Channel(pipe) => write_channel(pipe, mem.bytes(ptr, len)?)?,
542
- Descriptor::File(file) => {
543
- // Bounded before the access is checked, as in `pwrite`.
544
- let buf = mem.bytes(ptr, len)?;
545
- if !file.writable {
546
- return Err(Errno::Badf.into());
547
- }
548
- let (at, written) = if file.append {
549
- file.file.append(buf)?
550
- } else {
551
- let buf = trim_to_largest_offset(buf, file.position)?;
552
- (file.position, file.file.write_at(buf, file.position)?)
553
- };
554
- file.position = at.checked_add(written as u64).ok_or(Errno::Fbig)?;
555
- written
556
- }
557
- Descriptor::Stdin(_) | Descriptor::Directory(_) => return Err(Errno::Badf.into()),
558
- };
559
- mem.write_u32(nwritten, written as u32)
560
- }
561
-
562
- /// A zero-length read of a stdin that still holds bytes is `INTR`, and one
563
- /// of a drained stdin reads nothing, as wasmtime-wasi's blocking read
564
- /// answers them.
565
- fn read_stdin(pipe: &mut MemoryInputPipe, len: usize) -> Answer<Vec<u8>> {
566
- match pipe.read(len) {
567
- Ok(bytes) if bytes.is_empty() => Err(Errno::Intr.into()),
568
- Ok(bytes) => Ok(bytes.to_vec()),
569
- Err(StreamError::Closed) => Ok(Vec::new()),
570
- Err(_) => Err(Errno::Io.into()),
571
- }
572
- }
573
-
574
- /// Fill the capture pipe as far as it holds. A pipe that fills before the
575
- /// bytes run out answers `IO`, though what fit is kept: the cap one past
576
- /// the configured limit is how a capture learns it was truncated.
577
- fn write_channel(pipe: &mut MemoryOutputPipe, bytes: &[u8]) -> Answer<usize> {
578
- for chunk in bytes.chunks(WRITE_CHUNK) {
579
- let mut rest = chunk;
580
- while !rest.is_empty() {
581
- let permit = pipe.check_write().map_err(|_| Errno::Io)?;
582
- let (now, later) = rest.split_at(rest.len().min(permit));
583
- pipe.write(Bytes::copy_from_slice(now))
584
- .map_err(|_| Errno::Io)?;
585
- rest = later;
586
- }
587
- }
588
- Ok(bytes.len())
509
+ ciovs: types::CiovecArray,
510
+ ) -> Answer<types::Size> {
511
+ let buf = mem.read_first_non_empty_ciovec(ciovs)?;
512
+ let mut file = get_file_mut(wasi, fd)?;
513
+ file.may_write()?;
514
+ Ok(file.write(mem.bytes(buf)?)? as u32)
589
515
  }
590
516
 
591
517
  #[cfg(test)]
@@ -594,79 +520,932 @@ mod tests {
594
520
  //! does, so its Filesystem learns of the close and may refuse it.
595
521
  use std::sync::Arc;
596
522
 
597
- use kobako_runtime::filesystem::{Access, File, FilesystemError, Memory, Metadata};
598
- use kobako_runtime::mount::Mount;
599
- use wasmtime_wasi::p2::pipe::{MemoryInputPipe, MemoryOutputPipe};
523
+ use super::{to_filetype, Filetype};
600
524
 
601
- use super::renumber;
602
- use crate::descriptors::{Descriptor, Descriptors, OpenFile};
603
- use crate::preview1::errno::{Errno, Failure};
525
+ // @behavior RT-195
526
+ #[test]
527
+ fn a_special_files_kind_reads_as_preview1_names_it() {
528
+ assert_eq!(
529
+ [
530
+ FileType::Sock,
531
+ FileType::Blkdev,
532
+ FileType::Chrdev,
533
+ FileType::Fifo,
534
+ FileType::Unknown,
535
+ ]
536
+ .map(to_filetype),
537
+ [
538
+ Filetype::SocketStream,
539
+ Filetype::BlockDevice,
540
+ Filetype::CharacterDevice,
541
+ Filetype::Unknown,
542
+ Filetype::Unknown,
543
+ ],
544
+ "to_filetype must name a socket as a stream, each device as itself, and a FIFO, which \
545
+ preview1 has no code for, as unknown"
546
+ );
547
+ }
548
+
549
+ use super::{
550
+ fdstat_get, fdstat_set_flags, filestat_set_size, filestat_set_times, readdir, renumber,
551
+ seek, sync, tell, utimensat, Answer, Errno, Fdflags, Fstflags,
552
+ };
553
+
554
+ /// `fd_filestat_set_times` of `fd` setting both times to zero as `flags`
555
+ /// ask, as the dispatcher answers it.
556
+ fn set_times(wasi: &Wasi, fd: u32, flags: Fstflags) -> Answer {
557
+ utimensat(0, 0, flags, |times| filestat_set_times(wasi, fd, times))
558
+ }
559
+ use crate::preview1::memory::GuestMemory;
560
+ use crate::preview1::path::{
561
+ create_directory, filestat_set_times as path_set_times, open as path_open, readlink,
562
+ rename, symlink, PathOpen,
563
+ };
564
+ use crate::preview1::types::{self, Rights, Whence};
565
+ use crate::wasi::Wasi;
566
+ use kobako_runtime::filesystem::{
567
+ FileOperations, FileType, Filesystem, InodeOperations, Kstat, Lookup,
568
+ };
569
+ use kobako_runtime::mount::{Access, Mount};
570
+ use kobako_runtime::security::prepare_creds;
571
+ use kobako_runtime::vfs::{self, Dentry, File, Inode, OpenHow, Path, PATH_MAX};
572
+ use wiggle::{GuestPtr, GuestType};
604
573
 
605
- /// A file whose Filesystem refuses to release it.
574
+ /// What `do_file_open` takes for an open `how` asks.
575
+ fn flags_of(how: &OpenHow) -> vfs::OpenFlags {
576
+ vfs::build_open_flags(how).expect("the flags must mean an open")
577
+ }
578
+
579
+ /// A context holding the three standard streams and `mounts`, at most
580
+ /// `limit` descriptors open, as a Driver makes one.
581
+ fn wasi_of(mounts: Vec<Mount>, limit: Option<usize>) -> Wasi {
582
+ Wasi::with_mounts(mounts, limit).unwrap_or_else(|_| panic!("the context must make"))
583
+ }
584
+
585
+ /// A context holding only the three standard streams.
586
+ fn standard_streams() -> Wasi {
587
+ wasi_of(Vec::new(), None)
588
+ }
589
+
590
+ /// The code a call answered, if it answered one.
591
+ fn errno<T>(answer: Answer<T>) -> Option<Errno> {
592
+ answer.err().and_then(|err| err.downcast().ok())
593
+ }
594
+
595
+ // @behavior RT-401
596
+ #[test]
597
+ fn a_standard_streams_descriptor_holds_its_pipe_apart_from_preview2s_handles() {
598
+ use crate::invocation::Invocation;
599
+ use crate::preview2::bindings::wasi_io_streams_0_2_12::{InputStream, OutputStream};
600
+ use crate::preview2::bindings::IoHost as _;
601
+
602
+ let config = crate::config::Config::for_profile(kobako_runtime::profile::Profile::Hermetic);
603
+ let mut guest = Invocation::new(Wasi::reading_stdin(&config, b"hi".to_vec()));
604
+ let read = guest.streams_input_stream_read(InputStream(1), 16).ok();
605
+ let dropped_while_open = guest.streams_output_stream_drop(OutputStream(2)).is_ok();
606
+ let closed = errno(super::close(guest.wasi_mut(), 1));
607
+ let dropped_once_closed = guest.streams_output_stream_drop(OutputStream(2)).is_ok();
608
+ assert_eq!(
609
+ (read, dropped_while_open, closed, dropped_once_closed),
610
+ (Some(b"hi".to_vec()), false, None, true),
611
+ "stdin's bytes must read through preview2's input-stream under handle 1, as \
612
+ wasi:cli's get-stdin hands it; dropping stdout's output-stream must trap while \
613
+ descriptor 1 stands over it, as the Canonical ABI traps a drop of a lent handle, and \
614
+ succeed once fd_close closed descriptor 1"
615
+ );
616
+ }
617
+
618
+ // @behavior RT-177
619
+ #[test]
620
+ fn a_standard_stream_answers_as_a_pipe_does() {
621
+ let mut wasi = standard_streams();
622
+ assert_eq!(
623
+ [
624
+ errno(sync(&mut wasi, 1, false)),
625
+ errno(filestat_set_size(&mut wasi, 1, 0)),
626
+ errno(tell(&mut wasi, 0)),
627
+ errno(tell(&mut wasi, 1)),
628
+ ],
629
+ [
630
+ Some(Errno::Inval),
631
+ Some(Errno::Inval),
632
+ Some(Errno::Spipe),
633
+ Some(Errno::Spipe)
634
+ ],
635
+ "fd_sync and fd_filestat_set_size on a standard stream through preview1 must answer \
636
+ EINVAL, and a call about its position ESPIPE, as Linux answers for a pipe"
637
+ );
638
+ }
639
+
640
+ /// A file whose Filesystem refuses to close it.
606
641
  struct RefusesClose;
607
642
 
608
- impl File for RefusesClose {
609
- fn read_at(&mut self, _buf: &mut [u8], _offset: u64) -> Result<usize, FilesystemError> {
610
- Ok(0)
643
+ impl FileOperations for RefusesClose {
644
+ fn flush(&mut self) -> Result<(), kobako_runtime::Errno> {
645
+ Err(kobako_runtime::Errno::PermissionDenied)
611
646
  }
647
+ }
612
648
 
613
- fn write_at(&mut self, buf: &[u8], _offset: u64) -> Result<usize, FilesystemError> {
614
- Ok(buf.len())
649
+ /// A file its Filesystem opens with no position.
650
+ struct Stream;
651
+
652
+ impl FileOperations for Stream {
653
+ fn is_stream(&self) -> bool {
654
+ true
655
+ }
656
+ }
657
+
658
+ /// A directory holding at every name an entry of the kind it names, whose
659
+ /// open answers what its function makes.
660
+ struct Holds(FileType, fn() -> Box<dyn FileOperations>);
661
+
662
+ /// A directory holding a file its Filesystem refuses to close.
663
+ const HOLDS_REFUSES_CLOSE: Holds = Holds(FileType::RegFile, || Box::new(RefusesClose));
664
+
665
+ impl kobako_runtime::filesystem::FileSystemType for Holds {
666
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), kobako_runtime::Errno> {
667
+ sb.d_make_root(kobako_runtime::vfs::Inode::new(
668
+ &kobako_runtime::Kstat::new(kobako_runtime::FileType::Dir, 0),
669
+ self,
670
+ ));
671
+ Ok(())
672
+ }
673
+ }
674
+
675
+ impl InodeOperations for Holds {
676
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, kobako_runtime::Errno> {
677
+ Ok(Kstat::new(FileType::Dir, 0))
615
678
  }
616
679
 
617
- fn append(&mut self, buf: &[u8]) -> Result<(u64, usize), FilesystemError> {
618
- Ok((0, buf.len()))
680
+ fn lookup(&self, _dentry: &Dentry) -> Result<Lookup, kobako_runtime::Errno> {
681
+ let found = Kstat::new(self.0, 0);
682
+ Ok(Lookup::Found(Inode::new(
683
+ &found,
684
+ Arc::new(Self(self.0, self.1)),
685
+ )))
619
686
  }
620
687
 
621
- fn metadata(&self) -> Result<Metadata, FilesystemError> {
622
- Err(FilesystemError::Unsupported)
688
+ fn open(
689
+ &self,
690
+ _dentry: &Dentry,
691
+ _options: &OpenHow,
692
+ ) -> Result<Box<dyn FileOperations>, kobako_runtime::Errno> {
693
+ Ok((self.1)())
623
694
  }
695
+ }
696
+
697
+ /// The file `holds` holds, opened as `how` asks beneath a Mount that
698
+ /// writes when `how` does.
699
+ fn open_held(holds: Holds, how: &OpenHow) -> File {
700
+ let access = match how.write {
701
+ true => Access::ReadWrite,
702
+ false => Access::Read,
703
+ };
704
+ let mount = Mount::new(
705
+ "/data",
706
+ Filesystem::new(holds).expect("the instance must stand"),
707
+ access,
708
+ )
709
+ .expect("/data is a guest path");
710
+ let start = Path::root(mount.mnt());
711
+ vfs::do_file_open(&prepare_creds(&[], None), &start, "file", &flags_of(how))
712
+ .unwrap_or_else(|_| panic!("the file must open"))
713
+ }
714
+
715
+ fn open_file() -> File {
716
+ let mut how = OpenHow::default();
717
+ how.read = true;
718
+ open_held(HOLDS_REFUSES_CLOSE, &how)
719
+ }
624
720
 
625
- fn set_len(&mut self, _len: u64) -> Result<(), FilesystemError> {
721
+ // @behavior RT-176
722
+ #[test]
723
+ fn a_file_without_fsync_refuses_a_sync() {
724
+ let mut wasi = standard_streams();
725
+ let fd = wasi.push_file(open_file()).expect("a descriptor to sync");
726
+ assert_eq!(
727
+ errno(sync(&mut wasi, fd, false)),
728
+ Some(Errno::Inval),
729
+ "fd_sync on a file whose Filesystem has no fsync must answer EINVAL"
730
+ );
731
+ }
732
+
733
+ // @behavior RT-129
734
+ #[test]
735
+ fn a_file_set_not_to_block_reports_it() {
736
+ let mut wasi = standard_streams();
737
+ let fd = wasi.push_file(open_file()).expect("a descriptor to set");
738
+ let flags = |wasi: &Wasi| {
739
+ fdstat_get(wasi, fd)
740
+ .unwrap_or_else(|_| panic!("the file must report its flags"))
741
+ .fs_flags
742
+ };
743
+ assert!(
744
+ fdstat_set_flags(&mut wasi, fd, Fdflags::NONBLOCK | Fdflags::SYNC).is_ok(),
745
+ "fd_fdstat_set_flags asking not to block and to sync must succeed, as Linux's setfl"
746
+ );
747
+ assert_eq!(
748
+ flags(&wasi),
749
+ Fdflags::NONBLOCK,
750
+ "fd_fdstat_get after fd_fdstat_set_flags must report not blocking and, as Linux's \
751
+ setfl ignores it, no sync"
752
+ );
753
+ }
754
+
755
+ // A pipe end is open one way only, so a stream open both ways comes from
756
+ // a Filesystem's open.
757
+ // @behavior RT-275
758
+ #[test]
759
+ fn a_stream_reports_what_it_was_opened_and_set_for() {
760
+ let mut wasi = standard_streams();
761
+ let mut how = OpenHow::default();
762
+ how.read = true;
763
+ how.write = true;
764
+ let fd = wasi
765
+ .push_file(open_held(
766
+ Holds(FileType::RegFile, || Box::new(Stream)),
767
+ &how,
768
+ ))
769
+ .expect("a descriptor to set");
770
+ assert!(
771
+ fdstat_set_flags(&mut wasi, fd, Fdflags::APPEND | Fdflags::NONBLOCK).is_ok(),
772
+ "fd_fdstat_set_flags asking a stream to append and not to block must succeed"
773
+ );
774
+ let stat = fdstat_get(&wasi, fd).unwrap_or_else(|_| panic!("the stream must report"));
775
+ assert_eq!(
776
+ (
777
+ stat.fs_flags,
778
+ stat.fs_rights_base
779
+ .contains(Rights::FD_READ | Rights::FD_WRITE)
780
+ ),
781
+ (Fdflags::APPEND | Fdflags::NONBLOCK, true),
782
+ "fd_fdstat_get on a stream open to read and write, set to append and not to block, \
783
+ must report both flags and both rights, as Linux's F_GETFL reports a pipe's"
784
+ );
785
+ }
786
+
787
+ // @behavior RT-276
788
+ #[test]
789
+ fn a_descriptor_reports_the_kind_its_file_is() {
790
+ let mut wasi = standard_streams();
791
+ let fd = wasi
792
+ .push_file(open_held(
793
+ Holds(FileType::Chrdev, || Box::new(RefusesClose)),
794
+ &OpenHow::default(),
795
+ ))
796
+ .expect("a descriptor to ask about");
797
+ assert_eq!(
798
+ fdstat_get(&wasi, fd)
799
+ .unwrap_or_else(|_| panic!("the device must report"))
800
+ .fs_filetype,
801
+ types::Filetype::CharacterDevice,
802
+ "fd_fdstat_get on a character device opened for its path alone must report a \
803
+ character device, as fd_filestat_get does"
804
+ );
805
+ }
806
+
807
+ // wasi-testsuite's dir_fd_op_failures names these answers and writes that
808
+ // they part from POSIX, where a directory seeks.
809
+ // @behavior RT-184
810
+ #[test]
811
+ fn a_directory_refuses_a_call_about_its_position() {
812
+ let mount = Mount::new(
813
+ "/data",
814
+ Filesystem::new(HOLDS_REFUSES_CLOSE).expect("the instance must stand"),
815
+ Access::Read,
816
+ )
817
+ .expect("/data is a guest path");
818
+ let mut wasi = wasi_of(vec![mount], None);
819
+ assert_eq!(
820
+ (
821
+ errno(tell(&mut wasi, 3)),
822
+ errno(seek(&mut wasi, 3, 0, Whence::Set)),
823
+ ),
824
+ (Some(Errno::Badf), Some(Errno::Badf)),
825
+ "fd_tell and fd_seek on a directory through preview1 must answer EBADF, as \
826
+ wasi-testsuite requires"
827
+ );
828
+ }
829
+
830
+ // @behavior RT-392
831
+ #[test]
832
+ fn a_descriptor_reports_how_far_it_was_opened_to_sync() {
833
+ let tmpfs: kobako_runtime::filesystem::Tmpfs = [("f", "x")].into_iter().collect();
834
+ let mount = Mount::new(
835
+ "/data",
836
+ Filesystem::new(tmpfs).expect("the instance must stand"),
837
+ Access::ReadWrite,
838
+ )
839
+ .expect("/data is a guest path");
840
+ let mut wasi = wasi_of(vec![mount], None);
841
+ let mut bytes = b"f".to_vec();
842
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
843
+ let mem = GuestMemory::new(&mut memory, 64);
844
+ let mut reported = |fdflags| {
845
+ let call = PathOpen {
846
+ dirflags: types::Lookupflags::empty(),
847
+ oflags: types::Oflags::empty(),
848
+ rights_base: Rights::FD_WRITE,
849
+ fdflags,
850
+ };
851
+ let fd = path_open(&mut wasi, &mem, 3, GuestPtr::new((0, 1)), &call)
852
+ .unwrap_or_else(|_| panic!("the file must open"));
853
+ let Ok(stat) = fdstat_get(&wasi, fd.into()) else {
854
+ panic!("the descriptor must report itself");
855
+ };
856
+ stat.fs_flags & (Fdflags::DSYNC | Fdflags::SYNC | Fdflags::RSYNC)
857
+ };
858
+ let every = Fdflags::DSYNC | Fdflags::SYNC | Fdflags::RSYNC;
859
+ assert_eq!(
860
+ [
861
+ reported(Fdflags::DSYNC),
862
+ reported(Fdflags::SYNC),
863
+ reported(Fdflags::RSYNC)
864
+ ],
865
+ [Fdflags::DSYNC, every, every],
866
+ "fd_fdstat_get must report DSYNC alone for a file path_open opened O_DSYNC, and DSYNC, \
867
+ SYNC, and RSYNC for one opened O_SYNC or O_RSYNC, as Linux's O_RSYNC is O_SYNC"
868
+ );
869
+ }
870
+
871
+ /// Allows every path, counting each it is asked about.
872
+ #[derive(Default)]
873
+ struct CountsAsks(std::sync::atomic::AtomicUsize);
874
+
875
+ impl kobako_runtime::policy::Policy<kobako_runtime::mount::MountRequest<'_>> for CountsAsks {
876
+ fn allows(&self, _request: &kobako_runtime::mount::MountRequest<'_>) -> bool {
877
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
878
+ true
879
+ }
880
+ }
881
+
882
+ // The guard sits in the Driver rather than the VFS, so only this call shows
883
+ // that setting a descriptor's times asks it.
884
+ // @behavior RT-201
885
+ #[test]
886
+ fn setting_a_descriptors_times_asks_whether_it_still_stands() {
887
+ use std::sync::atomic::Ordering;
888
+ let policy = Arc::new(CountsAsks::default());
889
+ let tmpfs: kobako_runtime::filesystem::Tmpfs = [("f", "x")].into_iter().collect();
890
+ let mount = Mount::new(
891
+ "/data",
892
+ Filesystem::new(tmpfs).expect("the instance must stand"),
893
+ Access::ReadWrite,
894
+ )
895
+ .expect("/data is a guest path")
896
+ .with_policy(policy.clone());
897
+ let root = Path::root(mount.mnt());
898
+ let mut wasi = wasi_of(vec![mount], None);
899
+ let cred = wasi.cred().clone();
900
+ let mut read = OpenHow::default();
901
+ read.read = true;
902
+ let opened = vfs::do_file_open(&cred, &root, "f", &flags_of(&read))
903
+ .unwrap_or_else(|_| panic!("the file must open"));
904
+ let fd = wasi
905
+ .push_file(opened)
906
+ .unwrap_or_else(|| panic!("the table must have room"));
907
+ vfs::filename_unlinkat(&cred, &root, "f").unwrap_or_else(|_| panic!("the name must go"));
908
+ policy.0.store(0, Ordering::SeqCst);
909
+ assert_eq!(
910
+ (
911
+ errno(set_times(&wasi, fd, Fstflags::ATIM_NOW)),
912
+ policy.0.load(Ordering::SeqCst)
913
+ ),
914
+ (Some(Errno::Noent), 0),
915
+ "fd_filestat_set_times through a descriptor of a file whose name is gone, beneath a \
916
+ Policy, must answer ENOENT without asking the Policy about the path it stood at"
917
+ );
918
+ }
919
+
920
+ // @behavior RT-186 RT-187
921
+ #[test]
922
+ fn setting_a_descriptors_times_answers_as_a_paths_do() {
923
+ let mount = Mount::new(
924
+ "/data",
925
+ Filesystem::new(HOLDS_REFUSES_CLOSE).expect("the instance must stand"),
926
+ Access::Read,
927
+ )
928
+ .expect("/data is a guest path");
929
+ let wasi = wasi_of(vec![mount], None);
930
+ assert_eq!(
931
+ (
932
+ errno(set_times(&wasi, 3, Fstflags::MTIM)),
933
+ errno(set_times(&wasi, 3, Fstflags::empty())),
934
+ errno(set_times(&wasi, 3, Fstflags::MTIM | Fstflags::MTIM_NOW)),
935
+ ),
936
+ (Some(Errno::Rofs), None, Some(Errno::Inval)),
937
+ "fd_filestat_set_times beneath a read-only Mount through preview1 must answer EROFS, \
938
+ a call asking no time must succeed, and one asking a time and now EINVAL"
939
+ );
940
+ }
941
+
942
+ // @behavior RT-185
943
+ #[test]
944
+ fn a_path_call_starting_from_a_file_is_not_a_directory() {
945
+ let mut wasi = standard_streams();
946
+ let fd = wasi
947
+ .push_file(open_file())
948
+ .expect("a descriptor to start from");
949
+ let mut bytes = *b"a";
950
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
951
+ let mem = GuestMemory::new(&mut memory, 1);
952
+ assert_eq!(
953
+ errno(create_directory(&wasi, &mem, fd, GuestPtr::new((0, 1)))),
954
+ Some(Errno::Notdir),
955
+ "path_create_directory starting from a file through preview1 must answer ENOTDIR, as \
956
+ Linux refuses a walk starting there"
957
+ );
958
+ }
959
+
960
+ // Linux reads the flags and the path before it looks at where a walk starts,
961
+ // so a Driver checking the start first would hide each of these.
962
+ // @behavior RT-225 RT-230 RT-231 RT-232
963
+ #[test]
964
+ fn a_call_no_walk_can_take_answers_before_where_it_starts() {
965
+ let mut wasi = standard_streams();
966
+ let fd = wasi
967
+ .push_file(open_file())
968
+ .expect("a descriptor to start from");
969
+ let mut bytes = vec![b'a'; PATH_MAX];
970
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
971
+ let mem = GuestMemory::new(&mut memory, 2 * PATH_MAX);
972
+ let call = PathOpen {
973
+ dirflags: types::Lookupflags::empty(),
974
+ oflags: types::Oflags::CREAT | types::Oflags::DIRECTORY,
975
+ rights_base: Rights::FD_READ,
976
+ fdflags: Fdflags::empty(),
977
+ };
978
+ let path = |len| GuestPtr::new((0, len));
979
+ assert_eq!(
980
+ (
981
+ errno(path_open(&mut wasi, &mem, fd, path(1), &call)),
982
+ errno(create_directory(&wasi, &mem, fd, path(0))),
983
+ errno(create_directory(&wasi, &mem, fd, path(PATH_MAX as u32))),
984
+ errno(utimensat(0, 0, Fstflags::empty(), |times| path_set_times(
985
+ &wasi,
986
+ &mem,
987
+ fd,
988
+ types::Lookupflags::empty(),
989
+ path(1),
990
+ times
991
+ ))),
992
+ ),
993
+ (
994
+ Some(Errno::Inval),
995
+ Some(Errno::Noent),
996
+ Some(Errno::Nametoolong),
997
+ None
998
+ ),
999
+ "path_open with O_CREAT and O_DIRECTORY, and path_create_directory of an empty and of \
1000
+ an overlong path, starting from a file through preview1 must answer EINVAL, ENOENT, \
1001
+ and ENAMETOOLONG, and path_filestat_set_times setting no time must succeed"
1002
+ );
1003
+ }
1004
+
1005
+ // Linux reads the flags and the name before `path_init` takes the
1006
+ // descriptor, so a number naming nothing answers only once both are fine.
1007
+ // @behavior RT-257 RT-258
1008
+ #[test]
1009
+ fn a_call_no_walk_can_take_answers_before_the_descriptor_it_names() {
1010
+ let mut wasi = standard_streams();
1011
+ let mut bytes = vec![b'a'; PATH_MAX];
1012
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1013
+ let mem = GuestMemory::new(&mut memory, 2 * PATH_MAX);
1014
+ let call = |oflags| PathOpen {
1015
+ dirflags: types::Lookupflags::empty(),
1016
+ oflags,
1017
+ rights_base: Rights::FD_READ,
1018
+ fdflags: Fdflags::empty(),
1019
+ };
1020
+ let path = |len| GuestPtr::new((0, len));
1021
+ let unopened = 99;
1022
+ let create_dir = call(types::Oflags::CREAT | types::Oflags::DIRECTORY);
1023
+ assert_eq!(
1024
+ (
1025
+ errno(path_open(&mut wasi, &mem, unopened, path(1), &create_dir)),
1026
+ errno(create_directory(&wasi, &mem, unopened, path(0))),
1027
+ errno(create_directory(
1028
+ &wasi,
1029
+ &mem,
1030
+ unopened,
1031
+ path(PATH_MAX as u32)
1032
+ )),
1033
+ errno(create_directory(&wasi, &mem, unopened, path(1))),
1034
+ ),
1035
+ (
1036
+ Some(Errno::Inval),
1037
+ Some(Errno::Noent),
1038
+ Some(Errno::Nametoolong),
1039
+ Some(Errno::Badf)
1040
+ ),
1041
+ "path_open with O_CREAT and O_DIRECTORY, and path_create_directory of an empty and of \
1042
+ an overlong path, from a descriptor number naming nothing through preview1 must \
1043
+ answer EINVAL, ENOENT, and ENAMETOOLONG, and a path a walk can take EBADF"
1044
+ );
1045
+ }
1046
+
1047
+ // Standard output is a pipe's end, so a walk from it answers ENOTDIR; the
1048
+ // second path is wrong too, so only the order picks which answers.
1049
+ // @behavior RT-286
1050
+ #[test]
1051
+ fn a_call_naming_two_paths_answers_for_its_first_before_its_second() {
1052
+ let wasi = standard_streams();
1053
+ let mut bytes = vec![b'a'; PATH_MAX];
1054
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1055
+ let mem = GuestMemory::new(&mut memory, 2 * PATH_MAX);
1056
+ let path = |len| GuestPtr::new((0, len));
1057
+ let (stdout, unopened) = (1, 99);
1058
+ assert_eq!(
1059
+ (
1060
+ errno(rename(
1061
+ &wasi,
1062
+ &mem,
1063
+ (stdout, path(1)),
1064
+ (stdout, path(PATH_MAX as u32))
1065
+ )),
1066
+ errno(rename(&wasi, &mem, (stdout, path(1)), (unopened, path(1)))),
1067
+ ),
1068
+ (Some(Errno::Notdir), Some(Errno::Notdir)),
1069
+ "path_rename from standard output to a path past PATH_MAX, or to a descriptor \
1070
+ number naming nothing, through preview1 must answer ENOTDIR for the first path"
1071
+ );
1072
+ }
1073
+
1074
+ // @behavior RT-287
1075
+ #[test]
1076
+ fn an_absolute_path_answers_before_the_descriptor_it_names() {
1077
+ let wasi = standard_streams();
1078
+ let mut bytes = b"/a".to_vec();
1079
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1080
+ let mem = GuestMemory::new(&mut memory, 16);
1081
+ assert_eq!(
1082
+ errno(create_directory(&wasi, &mem, 99, GuestPtr::new((0, 2)))),
1083
+ Some(Errno::Notcapable),
1084
+ "path_create_directory of an absolute path from a descriptor number naming nothing \
1085
+ through preview1 must answer ENOTCAPABLE, as path_init looks at no descriptor"
1086
+ );
1087
+ }
1088
+
1089
+ // @behavior RT-277
1090
+ #[test]
1091
+ fn a_readlink_into_no_room_is_invalid() {
1092
+ let wasi = standard_streams();
1093
+ let mut bytes = vec![0u8; 8];
1094
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1095
+ let mut mem = GuestMemory::new(&mut memory, 16);
1096
+ assert_eq!(
1097
+ errno(readlink(
1098
+ &wasi,
1099
+ &mut mem,
1100
+ 99,
1101
+ GuestPtr::new((0, 0)),
1102
+ GuestPtr::new(0),
1103
+ 0
1104
+ )),
1105
+ Some(Errno::Inval),
1106
+ "path_readlink into a buffer of no bytes, of an empty path from a descriptor number \
1107
+ naming nothing, through preview1 must answer EINVAL, as do_readlinkat refuses the \
1108
+ size first"
1109
+ );
1110
+ }
1111
+
1112
+ // Linux's `do_readlinkat` takes its name with `LOOKUP_EMPTY`, so an empty
1113
+ // path names the descriptor itself: one naming nothing answers as
1114
+ // `path_init` does, and a file, which is no link, as not found. The file
1115
+ // also shows the start need not be a directory.
1116
+ // @behavior RT-289
1117
+ #[test]
1118
+ fn a_readlink_of_an_empty_path_answers_for_its_descriptor() {
1119
+ let mut wasi = standard_streams();
1120
+ let fd = wasi
1121
+ .push_file(open_file())
1122
+ .expect("a descriptor to start from");
1123
+ let mut bytes = vec![0u8; 8];
1124
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1125
+ let mut mem = GuestMemory::new(&mut memory, 16);
1126
+ let mut empty_from = |start| {
1127
+ errno(readlink(
1128
+ &wasi,
1129
+ &mut mem,
1130
+ start,
1131
+ GuestPtr::new((0, 0)),
1132
+ GuestPtr::new(0),
1133
+ 8,
1134
+ ))
1135
+ };
1136
+ assert_eq!(
1137
+ (empty_from(99), empty_from(fd)),
1138
+ (Some(Errno::Badf), Some(Errno::Noent)),
1139
+ "path_readlink of an empty path through preview1 must answer EBADF from a descriptor \
1140
+ number naming nothing and ENOENT from a file, as do_readlinkat reads the descriptor \
1141
+ itself"
1142
+ );
1143
+ }
1144
+
1145
+ // Linux's `utimensat` answers a call asking no time before it takes the
1146
+ // name or the descriptor, so a number naming nothing never shows.
1147
+ // @behavior RT-271
1148
+ #[test]
1149
+ fn a_call_asking_no_time_succeeds_whatever_descriptor_it_names() {
1150
+ let wasi = standard_streams();
1151
+ let mut bytes = *b"a";
1152
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1153
+ let mem = GuestMemory::new(&mut memory, 1);
1154
+ let unopened = 99;
1155
+ assert_eq!(
1156
+ (
1157
+ errno(set_times(&wasi, unopened, Fstflags::empty())),
1158
+ errno(utimensat(0, 0, Fstflags::empty(), |times| path_set_times(
1159
+ &wasi,
1160
+ &mem,
1161
+ unopened,
1162
+ types::Lookupflags::empty(),
1163
+ GuestPtr::new((0, 1)),
1164
+ times
1165
+ ))),
1166
+ ),
1167
+ (None, None),
1168
+ "fd_filestat_set_times and path_filestat_set_times asking no time through preview1 \
1169
+ must succeed from a descriptor number naming nothing"
1170
+ );
1171
+ }
1172
+
1173
+ // Linux's `do_sys_openat2` reads the flags before `FD_ADD` reserves a
1174
+ // descriptor, and the name before the walk looks at where it starts.
1175
+ // @behavior RT-259
1176
+ #[test]
1177
+ fn a_full_table_answers_after_the_flags_and_before_the_start() {
1178
+ let mut wasi = wasi_of(Vec::new(), Some(3));
1179
+ let mut bytes = *b"a";
1180
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1181
+ let mem = GuestMemory::new(&mut memory, 1);
1182
+ let call = |oflags| PathOpen {
1183
+ dirflags: types::Lookupflags::empty(),
1184
+ oflags,
1185
+ rights_base: Rights::FD_READ,
1186
+ fdflags: Fdflags::empty(),
1187
+ };
1188
+ let unopened = 99;
1189
+ let path = GuestPtr::new((0, 1));
1190
+ assert_eq!(
1191
+ (
1192
+ errno(path_open(
1193
+ &mut wasi,
1194
+ &mem,
1195
+ unopened,
1196
+ path,
1197
+ &call(types::Oflags::CREAT | types::Oflags::DIRECTORY)
1198
+ )),
1199
+ errno(path_open(
1200
+ &mut wasi,
1201
+ &mem,
1202
+ unopened,
1203
+ path,
1204
+ &call(types::Oflags::empty())
1205
+ )),
1206
+ ),
1207
+ (Some(Errno::Inval), Some(Errno::Mfile)),
1208
+ "path_open with no descriptor left through preview1 must answer EINVAL for O_CREAT \
1209
+ with O_DIRECTORY, and EMFILE from a descriptor number naming nothing"
1210
+ );
1211
+ }
1212
+
1213
+ /// A directory listing `ok` and then `bad`, whatever `bad` is.
1214
+ struct ListsNames(&'static str);
1215
+
1216
+ impl kobako_runtime::filesystem::FileSystemType for ListsNames {
1217
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), kobako_runtime::Errno> {
1218
+ sb.d_make_root(kobako_runtime::vfs::Inode::new(
1219
+ &kobako_runtime::Kstat::new(kobako_runtime::FileType::Dir, 0),
1220
+ self,
1221
+ ));
626
1222
  Ok(())
627
1223
  }
1224
+ }
1225
+
1226
+ impl InodeOperations for ListsNames {
1227
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, kobako_runtime::Errno> {
1228
+ Ok(Kstat::new(FileType::Dir, 0))
1229
+ }
628
1230
 
629
- fn close(self: Box<Self>) -> Result<(), FilesystemError> {
630
- Err(FilesystemError::PermissionDenied)
1231
+ fn open(
1232
+ &self,
1233
+ _dentry: &Dentry,
1234
+ _options: &OpenHow,
1235
+ ) -> Result<Box<dyn FileOperations>, kobako_runtime::Errno> {
1236
+ Ok(Box::new(Self(self.0)))
631
1237
  }
632
1238
  }
633
1239
 
634
- fn open_file() -> Descriptor {
635
- Descriptor::File(OpenFile {
636
- file: Box::new(RefusesClose),
637
- position: 0,
638
- append: false,
639
- readable: true,
640
- writable: false,
641
- mount: Arc::new(
642
- Mount::new("/data", Arc::new(Memory::new()), Access::Read)
643
- .expect("/data is a guest path"),
1240
+ impl FileOperations for ListsNames {
1241
+ fn iterate_shared(
1242
+ &mut self,
1243
+ dentry: &Dentry,
1244
+ ctx: &mut vfs::DirContext<'_>,
1245
+ ) -> Result<(), kobako_runtime::Errno> {
1246
+ let entries = vec![
1247
+ vfs::DirEntry::new("ok", FileType::RegFile),
1248
+ vfs::DirEntry::new(self.0, FileType::RegFile),
1249
+ ];
1250
+ kobako_runtime::filesystem::Rdir::default().iterate_shared(dentry, ctx, || Ok(entries))
1251
+ }
1252
+ }
1253
+
1254
+ /// Each whole `dirent` in `bytes`, as its name and its `d_next`.
1255
+ fn dirents(bytes: &[u8]) -> Vec<(String, u64)> {
1256
+ let header = types::Dirent::guest_size() as usize;
1257
+ let mut seen = Vec::new();
1258
+ let mut at = 0;
1259
+ while at + header <= bytes.len() {
1260
+ let field = |from: usize, len: usize| &bytes[at + from..at + from + len];
1261
+ let d_next = u64::from_le_bytes(field(0, 8).try_into().expect("eight bytes"));
1262
+ let namlen = u32::from_le_bytes(field(16, 4).try_into().expect("four bytes")) as usize;
1263
+ if at + header + namlen > bytes.len() {
1264
+ break;
1265
+ }
1266
+ let name = String::from_utf8_lossy(field(header, namlen)).into_owned();
1267
+ seen.push((name, d_next));
1268
+ at += header + namlen;
1269
+ }
1270
+ seen
1271
+ }
1272
+
1273
+ // The first buffer holds `.` and `..` exactly, so `..` learns where the
1274
+ // listing goes on only from the entry refused after it, as `filldir64`
1275
+ // writes `prev->d_off`, and the last entry of the second from where the
1276
+ // listing stopped, as `getdents64` sets it from `f_pos`.
1277
+ // @behavior RT-182
1278
+ #[test]
1279
+ fn each_listed_entry_names_where_the_listing_goes_on() {
1280
+ let mount = Mount::new(
1281
+ "/data",
1282
+ Filesystem::new(ListsNames("bb")).expect("the instance must stand"),
1283
+ Access::Read,
1284
+ )
1285
+ .expect("/data is a guest path");
1286
+ let mut wasi = wasi_of(vec![mount], None);
1287
+ let header = types::Dirent::guest_size();
1288
+ let dots = 2 * header + 3;
1289
+ let mut bytes = vec![0u8; 256];
1290
+ let used = {
1291
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1292
+ let mut mem = GuestMemory::new(&mut memory, 256);
1293
+ let first = readdir(&mut wasi, &mut mem, 3, GuestPtr::new(0), dots, 0);
1294
+ let rest = readdir(&mut wasi, &mut mem, 3, GuestPtr::new(128), 128, 2);
1295
+ (first.ok(), rest.ok())
1296
+ };
1297
+ let entry = |name: &str, d_next| (name.to_string(), d_next);
1298
+ assert_eq!(
1299
+ (
1300
+ used,
1301
+ dirents(&bytes[..dots as usize]),
1302
+ dirents(&bytes[128..128 + 2 * (header as usize + 2)])
644
1303
  ),
645
- })
1304
+ (
1305
+ (Some(dots), Some(2 * (header + 2))),
1306
+ vec![entry(".", 1), entry("..", 2)],
1307
+ vec![entry("ok", 3), entry("bb", 4)],
1308
+ ),
1309
+ "fd_readdir through preview1 must give each whole entry the cookie a listing goes on \
1310
+ from past it, the one filling the buffer included, and the last the position the \
1311
+ listing stopped at"
1312
+ );
646
1313
  }
647
1314
 
648
- // @behavior RT-114
1315
+ // A built-in Filesystem cannot hold such a name, so only one that hands it
1316
+ // over shows the listing refuses it; Linux's `getdents64` answers what came
1317
+ // before it and leaves the name to the next call, whose cookie stands on it.
1318
+ // @behavior RT-212 RT-269
649
1319
  #[test]
650
- fn renumbering_onto_an_open_file_closes_it_first() {
651
- let mut table = Descriptors::new(
652
- MemoryInputPipe::new(Vec::new()),
653
- MemoryOutputPipe::new(1),
654
- MemoryOutputPipe::new(1),
655
- Vec::new(),
656
- None,
1320
+ fn a_listing_stops_at_a_name_no_directory_can_hold() {
1321
+ let listed = |bad: &'static str| {
1322
+ let mount = Mount::new(
1323
+ "/data",
1324
+ Filesystem::new(ListsNames(bad)).expect("the instance must stand"),
1325
+ Access::Read,
1326
+ )
1327
+ .expect("/data is a guest path");
1328
+ let mut wasi = wasi_of(vec![mount], None);
1329
+ let mut bytes = vec![0u8; 256];
1330
+ let (first, next) = {
1331
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1332
+ let mut mem = GuestMemory::new(&mut memory, 256);
1333
+ let buf = GuestPtr::new(0);
1334
+ let first = readdir(&mut wasi, &mut mem, 3, buf, 256, 0).ok();
1335
+ (first, errno(readdir(&mut wasi, &mut mem, 3, buf, 256, 3)))
1336
+ };
1337
+ let handed_over = bytes.windows(bad.len().max(1)).any(|w| w == bad.as_bytes());
1338
+ (
1339
+ first.is_some_and(|used| used > 0),
1340
+ next,
1341
+ handed_over && !bad.is_empty(),
1342
+ )
1343
+ };
1344
+ assert_eq!(
1345
+ (listed("../escape"), listed("")),
1346
+ ((true, Some(Errno::Io), false), (true, Some(Errno::Io), false)),
1347
+ "fd_readdir through preview1 of a Filesystem listing `ok` and then a name with a `/` or \
1348
+ an empty one must hand over what came before it, and answer EIO from where it stands, \
1349
+ handing over no such name"
657
1350
  );
658
- let from = table.push(open_file()).expect("a descriptor to move");
659
- let to = table.push(open_file()).expect("a descriptor to move onto");
660
- assert!(
661
- matches!(
662
- renumber(&mut table, from, to),
663
- Err(Failure::Errno(Errno::Acces))
1351
+ }
1352
+
1353
+ /// A directory that would make any link it is asked to.
1354
+ struct MakesLinks;
1355
+
1356
+ impl kobako_runtime::filesystem::FileSystemType for MakesLinks {
1357
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), kobako_runtime::Errno> {
1358
+ sb.d_make_root(kobako_runtime::vfs::Inode::new(
1359
+ &kobako_runtime::Kstat::new(kobako_runtime::FileType::Dir, 0),
1360
+ self,
1361
+ ));
1362
+ Ok(())
1363
+ }
1364
+ }
1365
+
1366
+ impl InodeOperations for MakesLinks {
1367
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, kobako_runtime::Errno> {
1368
+ Ok(Kstat::new(FileType::Dir, 0))
1369
+ }
1370
+
1371
+ fn lookup(&self, _dentry: &Dentry) -> Result<Lookup, kobako_runtime::Errno> {
1372
+ Ok(Lookup::Absent)
1373
+ }
1374
+
1375
+ fn symlink(&self, _dentry: &Dentry, _target: &str) -> Result<(), kobako_runtime::Errno> {
1376
+ Ok(())
1377
+ }
1378
+ }
1379
+
1380
+ // No built-in Filesystem makes a link, so only one that would shows the
1381
+ // call stopped here.
1382
+ // @behavior RT-202
1383
+ #[test]
1384
+ fn a_link_to_an_absolute_path_is_not_made() {
1385
+ let mount = Mount::new(
1386
+ "/data",
1387
+ Filesystem::new(MakesLinks).expect("the instance must stand"),
1388
+ Access::ReadWrite,
1389
+ )
1390
+ .expect("/data is a guest path");
1391
+ let wasi = wasi_of(vec![mount], None);
1392
+ let mut bytes = *b"/trelative";
1393
+ let mut memory = wiggle::GuestMemory::Unshared(&mut bytes);
1394
+ let mem = GuestMemory::new(&mut memory, 64);
1395
+ let (absolute, relative, name) = (
1396
+ GuestPtr::new((0, 2)),
1397
+ GuestPtr::new((1, 1)),
1398
+ GuestPtr::new((2, 8)),
1399
+ );
1400
+ assert_eq!(
1401
+ (
1402
+ errno(symlink(&wasi, &mem, absolute, 3, name)),
1403
+ errno(symlink(&wasi, &mem, relative, 3, name)),
664
1404
  ),
665
- "fd_renumber onto a file whose Filesystem refuses the close must answer that refusal"
1405
+ (Some(Errno::Perm), None),
1406
+ "path_symlink through preview1 to an absolute target must answer EPERM, as \
1407
+ wasi-testsuite requires, and to a relative one must reach the Filesystem"
666
1408
  );
667
- assert!(
668
- table.get(to).is_none() && table.get(from).is_some(),
669
- "a refused close through fd_renumber must leave the target closed and the source in place"
1409
+ }
1410
+
1411
+ // The replaced file refuses its close, so only a renumber that moves the
1412
+ // source before closing, and ignores that answer, succeeds.
1413
+ // @behavior RT-114
1414
+ #[test]
1415
+ fn renumbering_onto_an_open_file_replaces_it_whatever_its_close_answers() {
1416
+ let mut wasi = standard_streams();
1417
+ let from = wasi.push_file(open_file()).expect("a descriptor to move");
1418
+ let to = wasi
1419
+ .push_file(open_file())
1420
+ .expect("a descriptor to move onto");
1421
+ assert_eq!(
1422
+ (
1423
+ errno(renumber(&mut wasi, from, to)),
1424
+ wasi.descriptors().get(from).is_none(),
1425
+ wasi.descriptors().get(to).is_some()
1426
+ ),
1427
+ (None, true, true),
1428
+ "fd_renumber through preview1 onto a file whose Filesystem refuses the close must \
1429
+ succeed, the source now standing at the target and its own number free, as Linux's \
1430
+ do_dup2 ignores filp_close of the file it replaced"
1431
+ );
1432
+ }
1433
+
1434
+ // @behavior RT-309
1435
+ #[test]
1436
+ fn renumbering_onto_a_number_not_open_answers_ebadf_and_keeps_the_source() {
1437
+ let mut wasi = standard_streams();
1438
+ let from = wasi.push_file(open_file()).expect("a descriptor to move");
1439
+ let to = from + 1;
1440
+ assert_eq!(
1441
+ (
1442
+ errno(renumber(&mut wasi, from, to)),
1443
+ wasi.descriptors().get(from).is_some(),
1444
+ wasi.descriptors().get(to).is_none()
1445
+ ),
1446
+ (Some(Errno::Badf), true, true),
1447
+ "fd_renumber through preview1 onto a number nothing stands at must answer EBADF and \
1448
+ leave the source at its own number, as wasmtime-wasi replaces only an open one"
670
1449
  );
671
1450
  }
672
1451
  }