kobako 0.30.0 → 0.32.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 (288) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/Cargo.lock +868 -447
  6. data/README.md +43 -4
  7. data/ROADMAP.md +1 -2
  8. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  9. data/crates/kobako-runtime/Cargo.toml +58 -11
  10. data/crates/kobako-runtime/README.md +7 -4
  11. data/crates/kobako-runtime/src/cred.rs +136 -0
  12. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  13. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  14. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  15. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  16. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  17. data/crates/kobako-runtime/src/errno.rs +391 -0
  18. data/crates/kobako-runtime/src/error.rs +31 -10
  19. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  21. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +101 -29
  22. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  23. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +52 -34
  24. data/crates/kobako-runtime/src/filesystem/bind.rs +812 -447
  25. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  26. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +11 -16
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  31. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +120 -37
  32. data/crates/kobako-runtime/src/filesystem/overlay.rs +578 -388
  33. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  34. data/crates/kobako-runtime/src/filesystem/rdir.rs +14 -50
  35. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  38. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  39. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  40. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +219 -173
  41. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  42. data/crates/kobako-runtime/src/filesystem.rs +8 -3
  43. data/crates/kobako-runtime/src/fork.rs +319 -0
  44. data/crates/kobako-runtime/src/grant.rs +3 -0
  45. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  46. data/crates/kobako-runtime/src/lib.rs +18 -7
  47. data/crates/kobako-runtime/src/limits.rs +171 -0
  48. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  49. data/crates/kobako-runtime/src/locking.rs +518 -113
  50. data/crates/kobako-runtime/src/memcg.rs +306 -0
  51. data/crates/kobako-runtime/src/mount.rs +37 -9
  52. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  53. data/crates/kobako-runtime/src/net/connections.rs +219 -0
  54. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  55. data/crates/kobako-runtime/src/net/egress.rs +180 -0
  56. data/crates/kobako-runtime/src/net/family.rs +181 -0
  57. data/crates/kobako-runtime/src/net/http.rs +3165 -0
  58. data/crates/kobako-runtime/src/net/lookup.rs +385 -0
  59. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  60. data/crates/kobako-runtime/src/net/namespace.rs +1368 -0
  61. data/crates/kobako-runtime/src/net/reactor.rs +626 -0
  62. data/crates/kobako-runtime/src/net/resolv/darwin.rs +280 -0
  63. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +519 -0
  64. data/crates/kobako-runtime/src/net/resolv/stub.rs +542 -0
  65. data/crates/kobako-runtime/src/net/resolv/windows.rs +218 -0
  66. data/crates/kobako-runtime/src/net/resolv.rs +251 -0
  67. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  68. data/crates/kobako-runtime/src/net/socket.rs +869 -0
  69. data/crates/kobako-runtime/src/net/task.rs +223 -0
  70. data/crates/kobako-runtime/src/net/tcp.rs +1840 -0
  71. data/crates/kobako-runtime/src/net/tls.rs +120 -0
  72. data/crates/kobako-runtime/src/net/transport.rs +304 -0
  73. data/crates/kobako-runtime/src/net/udp.rs +1105 -0
  74. data/crates/kobako-runtime/src/net.rs +45 -0
  75. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  76. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  77. data/crates/kobako-runtime/src/network.rs +551 -0
  78. data/crates/kobako-runtime/src/policy.rs +16 -0
  79. data/crates/kobako-runtime/src/profile.rs +29 -144
  80. data/crates/kobako-runtime/src/runtime.rs +3 -5
  81. data/crates/kobako-runtime/src/sched.rs +338 -51
  82. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  83. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  84. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  85. data/crates/kobako-runtime/src/security.rs +125 -209
  86. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  87. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  88. data/crates/kobako-runtime/src/vfs/dentry.rs +210 -117
  89. data/crates/kobako-runtime/src/vfs/file.rs +243 -248
  90. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  91. data/crates/kobako-runtime/src/vfs/kern_path.rs +62 -53
  92. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  93. data/crates/kobako-runtime/src/vfs/namei.rs +1162 -818
  94. data/crates/kobako-runtime/src/vfs/namespace.rs +245 -0
  95. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  96. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  97. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  98. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  99. data/crates/kobako-runtime/src/vfs/stat.rs +248 -23
  100. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  101. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  102. data/crates/kobako-runtime/src/vfs.rs +10 -6
  103. data/crates/kobako-runtime/src/wait.rs +381 -0
  104. data/crates/kobako-transport/CHANGELOG.md +38 -0
  105. data/crates/kobako-transport/Cargo.toml +1 -1
  106. data/crates/kobako-transport/README.md +3 -4
  107. data/crates/kobako-transport/src/abi.rs +78 -72
  108. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  109. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  110. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  111. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  112. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  113. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  114. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  116. data/crates/kobako-transport/src/envelope.rs +13 -8
  117. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  118. data/crates/kobako-wasmtime/Cargo.toml +47 -7
  119. data/crates/kobako-wasmtime/README.md +4 -3
  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 +18 -37
  123. data/crates/kobako-wasmtime/src/ambient.rs +43 -19
  124. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  125. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  126. data/crates/kobako-wasmtime/src/cache.rs +106 -113
  127. data/crates/kobako-wasmtime/src/config.rs +52 -68
  128. data/crates/kobako-wasmtime/src/driver.rs +80 -82
  129. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  130. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  131. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  132. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  133. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  134. data/crates/kobako-wasmtime/src/invocation.rs +91 -15
  135. data/crates/kobako-wasmtime/src/lib.rs +7 -3
  136. data/crates/kobako-wasmtime/src/limiter.rs +130 -12
  137. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +305 -0
  138. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +9 -20
  139. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  140. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  141. data/crates/kobako-wasmtime/src/preview1/fd.rs +347 -312
  142. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  143. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  144. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +335 -388
  145. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  146. data/crates/kobako-wasmtime/src/preview1/poll.rs +255 -125
  147. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  148. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  149. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  150. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  151. data/crates/kobako-wasmtime/src/preview1.rs +131 -51
  152. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  153. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  154. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  155. data/crates/kobako-wasmtime/src/preview2/host.rs +4319 -0
  156. data/crates/kobako-wasmtime/src/preview2/http.rs +1587 -0
  157. data/crates/kobako-wasmtime/src/preview2/io.rs +328 -0
  158. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  159. data/crates/kobako-wasmtime/src/preview2/table.rs +257 -0
  160. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  161. data/crates/kobako-wasmtime/src/trap.rs +88 -28
  162. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  163. data/crates/kobako-wasmtime/src/wasi.rs +291 -81
  164. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  165. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  166. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  167. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  168. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  169. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  170. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  171. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  172. data/data/kobako.wasm +0 -0
  173. data/ext/kobako/Cargo.toml +6 -2
  174. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  175. data/ext/kobako/src/escape.rs +404 -0
  176. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +34 -32
  177. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +158 -170
  178. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +71 -23
  179. data/ext/kobako/src/fork.rs +72 -0
  180. data/ext/kobako/src/gvl.rs +729 -0
  181. data/ext/kobako/src/handoff.rs +490 -0
  182. data/ext/kobako/src/lib.rs +74 -3
  183. data/ext/kobako/src/network/mock.rs +187 -0
  184. data/ext/kobako/src/network.rs +593 -0
  185. data/ext/kobako/src/pinned_value.rs +44 -0
  186. data/ext/kobako/src/runtime/bridge.rs +58 -50
  187. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  188. data/ext/kobako/src/runtime.rs +272 -163
  189. data/ext/kobako/src/wire.rs +42 -0
  190. data/lib/kobako/catalog/extensions.rb +14 -2
  191. data/lib/kobako/catalog/flags.rb +3 -5
  192. data/lib/kobako/catalog/grants.rb +5 -4
  193. data/lib/kobako/catalog/handles.rb +14 -32
  194. data/lib/kobako/catalog/mount.rb +11 -3
  195. data/lib/kobako/catalog/network.rb +35 -0
  196. data/lib/kobako/catalog/replacements.rb +28 -0
  197. data/lib/kobako/catalog/services.rb +5 -19
  198. data/lib/kobako/catalog/snippets.rb +3 -18
  199. data/lib/kobako/catalog.rb +3 -0
  200. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  201. data/lib/kobako/codec/decoder.rb +5 -5
  202. data/lib/kobako/codec/ext_types.rb +3 -3
  203. data/lib/kobako/codec/handle_walk.rb +3 -43
  204. data/lib/kobako/codec/state.rb +2 -18
  205. data/lib/kobako/codec/value_budget.rb +133 -41
  206. data/lib/kobako/codec.rb +6 -7
  207. data/lib/kobako/context.rb +24 -11
  208. data/lib/kobako/errors.rb +18 -18
  209. data/lib/kobako/extension.rb +3 -2
  210. data/lib/kobako/filesystem.rb +10 -3
  211. data/lib/kobako/fork.rb +42 -0
  212. data/lib/kobako/handle.rb +2 -3
  213. data/lib/kobako/names.rb +28 -0
  214. data/lib/kobako/network.rb +210 -0
  215. data/lib/kobako/outcome.rb +7 -7
  216. data/lib/kobako/runtime.rb +3 -2
  217. data/lib/kobako/sandbox.rb +73 -35
  218. data/lib/kobako/sandbox_options.rb +42 -109
  219. data/lib/kobako/transport/argument_wrap.rb +64 -0
  220. data/lib/kobako/transport/block_failure.rb +1 -1
  221. data/lib/kobako/transport/dispatcher.rb +6 -6
  222. data/lib/kobako/transport/exposure.rb +26 -15
  223. data/lib/kobako/transport/reflection.rb +21 -4
  224. data/lib/kobako/transport/run.rb +8 -23
  225. data/lib/kobako/transport/yielder.rb +2 -9
  226. data/lib/kobako/transport.rb +1 -0
  227. data/lib/kobako/usage.rb +4 -2
  228. data/lib/kobako/version.rb +1 -1
  229. data/lib/kobako.rb +8 -4
  230. data/release-please-config.json +15 -0
  231. data/sig/kobako/catalog/extensions.rbs +2 -0
  232. data/sig/kobako/catalog/grants.rbs +7 -4
  233. data/sig/kobako/catalog/handles.rbs +2 -2
  234. data/sig/kobako/catalog/mount.rbs +3 -1
  235. data/sig/kobako/catalog/network.rbs +20 -0
  236. data/sig/kobako/catalog/replacements.rbs +14 -0
  237. data/sig/kobako/catalog/services.rbs +0 -4
  238. data/sig/kobako/catalog/snippets.rbs +0 -2
  239. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  240. data/sig/kobako/codec/handle_walk.rbs +0 -6
  241. data/sig/kobako/codec/state.rbs +0 -4
  242. data/sig/kobako/codec/value_budget.rbs +48 -5
  243. data/sig/kobako/codec.rbs +2 -2
  244. data/sig/kobako/context.rbs +3 -1
  245. data/sig/kobako/errors.rbs +4 -7
  246. data/sig/kobako/filesystem.rbs +21 -3
  247. data/sig/kobako/fork.rbs +17 -0
  248. data/sig/kobako/network.rbs +115 -0
  249. data/sig/kobako/outcome.rbs +1 -1
  250. data/sig/kobako/runtime.rbs +32 -3
  251. data/sig/kobako/sandbox.rbs +10 -2
  252. data/sig/kobako/sandbox_options.rbs +29 -40
  253. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  254. data/sig/kobako/transport/error.rbs +1 -1
  255. data/sig/kobako/transport/exposure.rbs +2 -4
  256. data/sig/kobako/transport/reflection.rbs +10 -0
  257. data/sig/kobako/transport/run.rbs +0 -2
  258. data/sig/kobako/transport/yielder.rbs +0 -3
  259. data/sig/kobako/transport.rbs +1 -1
  260. data/sig/kobako.rbs +13 -0
  261. metadata +97 -37
  262. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  263. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  264. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  265. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  266. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  267. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  268. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  269. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  270. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  271. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  272. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  273. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  274. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  275. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  276. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  277. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  278. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  279. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  280. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  281. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  282. data/ext/kobako/src/runtime/escape.rs +0 -67
  283. data/ext/kobako/src/runtime/gvl.rs +0 -147
  284. data/ext/kobako/src/runtime/pinned_value.rs +0 -31
  285. data/lib/kobako/constant_name.rb +0 -8
  286. data/lib/kobako/pool.rb +0 -140
  287. data/sig/kobako/constant_name.rbs +0 -3
  288. data/sig/kobako/pool.rbs +0 -42
@@ -7,9 +7,27 @@
7
7
  //! path itself, which refuses a `..` or a link leading out of the
8
8
  //! directory whatever a caller hands over, and answers alike on every
9
9
  //! host, Windows among them.
10
+ //!
11
+ //! A Windows host differs from Linux in each row below, and a Bind answers
12
+ //! there as Linux does:
13
+ //!
14
+ //! | What Windows does apart | How a Bind answers | Where |
15
+ //! |---|---|---|
16
+ //! | spells names and link targets its own way | as a guest spells them | `unicode` |
17
+ //! | folds a name's case | the name the directory stores | `lookup` |
18
+ //! | names an entry by volume and file index | that pair as its identity | `to_kstat` |
19
+ //! | keeps no time a status changed | no such time | `to_kstat` |
20
+ //! | removes a link to a directory only as a directory | the link removed as itself | `unlink` |
21
+ //! | appends only by one write at the end | one such write | `BindFile::append` |
22
+ //! | sets a time only through a handle granted to | a handle reopened for it | `set_held_times` |
23
+ //! | refuses a file another process holds unshared | permission denied | `to_error` |
24
+ //!
25
+ //! A directory a process holds open cannot move there, so what a guest
26
+ //! would see of one moved is never staged on Windows.
10
27
 
11
28
  mod fid;
12
29
  mod lookup;
30
+ mod unicode;
13
31
  mod walk;
14
32
 
15
33
  use std::any::Any;
@@ -23,14 +41,14 @@ use cap_std::fs::{Dir, OpenOptions as CapOpenOptions};
23
41
 
24
42
  use super::rdir::Rdir;
25
43
  use super::{
26
- DentryOperations, DirEntry, FileOperations, FileSystemType, FileType, Filesystem,
27
- FilesystemError, Finish, Iattr, InodeOperations, Kiocb, Kstat, Lookup, OpenHow, RenameFlag,
28
- SetTime,
44
+ DentryOperations, DirEntry, Errno, FileOperations, FileSystemType, FileType, Filesystem,
45
+ Finish, Iattr, InodeOperations, Kiocb, Kstat, Lookup, OpenHow, RenameFlag, SetTime,
29
46
  };
30
47
  use crate::vfs::{
31
48
  generic_file_llseek, generic_read_dir, Dentry, DirContext, Identity, Inode, Whence,
32
49
  };
33
- use fid::{FidCache, OpenDirFid};
50
+ use fid::{FidOwner, OpenDirFid, FIDS};
51
+ use unicode::{to_guest_name, to_guest_target, to_host_name};
34
52
 
35
53
  /// A host directory and everything beneath it. What a guest writes lands
36
54
  /// on the host and lasts as long as the directory does.
@@ -39,34 +57,60 @@ use fid::{FidCache, OpenDirFid};
39
57
  /// about through the dentry it is handed, as Linux's 9p does. A directory is
40
58
  /// opened on the host when first asked, as 9p walks to a dentry's fid only
41
59
  /// when a call needs one. One a guest holds open holds a host descriptor; the
42
- /// others a walk asked about hold one only up to a bound.
60
+ /// others a walk asked about hold one only up to a bound every Bind shares.
43
61
  #[derive(Clone)]
44
62
  pub struct Bind {
45
- /// The host directory the Bind was made at.
63
+ /// The host directory the Bind was made at, let go before what its walks
64
+ /// kept.
46
65
  root: Arc<Dir>,
47
- fids: Arc<FidCache>,
66
+ fids: Arc<FidOwner>,
67
+ /// Whether only the guest changes the directory, so a name it found
68
+ /// stays as found without asking the host again.
69
+ exclusive: bool,
48
70
  }
49
71
 
50
72
  impl Bind {
51
- /// Open the host directory at `path`, the one place this Filesystem
52
- /// reaches outside itself. One the host lets no one read is refused, so its
53
- /// root answers an open to read as any directory beneath it does, on every
54
- /// host alike.
73
+ /// Let go of every host directory the process's Binds keep for walks,
74
+ /// as a process about to fork does, so the child inherits none of them.
75
+ /// A directory a guest holds open stays with the guest.
76
+ pub fn drop_kept_directories() {
77
+ FIDS.drop_all();
78
+ }
79
+
80
+ /// Open the host directory at `path` now, the one place this Filesystem
81
+ /// reaches outside itself, so it stays the directory standing there as
82
+ /// it is made. One the host lets no one read is refused, so its root
83
+ /// answers an open to read as any directory beneath it does, on every host
84
+ /// alike. A host out of descriptors makes the directories Binds keep give
85
+ /// way first; a refusal answers the host's own errno.
55
86
  pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
56
- let root = Dir::open_ambient_dir(path, ambient_authority())?;
57
- may_read_dir(&root).map_err(|_| io::Error::from(io::ErrorKind::PermissionDenied))?;
87
+ let path = path.as_ref();
88
+ let root = FIDS.open_or_give_way(
89
+ || Dir::open_ambient_dir(path, ambient_authority()),
90
+ host_out_of_descriptors,
91
+ )?;
92
+ FIDS.open_or_give_way(|| readable(&root), host_out_of_descriptors)?;
58
93
  Ok(Self {
59
94
  root: Arc::new(root),
60
95
  fids: Arc::default(),
96
+ exclusive: false,
61
97
  })
62
98
  }
63
99
 
100
+ /// This Bind trusting the names it found when `exclusive`, the Host App
101
+ /// vouching that only the guest changes the directory, as gVisor's
102
+ /// exclusive mount skips revalidation. A change made on the host meanwhile
103
+ /// may go unseen.
104
+ pub fn with_exclusive(self, exclusive: bool) -> Self {
105
+ Self { exclusive, ..self }
106
+ }
107
+
64
108
  /// The host directory kept for `dentry`, if one is.
65
109
  fn find_fid(&self, dentry: &Dentry) -> Option<Arc<Dir>> {
66
110
  if dentry.is_root() {
67
111
  return Some(self.root.clone());
68
112
  }
69
- OpenDirFid::get(dentry).or_else(|| self.fids.get(dentry))
113
+ OpenDirFid::get(dentry).or_else(|| FIDS.get(dentry))
70
114
  }
71
115
 
72
116
  /// The host directory `dentry` names, as 9p's `v9fs_fid_lookup` finds a
@@ -74,7 +118,7 @@ impl Bind {
74
118
  /// kept, read from the dentries as `build_path_from_dentry` reads them.
75
119
  /// 9p holds the rename lock through a walk; one here compares what it found
76
120
  /// with what the dentry recorded instead, as NFS compares a file handle.
77
- fn fid_lookup(&self, dentry: &Dentry) -> Result<Arc<Dir>, FilesystemError> {
121
+ fn fid_lookup(&self, dentry: &Dentry) -> Result<Arc<Dir>, Errno> {
78
122
  if let Some(held) = self.find_fid(dentry) {
79
123
  return Ok(held);
80
124
  }
@@ -95,12 +139,13 @@ impl Bind {
95
139
  .dir_metadata()
96
140
  .is_ok_and(|found| Identity::of(&to_kstat(found)) == recorded)
97
141
  };
142
+ FIDS.make_room();
98
143
  let dir = walk::walk(&above, &names)?;
99
144
  if !stands(&dir) {
100
- return Err(FilesystemError::NotFound);
145
+ return Err(Errno::NotFound);
101
146
  }
102
147
  let dir = Arc::new(dir);
103
- self.fids.put(dentry, &dir);
148
+ FIDS.put(&self.fids, dentry, &dir);
104
149
  Ok(dir)
105
150
  }
106
151
 
@@ -109,8 +154,8 @@ impl Bind {
109
154
  fn at<T>(
110
155
  &self,
111
156
  dentry: &Dentry,
112
- call: impl FnOnce(&Dir, &str) -> Result<T, FilesystemError>,
113
- ) -> Result<T, FilesystemError> {
157
+ call: impl FnOnce(&Dir, &str) -> Result<T, Errno>,
158
+ ) -> Result<T, Errno> {
114
159
  let (parent, name) = dentry.parent_and_name();
115
160
  call(&*self.fid_lookup(&parent)?, to_host_name(&name)?)
116
161
  }
@@ -124,7 +169,7 @@ impl Bind {
124
169
  dentry: &Dentry,
125
170
  how: &OpenHow,
126
171
  create: bool,
127
- ) -> Result<Box<dyn FileOperations>, FilesystemError> {
172
+ ) -> Result<Box<dyn FileOperations>, Errno> {
128
173
  let file = self.at(dentry, |dir, name| open_in(dir, name, how, create))?;
129
174
  let opened = to_kstat(cap_std::fs::Metadata::from_file(&file).map_err(to_error)?);
130
175
  match dentry.inode().map(|inode| inode.identity()) {
@@ -136,12 +181,12 @@ impl Bind {
136
181
  // which only what opened can tell, as NFS's open compares the file
137
182
  // handle it gets back.
138
183
  Some(Some(identity)) if Identity::of(&opened) != Some(identity) => {
139
- return Err(FilesystemError::NotFound)
184
+ return Err(Errno::NotFound)
140
185
  }
141
186
  Some(_) => {}
142
187
  }
143
188
  let file = Arc::new(file);
144
- let inode = dentry.inode().ok_or(FilesystemError::NotFound)?;
189
+ let inode = dentry.inode().ok_or(Errno::NotFound)?;
145
190
  let kept = inode
146
191
  .private()
147
192
  .get_or_init(|| Arc::new(OpenFids::default()))
@@ -158,7 +203,7 @@ impl Bind {
158
203
  /// directory above, as a walk asks each name once the one above it stood.
159
204
  /// A host may reuse an inode number for what it made in its place, so the
160
205
  /// kind must match too, as NFS compares a file handle's attributes.
161
- fn stands_as_recorded(&self, dentry: &Dentry) -> Result<bool, FilesystemError> {
206
+ fn stands_as_recorded(&self, dentry: &Dentry) -> Result<bool, Errno> {
162
207
  let inode = dentry.inode();
163
208
  if inode
164
209
  .as_ref()
@@ -172,44 +217,47 @@ impl Bind {
172
217
  match (found, inode) {
173
218
  (Ok(found), Some(inode)) => {
174
219
  let found = to_kstat(found);
175
- Ok(Identity::of(&found) == inode.identity() && found.file_type == inode.kind())
220
+ Ok(
221
+ Identity::of(&found) == inode.identity()
222
+ && found.file_type == inode.file_type(),
223
+ )
176
224
  }
177
225
  (Ok(_), None) => Ok(false),
178
- (Err(FilesystemError::NotFound), None) => Ok(true),
179
- (
180
- Err(
181
- FilesystemError::NotFound
182
- | FilesystemError::NotADirectory
183
- | FilesystemError::FilesystemLoop,
184
- ),
185
- _,
186
- ) => Ok(false),
226
+ (Err(Errno::NotFound), None) => Ok(true),
227
+ (Err(Errno::NotFound | Errno::NotADirectory | Errno::FilesystemLoop), _) => Ok(false),
187
228
  (Err(err), _) => Err(err),
188
229
  }
189
230
  }
190
231
  }
191
232
 
192
- /// The names `dir` holds, each with the kind and the identity a listing gives.
193
- fn entries_of(dir: &Dir) -> Result<Vec<DirEntry>, FilesystemError> {
233
+ /// The names `dir` holds, each with the kind and the identity a stat names.
234
+ /// A Windows listing carries no file index, so there each name is asked of
235
+ /// a stat; one gone by then lists without an identity.
236
+ fn entries_of(dir: &Dir) -> Result<Vec<DirEntry>, Errno> {
194
237
  #[cfg(unix)]
195
238
  let dev = {
196
239
  use cap_std::fs::MetadataExt;
197
240
  dir.dir_metadata().map_err(to_error)?.dev()
198
241
  };
199
- dir.entries()
200
- .map_err(to_error)?
242
+ FIDS.open(|| dir.entries().map_err(to_error))?
201
243
  .map(|entry| {
244
+ crate::sched::stop_if_fatal()?;
202
245
  let entry = entry.map_err(to_error)?;
203
- let name = entry
204
- .file_name()
205
- .into_string()
206
- .map_err(|_| FilesystemError::IllegalSequence)?;
246
+ let name = to_guest_name(entry.file_name())?;
207
247
  let listed = DirEntry::new(name, to_file_type(entry.file_type().map_err(to_error)?));
208
248
  #[cfg(unix)]
209
249
  let listed = {
210
250
  use std::os::unix::fs::DirEntryExt;
211
251
  listed.with_identity(dev, entry.ino())
212
252
  };
253
+ #[cfg(not(unix))]
254
+ let listed = match dir.symlink_metadata(&listed.name) {
255
+ Ok(found) => {
256
+ use cap_fs_ext::MetadataExt;
257
+ listed.with_identity(found.dev(), found.ino())
258
+ }
259
+ Err(_) => listed,
260
+ };
213
261
  Ok(listed)
214
262
  })
215
263
  .collect()
@@ -218,7 +266,7 @@ fn entries_of(dir: &Dir) -> Result<Vec<DirEntry>, FilesystemError> {
218
266
  /// The directory `name` in `dir`, a link there refused as a loop, as
219
267
  /// Linux's `RESOLVE_NO_SYMLINKS` refuses one, where the host names it no
220
268
  /// directory.
221
- fn open_dir_nofollow(dir: &Dir, name: &str) -> Result<Dir, FilesystemError> {
269
+ fn open_dir_nofollow(dir: &Dir, name: &str) -> Result<Dir, Errno> {
222
270
  dir.open_dir_nofollow(name)
223
271
  .map_err(|err| nofollow_error(dir, name, err))
224
272
  }
@@ -226,70 +274,22 @@ fn open_dir_nofollow(dir: &Dir, name: &str) -> Result<Dir, FilesystemError> {
226
274
  /// Why an open of `name` in `dir` that follows no link failed, a link there
227
275
  /// named a loop, as Linux's `O_NOFOLLOW` answers `ELOOP`, where the host
228
276
  /// names it otherwise.
229
- fn nofollow_error(dir: &Dir, name: &str, err: io::Error) -> FilesystemError {
277
+ fn nofollow_error(dir: &Dir, name: &str, err: io::Error) -> Errno {
230
278
  match dir.symlink_metadata(name) {
231
- Ok(metadata) if metadata.file_type().is_symlink() => FilesystemError::FilesystemLoop,
279
+ Ok(metadata) if metadata.file_type().is_symlink() => Errno::FilesystemLoop,
232
280
  _ => to_error(err),
233
281
  }
234
282
  }
235
283
 
236
- /// `name` as `cap_std` takes it. Windows reads some names as other names or as
237
- /// devices, so there one is refused rather than reached as an entry a Mount's
238
- /// Policy never saw.
239
- fn to_host_name(name: &str) -> Result<&str, FilesystemError> {
240
- if cfg!(windows) && is_windows_alias(name) {
241
- return Err(FilesystemError::InvalidInput);
242
- }
243
- Ok(name)
244
- }
245
-
246
- /// Whether Windows reads `name` as something else: a `\` as a separator, a `:`
247
- /// as a stream of a file, a trailing `.` or space as nothing, a wildcard as a
248
- /// pattern, or a device's name, whatever extension follows, as the device.
249
- fn is_windows_alias(name: &str) -> bool {
250
- const DEVICES: [&str; 33] = [
251
- "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$", "COM0", "COM1", "COM2", "COM3",
252
- "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1",
253
- "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³",
254
- ];
255
- let reserved = |c: char| c.is_ascii_control() || "\\:*?\"<>|".contains(c);
256
- let stem = name.split('.').next().unwrap_or(name).trim_end();
257
- name.contains(reserved)
258
- || name.ends_with(['.', ' '])
259
- || DEVICES.contains(&stem.to_uppercase().as_str())
260
- }
261
-
262
- /// The FilesystemError a host failure names. cap-std's own refusal of a path
284
+ /// The Errno a host failure names. cap-std's own refusal of a path
263
285
  /// leading out of the directory carries no OS code. A Bind hands it one name and
264
286
  /// no `..`, so that refusal only says a move carried the name out of the
265
287
  /// directory as it was opened, as `complete_walk` answers EXDEV, and nothing
266
- /// stands at it now. A link loop stays unnamed until std's `FilesystemLoop` is
267
- /// stable.
268
- fn to_error(err: io::Error) -> FilesystemError {
288
+ /// stands at it now.
289
+ fn to_error(err: io::Error) -> Errno {
269
290
  match err.kind() {
270
- io::ErrorKind::PermissionDenied if err.raw_os_error().is_none() => {
271
- FilesystemError::NotFound
272
- }
273
- io::ErrorKind::NotFound => FilesystemError::NotFound,
274
- io::ErrorKind::AlreadyExists => FilesystemError::AlreadyExists,
275
- io::ErrorKind::NotADirectory => FilesystemError::NotADirectory,
276
- io::ErrorKind::IsADirectory => FilesystemError::IsADirectory,
277
- io::ErrorKind::DirectoryNotEmpty => FilesystemError::DirectoryNotEmpty,
278
- io::ErrorKind::PermissionDenied => FilesystemError::PermissionDenied,
279
- io::ErrorKind::ReadOnlyFilesystem => FilesystemError::ReadOnlyFilesystem,
280
- io::ErrorKind::InvalidInput => FilesystemError::InvalidInput,
281
- io::ErrorKind::Unsupported => FilesystemError::Unsupported,
282
- io::ErrorKind::StorageFull => FilesystemError::StorageFull,
283
- io::ErrorKind::FileTooLarge => FilesystemError::FileTooLarge,
284
- io::ErrorKind::CrossesDevices => FilesystemError::CrossesDevices,
285
- io::ErrorKind::Deadlock => FilesystemError::Deadlock,
286
- io::ErrorKind::ResourceBusy => FilesystemError::ResourceBusy,
287
- io::ErrorKind::InvalidFilename => FilesystemError::InvalidFilename,
288
- io::ErrorKind::NotSeekable => FilesystemError::NotSeekable,
289
- io::ErrorKind::Interrupted => FilesystemError::Interrupted,
290
- io::ErrorKind::WouldBlock => FilesystemError::WouldBlock,
291
- io::ErrorKind::OutOfMemory => FilesystemError::OutOfMemory,
292
- _ => FilesystemError::Other(err.to_string()),
291
+ io::ErrorKind::PermissionDenied if err.raw_os_error().is_none() => Errno::NotFound,
292
+ _ => Errno::from_io_error(&err),
293
293
  }
294
294
  }
295
295
 
@@ -330,8 +330,9 @@ fn to_special_file_type(_host: cap_std::fs::FileType) -> FileType {
330
330
  }
331
331
 
332
332
  /// What a host entry is, with the size the host reports. The host names
333
- /// its identity, link count, and times on unix; elsewhere a Bind reports
334
- /// none.
333
+ /// its identity, link count, and times everywhere. Windows names the
334
+ /// identity by volume and file index, which cap-std reads from the handle
335
+ /// each of its stats opens, and keeps no time an entry's status changed.
335
336
  fn to_kstat(metadata: cap_std::fs::Metadata) -> Kstat {
336
337
  let file_type = to_file_type(metadata.file_type());
337
338
  let size = metadata.len();
@@ -348,7 +349,17 @@ fn to_kstat(metadata: cap_std::fs::Metadata) -> Kstat {
348
349
  )
349
350
  }
350
351
  #[cfg(not(unix))]
351
- Kstat::new(file_type, size)
352
+ {
353
+ use cap_fs_ext::MetadataExt;
354
+ Kstat::new(file_type, size)
355
+ .with_identity(metadata.dev(), metadata.ino())
356
+ .with_nlink(metadata.nlink())
357
+ .with_times(
358
+ metadata.accessed().ok().map(|at| at.into_std()),
359
+ metadata.modified().ok().map(|at| at.into_std()),
360
+ None,
361
+ )
362
+ }
352
363
  }
353
364
 
354
365
  /// The time `seconds` and `nanoseconds` after the Unix epoch, as `stat`
@@ -368,6 +379,43 @@ fn to_host_time(time: Option<SetTime>) -> Option<SystemTimeSpec> {
368
379
  })
369
380
  }
370
381
 
382
+ /// Set `times` on the file `held` holds, as `futimens` does on any open
383
+ /// descriptor.
384
+ #[cfg(unix)]
385
+ fn set_held_times(held: &std::fs::File, times: std::fs::FileTimes) -> io::Result<()> {
386
+ held.set_times(times)
387
+ }
388
+
389
+ /// Set `times` on the file `held` holds, as `futimens` does on any open
390
+ /// descriptor. Windows sets a time only through a handle granted to change
391
+ /// attributes, which one opened to read lacks, so the time goes through a
392
+ /// handle reopened from `held` for that alone, reaching the same file
393
+ /// whatever now stands at its name.
394
+ #[cfg(windows)]
395
+ fn set_held_times(held: &std::fs::File, times: std::fs::FileTimes) -> io::Result<()> {
396
+ use std::os::windows::io::{AsRawHandle, FromRawHandle};
397
+ use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
398
+ use windows_sys::Win32::Storage::FileSystem::{
399
+ ReOpenFile, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,
400
+ FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES,
401
+ };
402
+
403
+ // SAFETY: `held` owns a live handle for the call's length; the handle
404
+ // ReOpenFile answers is a new one, owned from here by the File made of it.
405
+ let reopened = unsafe {
406
+ ReOpenFile(
407
+ held.as_raw_handle(),
408
+ FILE_WRITE_ATTRIBUTES,
409
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
410
+ FILE_FLAG_BACKUP_SEMANTICS,
411
+ )
412
+ };
413
+ if reopened == INVALID_HANDLE_VALUE {
414
+ return Err(io::Error::last_os_error());
415
+ }
416
+ unsafe { std::fs::File::from_raw_handle(reopened) }.set_times(times)
417
+ }
418
+
371
419
  /// The descriptors open on one file, and which were opened to write, as 9p
372
420
  /// keeps open fids on `i_private`.
373
421
  #[derive(Default)]
@@ -386,13 +434,24 @@ fn v9fs_fid_find_inode(dentry: &Dentry, writable: bool) -> Option<Arc<std::fs::F
386
434
 
387
435
  /// Open `name` in `dir` as `how` asks, made first where `create` says,
388
436
  /// refusing one that already stands.
389
- fn open_in(
437
+ fn open_in(dir: &Dir, name: &str, how: &OpenHow, create: bool) -> Result<std::fs::File, Errno> {
438
+ FIDS.open(|| open_in_once(dir, name, how, create))
439
+ }
440
+
441
+ /// One try at `open_in`, which the host may refuse for want of descriptors.
442
+ fn open_in_once(
390
443
  dir: &Dir,
391
444
  name: &str,
392
445
  how: &OpenHow,
393
446
  create: bool,
394
- ) -> Result<std::fs::File, FilesystemError> {
447
+ ) -> Result<std::fs::File, Errno> {
395
448
  let writes = how.write || how.truncate || create;
449
+ #[cfg(target_os = "linux")]
450
+ if !create {
451
+ if let Some(opened) = open_judged(dir, name, how.read, writes)? {
452
+ return Ok(opened);
453
+ }
454
+ }
396
455
  let mut open = CapOpenOptions::new();
397
456
  // The host refuses one that creates or truncates without writing; the
398
457
  // runtime decides what is written, so such opens write here.
@@ -414,8 +473,8 @@ fn open_in(
414
473
  .map_err(|err| nofollow_error(dir, name, err))?;
415
474
  match to_file_type(file.metadata().map_err(to_error)?.file_type()) {
416
475
  FileType::RegFile => {}
417
- FileType::Dir => return Err(FilesystemError::IsADirectory),
418
- _ => return Err(FilesystemError::PermissionDenied),
476
+ FileType::Dir => return Err(Errno::IsADirectory),
477
+ _ => return Err(Errno::PermissionDenied),
419
478
  }
420
479
  #[cfg(unix)]
421
480
  {
@@ -430,6 +489,53 @@ fn open_in(
430
489
  Ok(file.into_std())
431
490
  }
432
491
 
492
+ /// The file standing at `name` in `dir`, held by `O_PATH` first, which opens
493
+ /// nothing, and opened only once it stands as a file, through
494
+ /// `/proc/self/fd`, so what opens is the inode judged and no device swapped
495
+ /// in acts on being opened, as gVisor's directfs reopens its control
496
+ /// descriptor. None where the host has no `/proc` to reopen through.
497
+ #[cfg(target_os = "linux")]
498
+ fn open_judged(
499
+ dir: &Dir,
500
+ name: &str,
501
+ read: bool,
502
+ writes: bool,
503
+ ) -> Result<Option<std::fs::File>, Errno> {
504
+ use rustix::fs::{fstat, open, openat, FileType as HostType, Mode, OFlags};
505
+ use std::os::fd::AsRawFd;
506
+
507
+ let held = openat(
508
+ dir,
509
+ name,
510
+ OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
511
+ Mode::empty(),
512
+ )
513
+ .map_err(io::Error::from)
514
+ .map_err(to_error)?;
515
+ let stat = fstat(&held).map_err(io::Error::from).map_err(to_error)?;
516
+ match HostType::from_raw_mode(stat.st_mode) {
517
+ HostType::RegularFile => {}
518
+ HostType::Directory => return Err(Errno::IsADirectory),
519
+ HostType::Symlink => return Err(Errno::FilesystemLoop),
520
+ _ => return Err(Errno::PermissionDenied),
521
+ }
522
+ let access = match (read, writes) {
523
+ (true, true) => OFlags::RDWR,
524
+ (false, true) => OFlags::WRONLY,
525
+ _ => OFlags::RDONLY,
526
+ };
527
+ let reopened = open(
528
+ format!("/proc/self/fd/{}", held.as_raw_fd()).as_str(),
529
+ access | OFlags::CLOEXEC | OFlags::NOCTTY,
530
+ Mode::empty(),
531
+ );
532
+ match reopened {
533
+ Ok(fd) => Ok(Some(std::fs::File::from(fd))),
534
+ Err(rustix::io::Errno::NOENT) => Ok(None),
535
+ Err(err) => Err(to_error(io::Error::from(err))),
536
+ }
537
+ }
538
+
433
539
  /// The host may move or remake what a dentry names behind the runtime's
434
540
  /// back, so a dentry recording an identity is valid only while the same
435
541
  /// entry stands at the path it stands for, as NFS compares the handle a
@@ -438,7 +544,7 @@ fn open_in(
438
544
  impl FileSystemType for Bind {
439
545
  /// Its root reports the host directory it holds, as 9p's `fill_super` asks of
440
546
  /// the attached fid, and a host that cannot answer makes no instance.
441
- fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), FilesystemError> {
547
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
442
548
  sb.set_default_d_op(self.clone());
443
549
  let root = to_kstat(self.root.dir_metadata().map_err(to_error)?);
444
550
  sb.d_make_root(Inode::new(&root, self));
@@ -447,12 +553,11 @@ impl FileSystemType for Bind {
447
553
  }
448
554
 
449
555
  impl DentryOperations for Bind {
450
- fn revalidate(
451
- &self,
452
- _dir: &dyn InodeOperations,
453
- dentry: &Dentry,
454
- ) -> Result<bool, FilesystemError> {
455
- self.stands_as_recorded(dentry)
556
+ fn revalidate(&self, _dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno> {
557
+ match self.exclusive {
558
+ true => Ok(true),
559
+ false => self.stands_as_recorded(dentry),
560
+ }
456
561
  }
457
562
 
458
563
  fn delete(&self, dentry: &Dentry) -> bool {
@@ -470,7 +575,7 @@ struct BindRegular(Bind);
470
575
  struct BindLink(Bind);
471
576
 
472
577
  /// What an entry standing at its name in the directory above reports.
473
- fn stat_at(bind: &Bind, dentry: &Dentry) -> Result<Kstat, FilesystemError> {
578
+ fn stat_at(bind: &Bind, dentry: &Dentry) -> Result<Kstat, Errno> {
474
579
  bind.at(dentry, |dir, name| {
475
580
  Ok(to_kstat(dir.symlink_metadata(name).map_err(to_error)?))
476
581
  })
@@ -479,7 +584,7 @@ fn stat_at(bind: &Bind, dentry: &Dentry) -> Result<Kstat, FilesystemError> {
479
584
  impl InodeOperations for BindRegular {
480
585
  /// A file open anywhere answers from the descriptor that holds it, even
481
586
  /// once its name is gone.
482
- fn getattr(&self, dentry: &Dentry) -> Result<Kstat, FilesystemError> {
587
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
483
588
  match v9fs_fid_find_inode(dentry, false) {
484
589
  Some(file) => Ok(to_kstat(
485
590
  cap_std::fs::Metadata::from_file(&file).map_err(to_error)?,
@@ -488,7 +593,7 @@ impl InodeOperations for BindRegular {
488
593
  }
489
594
  }
490
595
 
491
- fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), FilesystemError> {
596
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
492
597
  if let Some(len) = attr.size {
493
598
  // A truncate made through an open takes that open's descriptor, as
494
599
  // 9p takes `ia_file`'s fid; one made by name, one open to write
@@ -499,7 +604,7 @@ impl InodeOperations for BindRegular {
499
604
  .map(|opened| opened.file.clone());
500
605
  return match through.or_else(|| v9fs_fid_find_inode(dentry, true)) {
501
606
  Some(file) => file.set_len(len).map_err(to_error),
502
- None => Err(FilesystemError::InvalidInput),
607
+ None => Err(Errno::InvalidInput),
503
608
  };
504
609
  }
505
610
  // A file open anywhere takes them through what holds it, whatever stands
@@ -512,7 +617,7 @@ impl InodeOperations for BindRegular {
512
617
  if let Some(mtime) = attr.mtime {
513
618
  times = times.set_modified(attr.time_of(mtime));
514
619
  }
515
- return file.set_times(times).map_err(to_error);
620
+ return set_held_times(&file, times).map_err(to_error);
516
621
  }
517
622
  let (atime, mtime) = (to_host_time(attr.atime), to_host_time(attr.mtime));
518
623
  self.0.at(dentry, |dir, name| {
@@ -520,17 +625,13 @@ impl InodeOperations for BindRegular {
520
625
  })
521
626
  }
522
627
 
523
- fn open(
524
- &self,
525
- dentry: &Dentry,
526
- how: &OpenHow,
527
- ) -> Result<Box<dyn FileOperations>, FilesystemError> {
628
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
528
629
  self.0.open_file(dentry, how, false)
529
630
  }
530
631
  }
531
632
 
532
633
  impl InodeOperations for BindLink {
533
- fn getattr(&self, dentry: &Dentry) -> Result<Kstat, FilesystemError> {
634
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
534
635
  stat_at(&self.0, dentry)
535
636
  }
536
637
 
@@ -538,13 +639,13 @@ impl InodeOperations for BindLink {
538
639
  /// as `->get_link` answers, since the walk judges what a link leads to. A
539
640
  /// target that is no valid UTF-8 answers `IllegalSequence`, as a guest path
540
641
  /// is one.
541
- fn get_link(&self, dentry: &Dentry) -> Result<String, FilesystemError> {
642
+ fn get_link(&self, dentry: &Dentry) -> Result<String, Errno> {
542
643
  self.0.at(dentry, |dir, name| {
543
- dir.read_link_contents(name)
544
- .map_err(to_error)?
545
- .into_os_string()
546
- .into_string()
547
- .map_err(|_| FilesystemError::IllegalSequence)
644
+ to_guest_target(
645
+ dir.read_link_contents(name)
646
+ .map_err(to_error)?
647
+ .into_os_string(),
648
+ )
548
649
  })
549
650
  }
550
651
  }
@@ -552,7 +653,7 @@ impl InodeOperations for BindLink {
552
653
  impl InodeOperations for Bind {
553
654
  /// A directory answers from its own descriptor, which follows it wherever
554
655
  /// it moves and keeps its inode taken while it is open.
555
- fn getattr(&self, dentry: &Dentry) -> Result<Kstat, FilesystemError> {
656
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
556
657
  Ok(to_kstat(
557
658
  self.fid_lookup(dentry)?.dir_metadata().map_err(to_error)?,
558
659
  ))
@@ -560,7 +661,7 @@ impl InodeOperations for Bind {
560
661
 
561
662
  /// A directory takes the times through the descriptor that holds it, as it
562
663
  /// answers for itself.
563
- fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), FilesystemError> {
664
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
564
665
  let (atime, mtime) = (to_host_time(attr.atime), to_host_time(attr.mtime));
565
666
  self.fid_lookup(dentry)?
566
667
  .set_times(".", atime, mtime)
@@ -571,7 +672,7 @@ impl InodeOperations for Bind {
571
672
  /// it, as a lookup hands `d_splice_alias` the inode it found, so
572
673
  /// `revalidate` can tell a dentry the host replaced behind the
573
674
  /// runtime's back. That costs one host stat a name.
574
- fn lookup(&self, dentry: &Dentry) -> Result<Lookup, FilesystemError> {
675
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
575
676
  self.at(dentry, |dir, name| {
576
677
  let stored_name = lookup::lookup(dir, name)?;
577
678
  match dir.symlink_metadata(&stored_name).map_err(to_error) {
@@ -591,29 +692,28 @@ impl InodeOperations for Bind {
591
692
  }),
592
693
  }
593
694
  }
594
- Err(FilesystemError::NotFound) => Ok(Lookup::Absent),
695
+ Err(Errno::NotFound) => Ok(Lookup::Absent),
595
696
  Err(err) => Err(err),
596
697
  }
597
698
  })
598
699
  }
599
700
 
600
- fn open(
601
- &self,
602
- dentry: &Dentry,
603
- how: &OpenHow,
604
- ) -> Result<Box<dyn FileOperations>, FilesystemError> {
701
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
605
702
  let fid = self.fid_lookup(dentry)?;
606
703
  if how.read {
607
704
  may_read_dir(&fid)?;
608
705
  }
609
706
  OpenDirFid::set(dentry, &fid);
610
- Ok(Box::new(BindDir(fid, Rdir::default())))
707
+ Ok(Box::new(BindDir {
708
+ fid,
709
+ cache: Rdir::default(),
710
+ }))
611
711
  }
612
712
 
613
713
  /// A name still in lookup is looked up first, and any name is left to the
614
714
  /// VFS unless the open may make it and nothing stands there, as 9p's
615
715
  /// `v9fs_vfs_atomic_open_dotl` asks its server before it creates.
616
- fn atomic_open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Finish, FilesystemError> {
716
+ fn atomic_open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Finish, Errno> {
617
717
  if dentry.in_lookup() {
618
718
  let found = self.lookup(dentry)?;
619
719
  if !how.create || !matches!(found, Lookup::Absent) {
@@ -630,16 +730,20 @@ impl InodeOperations for Bind {
630
730
  })
631
731
  }
632
732
 
633
- fn mkdir(&self, dentry: &Dentry) -> Result<(), FilesystemError> {
733
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
634
734
  self.at(dentry, |dir, name| dir.create_dir(name).map_err(to_error))
635
735
  }
636
736
 
637
- fn rmdir(&self, dentry: &Dentry) -> Result<(), FilesystemError> {
737
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
638
738
  self.at(dentry, |dir, name| dir.remove_dir(name).map_err(to_error))
639
739
  }
640
740
 
641
- fn unlink(&self, dentry: &Dentry) -> Result<(), FilesystemError> {
642
- self.at(dentry, |dir, name| dir.remove_file(name).map_err(to_error))
741
+ /// Whatever stands at the name and is no directory goes, a link to a
742
+ /// directory included, which Windows removes as a directory.
743
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
744
+ self.at(dentry, |dir, name| {
745
+ dir.remove_file_or_symlink(name).map_err(to_error)
746
+ })
643
747
  }
644
748
 
645
749
  /// A host directory takes no lock the runtime's check of the source
@@ -648,21 +752,21 @@ impl InodeOperations for Bind {
648
752
  /// moves one.
649
753
  fn rename(
650
754
  &self,
651
- from: &Dentry,
652
- to_dir: &dyn InodeOperations,
653
- to: &Dentry,
654
- flag: Option<RenameFlag>,
655
- ) -> Result<(), FilesystemError> {
656
- if flag.is_some() {
657
- return Err(FilesystemError::InvalidInput);
755
+ old: &Dentry,
756
+ new_dir: &dyn InodeOperations,
757
+ new: &Dentry,
758
+ flags: Option<RenameFlag>,
759
+ ) -> Result<(), Errno> {
760
+ if flags.is_some() {
761
+ return Err(Errno::InvalidInput);
658
762
  }
659
- let target = (to_dir as &dyn Any)
763
+ let target = (new_dir as &dyn Any)
660
764
  .downcast_ref::<Self>()
661
- .ok_or(FilesystemError::CrossesDevices)?;
662
- self.at(from, |from_dir, from_name| {
663
- target.at(to, |to_dir, to_name| {
664
- from_dir
665
- .rename(from_name, to_dir, to_name)
765
+ .ok_or(Errno::CrossesDevices)?;
766
+ self.at(old, |old_dir, old_name| {
767
+ target.at(new, |new_dir, new_name| {
768
+ old_dir
769
+ .rename(old_name, new_dir, new_name)
666
770
  .map_err(to_error)
667
771
  })
668
772
  })
@@ -672,7 +776,11 @@ impl InodeOperations for Bind {
672
776
  /// A host directory, open on the descriptor it holds, as 9p's `v9fs_dir_readdir`
673
777
  /// reads the fid in `private_data`, so it follows the directory wherever it
674
778
  /// moves.
675
- struct BindDir(Arc<Dir>, Rdir);
779
+ struct BindDir {
780
+ fid: Arc<Dir>,
781
+ /// What a listing began with, as 9p's `fid->rdir` holds it.
782
+ cache: Rdir,
783
+ }
676
784
 
677
785
  impl FileOperations for BindDir {
678
786
  fn llseek(
@@ -681,49 +789,76 @@ impl FileOperations for BindDir {
681
789
  pos: u64,
682
790
  offset: i64,
683
791
  whence: Whence,
684
- ) -> Result<u64, FilesystemError> {
792
+ ) -> Result<u64, Errno> {
685
793
  generic_file_llseek(dentry, pos, offset, whence)
686
794
  }
687
795
 
688
- fn read_iter(&mut self, _iocb: &mut Kiocb, _buf: &mut [u8]) -> Result<usize, FilesystemError> {
796
+ fn read_iter(&mut self, _iocb: &mut Kiocb, _buf: &mut [u8]) -> Result<usize, Errno> {
689
797
  generic_read_dir()
690
798
  }
691
799
 
800
+ fn has_iterate_shared(&self) -> bool {
801
+ true
802
+ }
803
+
692
804
  /// What a listing began with stays on the open directory until it ends, as
693
805
  /// 9p's `fid->rdir` holds what the server sent.
694
- fn iterate_shared(
695
- &mut self,
696
- dentry: &Dentry,
697
- ctx: &mut DirContext<'_>,
698
- ) -> Result<(), FilesystemError> {
699
- let dir = self.0.clone();
700
- self.1.iterate(dentry, ctx, || entries_of(&dir))
806
+ fn iterate_shared(&mut self, dentry: &Dentry, ctx: &mut DirContext<'_>) -> Result<(), Errno> {
807
+ let dir = self.fid.clone();
808
+ self.cache.iterate_shared(dentry, ctx, || entries_of(&dir))
701
809
  }
702
810
 
703
811
  /// Make the host directory's names durable. Windows syncs no directory, so
704
812
  /// there the host answers for them itself.
705
- fn fsync(&mut self, _datasync: bool) -> Result<(), FilesystemError> {
706
- sync_dir(&self.0)
813
+ fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
814
+ sync_dir(&self.fid)
707
815
  }
708
816
  }
709
817
 
710
818
  /// `dir` opened to read. cap-std holds a directory for its path alone on Linux,
711
819
  /// which reads and syncs nothing, so the host judges reading it only here.
712
820
  #[cfg(unix)]
713
- fn open_to_read(dir: &Dir) -> Result<rustix::fd::OwnedFd, FilesystemError> {
821
+ fn open_to_read(dir: &Dir) -> Result<rustix::fd::OwnedFd, Errno> {
822
+ FIDS.open(|| open_to_read_once(dir).map_err(to_error))
823
+ }
824
+
825
+ /// One try at `open_to_read`, answering the host's own error.
826
+ #[cfg(unix)]
827
+ fn open_to_read_once(dir: &Dir) -> io::Result<rustix::fd::OwnedFd> {
714
828
  use rustix::fs::{openat, Mode, OFlags};
715
829
 
716
830
  let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
717
- openat(dir, ".", flags, Mode::empty()).map_err(|err| to_error(io::Error::from(err)))
831
+ openat(dir, ".", flags, Mode::empty()).map_err(io::Error::from)
832
+ }
833
+
834
+ /// Whether the host lets `dir` be read, answering the host's own error when
835
+ /// it does not.
836
+ #[cfg(unix)]
837
+ fn readable(dir: &Dir) -> io::Result<()> {
838
+ open_to_read_once(dir).map(drop)
839
+ }
840
+
841
+ #[cfg(not(unix))]
842
+ fn readable(_dir: &Dir) -> io::Result<()> {
843
+ Ok(())
844
+ }
845
+
846
+ /// Whether the host refused for want of descriptors, its process's or its
847
+ /// machine's.
848
+ fn host_out_of_descriptors(err: &io::Error) -> bool {
849
+ matches!(
850
+ Errno::from_io_error(err),
851
+ Errno::TooManyOpenFiles | Errno::TooManyOpenFilesInSystem
852
+ )
718
853
  }
719
854
 
720
855
  #[cfg(unix)]
721
- fn sync_dir(dir: &Dir) -> Result<(), FilesystemError> {
856
+ fn sync_dir(dir: &Dir) -> Result<(), Errno> {
722
857
  rustix::fs::fsync(open_to_read(dir)?).map_err(|err| to_error(io::Error::from(err)))
723
858
  }
724
859
 
725
860
  #[cfg(not(unix))]
726
- fn sync_dir(_dir: &Dir) -> Result<(), FilesystemError> {
861
+ fn sync_dir(_dir: &Dir) -> Result<(), Errno> {
727
862
  Ok(())
728
863
  }
729
864
 
@@ -731,12 +866,12 @@ fn sync_dir(_dir: &Dir) -> Result<(), FilesystemError> {
731
866
  /// asks `inode_permission`. A file holds it for what it was opened for, so a
732
867
  /// directory reached only for its path answers no such question.
733
868
  #[cfg(unix)]
734
- fn may_read_dir(dir: &Dir) -> Result<(), FilesystemError> {
869
+ fn may_read_dir(dir: &Dir) -> Result<(), Errno> {
735
870
  open_to_read(dir).map(drop)
736
871
  }
737
872
 
738
873
  #[cfg(not(unix))]
739
- fn may_read_dir(_dir: &Dir) -> Result<(), FilesystemError> {
874
+ fn may_read_dir(_dir: &Dir) -> Result<(), Errno> {
740
875
  Ok(())
741
876
  }
742
877
 
@@ -747,17 +882,22 @@ struct BindFile {
747
882
  }
748
883
 
749
884
  impl BindFile {
750
- /// Windows has no append to switch one handle to for a single write,
751
- /// so an append that could land over another writer's is refused.
752
- #[cfg(not(unix))]
753
- fn append(&mut self, _iocb: &mut Kiocb, _buf: &[u8]) -> Result<usize, FilesystemError> {
754
- Err(FilesystemError::Unsupported)
885
+ /// The host places the write at the file's end: a write at the offset of
886
+ /// all ones bits does, as a handle opened with `FILE_APPEND_DATA` would,
887
+ /// so another writer's append lands before or after it, never over it.
888
+ #[cfg(windows)]
889
+ fn append(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
890
+ use std::os::windows::fs::FileExt;
891
+
892
+ let written = self.file.seek_write(buf, u64::MAX).map_err(to_error)?;
893
+ iocb.pos = (&*self.file).stream_position().map_err(to_error)?;
894
+ Ok(written)
755
895
  }
756
896
 
757
897
  /// The host places the write at the file's end as `O_APPEND` does, so
758
898
  /// another writer's append lands before or after it, never over it.
759
899
  #[cfg(unix)]
760
- fn append(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, FilesystemError> {
900
+ fn append(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
761
901
  use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
762
902
 
763
903
  let mut file = &*self.file;
@@ -785,11 +925,11 @@ impl FileOperations for BindFile {
785
925
  pos: u64,
786
926
  offset: i64,
787
927
  whence: Whence,
788
- ) -> Result<u64, FilesystemError> {
928
+ ) -> Result<u64, Errno> {
789
929
  generic_file_llseek(dentry, pos, offset, whence)
790
930
  }
791
931
 
792
- fn read_iter(&mut self, iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, FilesystemError> {
932
+ fn read_iter(&mut self, iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
793
933
  let mut file = &*self.file;
794
934
  file.seek(SeekFrom::Start(iocb.pos)).map_err(to_error)?;
795
935
  let read = file.read(buf).map_err(to_error)?;
@@ -797,7 +937,7 @@ impl FileOperations for BindFile {
797
937
  Ok(read)
798
938
  }
799
939
 
800
- fn write_iter(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, FilesystemError> {
940
+ fn write_iter(&mut self, iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
801
941
  let written = match iocb.append {
802
942
  true => self.append(iocb, buf)?,
803
943
  false => {
@@ -811,7 +951,7 @@ impl FileOperations for BindFile {
811
951
  crate::vfs::generic_write_sync(self, iocb, written)
812
952
  }
813
953
 
814
- fn fsync(&mut self, datasync: bool) -> Result<(), FilesystemError> {
954
+ fn fsync(&mut self, datasync: bool) -> Result<(), Errno> {
815
955
  match datasync {
816
956
  true => self.file.sync_data(),
817
957
  false => self.file.sync_all(),
@@ -821,9 +961,9 @@ impl FileOperations for BindFile {
821
961
 
822
962
  /// Reserve the room on the host, as `v9fs_file_fallocate` asks its server. Only
823
963
  /// Linux grows a file in one step without shortening one a peer just grew, so
824
- /// elsewhere this refuses, as an append that cannot land in one step does.
964
+ /// elsewhere this refuses rather than take two steps a peer could land between.
825
965
  #[cfg(target_os = "linux")]
826
- fn fallocate(&mut self, offset: u64, len: u64) -> Result<(), FilesystemError> {
966
+ fn fallocate(&mut self, offset: u64, len: u64) -> Result<(), Errno> {
827
967
  let flags = rustix::fs::FallocateFlags::empty();
828
968
  rustix::fs::fallocate(&*self.file, flags, offset, len)
829
969
  .map_err(|err| to_error(io::Error::from(err)))
@@ -839,13 +979,11 @@ mod tests {
839
979
  use crate::vfs::kern_path::{kern_path, KernPath};
840
980
 
841
981
  /// A Bind reports times only where the host names them.
842
- #[cfg(unix)]
843
982
  mod set_times {
844
983
  use super::*;
845
984
  use crate::filesystem::{Overlay, Tmpfs};
846
985
  use crate::mount::{Access, Mount};
847
- use crate::vfs::kern_path::filp_open;
848
- use crate::vfs::{do_utimes_fd, do_utimes_path, vfs_fstatat, OpenHow, Path as VfsPath};
986
+ use crate::vfs::{do_utimes_path, vfs_fstatat, Path as VfsPath};
849
987
 
850
988
  /// One second past the Unix epoch, which no clock is at.
851
989
  fn moment() -> std::time::SystemTime {
@@ -853,7 +991,7 @@ mod tests {
853
991
  }
854
992
 
855
993
  fn set_modified() -> Iattr<'static> {
856
- Iattr::times(None, Some(SetTime::At(moment())))
994
+ Iattr::for_times(None, Some(SetTime::At(moment())))
857
995
  }
858
996
 
859
997
  /// The root of `filesystem` mounted to change.
@@ -871,8 +1009,8 @@ mod tests {
871
1009
  fn overlay_of(lower: Bind) -> Arc<Overlay> {
872
1010
  Arc::new(
873
1011
  Overlay::new(
874
- vec![Filesystem::new(Arc::new(lower)).expect("the instance must stand")],
875
- Some(Filesystem::new(Arc::new(Tmpfs::new())).expect("the instance must stand")),
1012
+ vec![Filesystem::new(lower).expect("the instance must stand")],
1013
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
876
1014
  )
877
1015
  .unwrap_or_else(|_| panic!("the Overlay must stack")),
878
1016
  )
@@ -925,8 +1063,8 @@ mod tests {
925
1063
  assert_eq!(
926
1064
  (answers, host_modified(&host.0.join("dir/file.txt"))),
927
1065
  ([(set, set); 3], set),
928
- "vfs::do_utimes_pathon a file and a directory of a Tmpfs, a Bind, and an Overlay must \
929
- keep the time, a Bind's on the host"
1066
+ "a modified time set on a file and a directory of a Tmpfs, a Bind, and an Overlay \
1067
+ must read back from a stat, and a Bind's must reach its host entry"
930
1068
  );
931
1069
  }
932
1070
 
@@ -939,8 +1077,8 @@ mod tests {
939
1077
  assert_eq!(
940
1078
  (seen, host_modified(&host.0.join("dir")) == before),
941
1079
  (Some(moment()), true),
942
- "vfs::do_utimes_pathon a directory through an Overlay must show the time and leave the \
943
- lower Layer's directory as it was"
1080
+ "a modified time set on a directory through an Overlay must read back from a stat and \
1081
+ leave the lower Layer's directory as it was"
944
1082
  );
945
1083
  }
946
1084
 
@@ -950,7 +1088,7 @@ mod tests {
950
1088
  #[test]
951
1089
  fn a_link_keeps_its_own_times() {
952
1090
  let host = host_with_a_file("link-time");
953
- std::os::unix::fs::symlink("dir", host.0.join("link")).expect("the link must be made");
1091
+ crate::filesystem::testing::symlink("dir", host.0.join("link"));
954
1092
  assert_eq!(
955
1093
  do_utimes_path(
956
1094
  &Arc::default(),
@@ -959,8 +1097,8 @@ mod tests {
959
1097
  false,
960
1098
  &set_modified(),
961
1099
  ),
962
- Err(FilesystemError::Unsupported),
963
- "vfs::do_utimes_pathfollowing no link of a Bind's link must answer ENOTSUP"
1100
+ Err(Errno::Unsupported),
1101
+ "setting the times of a Bind's link without following it must answer ENOTSUP"
964
1102
  );
965
1103
  }
966
1104
 
@@ -968,6 +1106,9 @@ mod tests {
968
1106
  // @behavior FS-188
969
1107
  #[test]
970
1108
  fn a_time_set_through_a_descriptor_reaches_the_file_it_holds() {
1109
+ use crate::vfs::kern_path::filp_open;
1110
+ use crate::vfs::{do_utimes_fd, OpenHow};
1111
+
971
1112
  let host = host_with_a_file("held-time");
972
1113
  let root = root_of(Arc::new(bind_of(&host)));
973
1114
  let how = OpenHow {
@@ -985,8 +1126,8 @@ mod tests {
985
1126
  assert_eq!(
986
1127
  (answer, held_time, host_modified(&file) == other_before),
987
1128
  (Ok(()), Some(moment()), true),
988
- "vfs::do_utimes_fd through a Bind's descriptor must set the file it holds, and leave \
989
- what took its name"
1129
+ "a time set through a Bind's descriptor must reach the file it holds, and leave what \
1130
+ took its name"
990
1131
  );
991
1132
  }
992
1133
  }
@@ -1020,7 +1161,6 @@ mod tests {
1020
1161
 
1021
1162
  /// A Bind over `depth` nested directories each named `d`, with the file
1022
1163
  /// `f` at the bottom, and the path to that file.
1023
- #[cfg(unix)]
1024
1164
  fn nested_tree(host: &HostDir, depth: usize) -> (Arc<Bind>, String) {
1025
1165
  let path = vec!["d"; depth].join("/");
1026
1166
  fs::create_dir_all(host.0.join(&path)).expect("the host tree must be made");
@@ -1029,33 +1169,89 @@ mod tests {
1029
1169
  (bind, format!("{path}/f"))
1030
1170
  }
1031
1171
 
1032
- // Counted on the Bind, as a count of the process's descriptors would see
1033
- // every other test's. Past the bound the walk still lands, so nothing a
1034
- // guest reaches depends on what was kept.
1035
- // @behavior FS-151
1172
+ // The same move behind each Bind, so the one told apart is what each
1173
+ // asks of the host again.
1174
+ // @behavior FS-207
1036
1175
  #[cfg(unix)]
1037
1176
  #[test]
1038
- fn a_walk_keeps_a_bounded_number_of_host_directories_open() {
1177
+ fn an_exclusive_bind_keeps_the_directory_it_found() {
1178
+ let size_after_a_move = |name: &str, exclusive: bool| {
1179
+ let host = HostDir::new(name);
1180
+ fs::create_dir(host.0.join("d")).expect("the host directory must be made");
1181
+ fs::write(host.0.join("d/f"), "x").expect("the host file must be written");
1182
+ let bind = Bind::new(&host.0)
1183
+ .expect("the host directory must open")
1184
+ .with_exclusive(exclusive);
1185
+ let root = kern_path(Arc::new(bind));
1186
+ root.vfs_lstat("d/f").expect("the file must stand");
1187
+ fs::rename(host.0.join("d"), host.0.join("moved")).expect("the host move must land");
1188
+ fs::create_dir(host.0.join("d")).expect("the host directory must be made");
1189
+ fs::write(host.0.join("d/f"), "xxxxx").expect("the host file must be written");
1190
+ root.vfs_lstat("d/f").map(|stat| stat.size)
1191
+ };
1192
+ assert_eq!(
1193
+ (
1194
+ size_after_a_move("exclusive-moved", true),
1195
+ size_after_a_move("plain-moved", false)
1196
+ ),
1197
+ (Ok(1), Ok(5)),
1198
+ "a walk through d/f after the host moved another d into place must reach the d it found \
1199
+ through an exclusive Bind, and the new d through one that is not"
1200
+ );
1201
+ }
1202
+
1203
+ // Counted on the cache, as a count of the process's descriptors would see
1204
+ // every other test's; the bound holds for whatever they keep. Past the
1205
+ // bound each walk still lands, so nothing a guest reaches depends on what
1206
+ // was kept.
1207
+ // @behavior FS-151
1208
+ #[test]
1209
+ fn the_binds_of_a_process_keep_a_bounded_number_of_host_directories_open() {
1039
1210
  use crate::vfs::{self, OpenHow, Path as VfsPath};
1040
- let host = HostDir::new("bounded-fids");
1041
- let (bind, file) = nested_tree(&host, 200);
1042
- let mount = crate::mount::Mount::new(
1043
- "/data",
1044
- crate::filesystem::Filesystem::new(bind.clone()).expect("the instance must stand"),
1045
- crate::mount::Access::Read,
1046
- )
1047
- .expect("/data is a guest path");
1048
- let root = VfsPath::root(mount.mnt());
1049
1211
  let read = OpenHow {
1050
1212
  read: true,
1051
1213
  ..OpenHow::default()
1052
1214
  };
1053
- let opened = vfs::kern_path::filp_open(&Arc::default(), &root, &file, &read);
1215
+ let hosts = [
1216
+ HostDir::new("bounded-fids-a"),
1217
+ HostDir::new("bounded-fids-b"),
1218
+ ];
1219
+ let opened = hosts.iter().map(|host| {
1220
+ let (bind, file) = nested_tree(host, 100);
1221
+ let mount = crate::mount::Mount::new(
1222
+ "/data",
1223
+ crate::filesystem::Filesystem::new(bind.clone()).expect("the instance must stand"),
1224
+ crate::mount::Access::Read,
1225
+ )
1226
+ .expect("/data is a guest path");
1227
+ let root = VfsPath::root(mount.mnt());
1228
+ let file = vfs::kern_path::filp_open(&Arc::default(), &root, &file, &read);
1229
+ (file.is_ok(), bind)
1230
+ });
1231
+ let (opened, binds): (Vec<_>, Vec<_>) = opened.unzip();
1054
1232
  assert!(
1055
- opened.is_ok() && bind.fids.len() <= 64,
1056
- "vfs::do_file_open 200 directories beneath a Bind must land and keep at most 64 of \
1057
- them open, keeping {}",
1058
- bind.fids.len()
1233
+ opened.iter().all(|&opened| opened) && FIDS.len() <= 64,
1234
+ "an open of a file 100 directories beneath each of two binds must land, the process \
1235
+ keeping at most 64 of those directories open, keeping {}",
1236
+ FIDS.len()
1237
+ );
1238
+ drop(binds);
1239
+ }
1240
+
1241
+ // @behavior FS-221
1242
+ #[test]
1243
+ fn a_bind_let_go_closes_the_directories_its_walks_kept() {
1244
+ let host = HostDir::new("released-fids");
1245
+ let (bind, file) = nested_tree(&host, 8);
1246
+ let owner = bind.fids.id();
1247
+ let root = kern_path(bind);
1248
+ root.vfs_lstat(&file).expect("the file must stand");
1249
+ let kept = FIDS.kept_by(owner);
1250
+ drop(root);
1251
+ assert_eq!(
1252
+ (kept > 0, FIDS.kept_by(owner)),
1253
+ (true, 0),
1254
+ "a Bind let go after a walk 8 directories deep must close every directory it kept"
1059
1255
  );
1060
1256
  }
1061
1257
 
@@ -1076,15 +1272,13 @@ mod tests {
1076
1272
  };
1077
1273
  let overlay = crate::filesystem::Overlay::new(
1078
1274
  vec![
1079
- Filesystem::new(Arc::new(crate::filesystem::Tmpfs::new()))
1080
- .expect("the instance must stand"),
1081
- Filesystem::new(Arc::new(crate::filesystem::Tmpfs::new()))
1082
- .expect("the instance must stand"),
1275
+ Filesystem::new(crate::filesystem::Tmpfs::new()).expect("the instance must stand"),
1276
+ Filesystem::new(crate::filesystem::Tmpfs::new()).expect("the instance must stand"),
1083
1277
  ],
1084
1278
  None,
1085
1279
  )
1086
1280
  .expect("the Overlay must stack");
1087
- let refused = Some(FilesystemError::IsADirectory);
1281
+ let refused = Some(Errno::IsADirectory);
1088
1282
  for answer in [
1089
1283
  read(Arc::new(crate::filesystem::Tmpfs::new())),
1090
1284
  read(Arc::new(
@@ -1110,9 +1304,9 @@ mod tests {
1110
1304
  let host = HostDir::new("kept-absent");
1111
1305
  let mount = crate::mount::Mount::new(
1112
1306
  "/data",
1113
- crate::filesystem::Filesystem::new(Arc::new(
1307
+ crate::filesystem::Filesystem::new(
1114
1308
  Bind::new(&host.0).expect("the host directory must open"),
1115
- ))
1309
+ )
1116
1310
  .expect("the instance must stand"),
1117
1311
  crate::mount::Access::ReadWrite,
1118
1312
  )
@@ -1124,7 +1318,7 @@ mod tests {
1124
1318
  fs::write(host.0.join("x"), "x").expect("the host file must be written");
1125
1319
  assert_eq!(
1126
1320
  (before, stat()),
1127
- (Some(FilesystemError::NotFound), None),
1321
+ (Some(Errno::NotFound), None),
1128
1322
  "vfs::vfs_fstatat of a name kept as absent, once the host made a file there, must \
1129
1323
  find the file"
1130
1324
  );
@@ -1139,9 +1333,9 @@ mod tests {
1139
1333
  let host = HostDir::new("made-at-absent");
1140
1334
  let mount = crate::mount::Mount::new(
1141
1335
  "/data",
1142
- crate::filesystem::Filesystem::new(Arc::new(
1336
+ crate::filesystem::Filesystem::new(
1143
1337
  Bind::new(&host.0).expect("the host directory must open"),
1144
- ))
1338
+ )
1145
1339
  .expect("the instance must stand"),
1146
1340
  crate::mount::Access::ReadWrite,
1147
1341
  )
@@ -1153,7 +1347,7 @@ mod tests {
1153
1347
  let after = vfs::vfs_fstatat(&cred, &root, "made", false).map(|made| made.file_type);
1154
1348
  assert_eq!(
1155
1349
  (before, after),
1156
- (Some(FilesystemError::NotFound), Ok(FileType::Dir)),
1350
+ (Some(Errno::NotFound), Ok(FileType::Dir)),
1157
1351
  "vfs::filename_mkdirat at a name kept as absent must leave the next walk finding \
1158
1352
  the directory, as d_drop leaves a dentry nothing recorded on"
1159
1353
  );
@@ -1173,18 +1367,19 @@ mod tests {
1173
1367
  fs::write(host.0.join("m/x/secret"), "s").expect("the host file must be written");
1174
1368
  let mount = crate::mount::Mount::new(
1175
1369
  "/data",
1176
- crate::filesystem::Filesystem::new(Arc::new(
1370
+ crate::filesystem::Filesystem::new(
1177
1371
  Bind::new(host.0.join("m")).expect("the host directory must open"),
1178
- ))
1372
+ )
1179
1373
  .expect("the instance must stand"),
1180
1374
  crate::mount::Access::Read,
1181
1375
  )
1182
1376
  .expect("/data is a guest path");
1183
1377
  let root = VfsPath::root(mount.mnt());
1184
1378
  let cred = crate::security::restrict_self(
1185
- &crate::security::prepare_creds_within(&[], None),
1186
- [&mount],
1187
- );
1379
+ &crate::security::prepare_creds(&[], None),
1380
+ [&crate::grant::Grant::Mount(mount.clone())],
1381
+ )
1382
+ .expect("every Mount stands");
1188
1383
  let read = OpenHow {
1189
1384
  read: true,
1190
1385
  ..OpenHow::default()
@@ -1194,7 +1389,7 @@ mod tests {
1194
1389
  fs::rename(host.0.join("m/x"), host.0.join("outside/x")).expect("the host must move it");
1195
1390
  assert_eq!(
1196
1391
  (before, open()),
1197
- (None, Some(FilesystemError::NotFound)),
1392
+ (None, Some(Errno::NotFound)),
1198
1393
  "vfs::do_file_open through a name kept since the last walk, once the host moved it \
1199
1394
  out of the Mount, must answer ENOENT"
1200
1395
  );
@@ -1204,7 +1399,6 @@ mod tests {
1204
1399
  // file onto where it went, between the judgement and the open, so only
1205
1400
  // telling what opened from what was judged keeps the open from reaching it.
1206
1401
  // @behavior FS-156
1207
- #[cfg(unix)]
1208
1402
  #[test]
1209
1403
  fn an_open_reaches_only_the_entry_it_judged() {
1210
1404
  use crate::vfs::{self, OpenHow, Path as VfsPath};
@@ -1212,8 +1406,8 @@ mod tests {
1212
1406
  /// Runs what it holds once, as a Policy is asked, then allows it.
1213
1407
  struct RunsWhenAsked(std::sync::Mutex<Option<Box<dyn FnOnce() + Send>>>);
1214
1408
 
1215
- impl crate::mount::Policy for RunsWhenAsked {
1216
- fn allows(&self, _path: &str, _access: crate::mount::Access) -> bool {
1409
+ impl crate::policy::Policy<crate::mount::MountRequest<'_>> for RunsWhenAsked {
1410
+ fn allows(&self, _request: &crate::mount::MountRequest<'_>) -> bool {
1217
1411
  let run = self.0.lock().expect("never poisoned").take();
1218
1412
  if let Some(run) = run {
1219
1413
  run();
@@ -1228,9 +1422,9 @@ mod tests {
1228
1422
  }
1229
1423
  fs::write(host.0.join("public/x"), "judged").expect("the host file must be written");
1230
1424
  fs::write(host.0.join("archive/secret"), "refused").expect("the host file must be written");
1231
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1425
+ let filesystem = crate::filesystem::Filesystem::new(
1232
1426
  Bind::new(&host.0).expect("the host directory must open"),
1233
- ))
1427
+ )
1234
1428
  .expect("the instance must stand");
1235
1429
  let writer =
1236
1430
  crate::mount::Mount::new("/data", filesystem.clone(), crate::mount::Access::ReadWrite)
@@ -1252,16 +1446,17 @@ mod tests {
1252
1446
  };
1253
1447
  let opened = vfs::kern_path::filp_open(
1254
1448
  &crate::security::restrict_self(
1255
- &crate::security::prepare_creds_within(&[], None),
1256
- [&mount],
1257
- ),
1449
+ &crate::security::prepare_creds(&[], None),
1450
+ [&crate::grant::Grant::Mount(mount.clone())],
1451
+ )
1452
+ .expect("every Mount stands"),
1258
1453
  &VfsPath::root(mount.mnt()),
1259
1454
  "public/x",
1260
1455
  &read,
1261
1456
  );
1262
1457
  assert_eq!(
1263
1458
  opened.err(),
1264
- Some(FilesystemError::NotFound),
1459
+ Some(Errno::NotFound),
1265
1460
  "vfs::do_file_open of a file another writer replaced after the Policy judged it must \
1266
1461
  answer ENOENT rather than open what stands there now"
1267
1462
  );
@@ -1322,9 +1517,9 @@ mod tests {
1322
1517
  use crate::vfs::{self, OpenHow};
1323
1518
  let host = HostDir::new("remade");
1324
1519
  fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1325
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1520
+ let filesystem = crate::filesystem::Filesystem::new(
1326
1521
  Bind::new(&host.0).expect("the host directory must open"),
1327
- ))
1522
+ )
1328
1523
  .expect("the instance must stand");
1329
1524
  let mount = Mount::new("/data", filesystem, crate::mount::Access::ReadWrite)
1330
1525
  .expect("/data is a guest path");
@@ -1352,14 +1547,50 @@ mod tests {
1352
1547
  );
1353
1548
  }
1354
1549
 
1550
+ // A Windows host refuses to move a directory a process holds open.
1551
+ // @behavior FS-225
1552
+ #[cfg(unix)]
1553
+ #[test]
1554
+ fn a_bind_reads_the_directory_standing_where_it_was_made() {
1555
+ use crate::mount::Mount;
1556
+ use crate::vfs::{self, OpenHow};
1557
+ let host = HostDir::new("made-over");
1558
+ let (made, moved) = (host.0.join("root"), host.0.join("moved"));
1559
+ fs::create_dir_all(made.join("d0")).expect("the host directory must be made");
1560
+ fs::write(made.join("d0/note.txt"), "hello").expect("the host file must be written");
1561
+ let filesystem =
1562
+ crate::filesystem::Filesystem::new(Bind::new(&made).expect("the root must open"))
1563
+ .expect("the instance must stand");
1564
+ let mount = Mount::new("/data", filesystem, crate::mount::Access::Read)
1565
+ .expect("/data is a guest path");
1566
+ fs::rename(&made, &moved).expect("the host must move it");
1567
+ fs::create_dir_all(made.join("d0")).expect("the host must make another");
1568
+ fs::write(made.join("d0/note.txt"), "other").expect("the other file must be written");
1569
+ let read = OpenHow {
1570
+ read: true,
1571
+ ..OpenHow::default()
1572
+ };
1573
+ let root = vfs::Path::root(mount.mnt());
1574
+ let mut note = vfs::kern_path::filp_open(&Arc::default(), &root, "d0/note.txt", &read)
1575
+ .unwrap_or_else(|err| panic!("the note must open, got {err:?}"));
1576
+ let mut text = [0; 5];
1577
+ let read = note.read(&mut text);
1578
+ assert_eq!(
1579
+ (read, &text),
1580
+ (Ok(5), b"hello"),
1581
+ "a file read through a Bind whose host directory was moved away and replaced by \
1582
+ another must read the directory the Bind was made over"
1583
+ );
1584
+ }
1585
+
1355
1586
  /// A Policy refusing everything beneath `/data/refused`.
1356
1587
  #[cfg(unix)]
1357
1588
  struct RefusesRefused;
1358
1589
 
1359
1590
  #[cfg(unix)]
1360
- impl crate::mount::Policy for RefusesRefused {
1361
- fn allows(&self, path: &str, _access: crate::mount::Access) -> bool {
1362
- !path.starts_with("/data/refused")
1591
+ impl crate::policy::Policy<crate::mount::MountRequest<'_>> for RefusesRefused {
1592
+ fn allows(&self, request: &crate::mount::MountRequest<'_>) -> bool {
1593
+ !request.path.starts_with("/data/refused")
1363
1594
  }
1364
1595
  }
1365
1596
 
@@ -1377,18 +1608,19 @@ mod tests {
1377
1608
  fs::create_dir_all(host.0.join("a/d")).expect("the host tree must be made");
1378
1609
  fs::create_dir_all(host.0.join("refused")).expect("the host tree must be made");
1379
1610
  fs::write(host.0.join("a/d/secret"), "s").expect("the host file must be written");
1380
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1611
+ let filesystem = crate::filesystem::Filesystem::new(
1381
1612
  Bind::new(&host.0).expect("the host directory must open"),
1382
- ))
1613
+ )
1383
1614
  .expect("the instance must stand");
1384
1615
  let mount = Mount::new("/data", filesystem, crate::mount::Access::Read)
1385
1616
  .expect("/data is a guest path")
1386
1617
  .with_policy(Arc::new(RefusesRefused));
1387
1618
  let root = vfs::Path::root(mount.mnt());
1388
1619
  let cred = crate::security::restrict_self(
1389
- &crate::security::prepare_creds_within(&[], None),
1390
- [&mount],
1391
- );
1620
+ &crate::security::prepare_creds(&[], None),
1621
+ [&crate::grant::Grant::Mount(mount.clone())],
1622
+ )
1623
+ .expect("every Mount stands");
1392
1624
  let directory = OpenHow {
1393
1625
  read: true,
1394
1626
  directory: true,
@@ -1405,7 +1637,7 @@ mod tests {
1405
1637
  };
1406
1638
  assert_eq!(
1407
1639
  vfs::kern_path::filp_open(&cred, &root, "a/d/secret", &read).err(),
1408
- Some(FilesystemError::NotFound),
1640
+ Some(Errno::NotFound),
1409
1641
  "vfs::do_file_open beneath a Bind Mount with a Policy, through a directory the host moved \
1410
1642
  beneath a refused path while a descriptor beneath it was held, must answer NotFound"
1411
1643
  );
@@ -1413,7 +1645,6 @@ mod tests {
1413
1645
 
1414
1646
  /// The roots of a Tmpfs, a Bind, and an Overlay, each holding a five byte
1415
1647
  /// `f`, by name.
1416
- #[cfg(unix)]
1417
1648
  fn each_holding_five_bytes(host: &HostDir) -> [(&'static str, crate::vfs::Path); 3] {
1418
1649
  use crate::filesystem::Filesystem;
1419
1650
  use crate::filesystem::{Overlay, Tmpfs};
@@ -1421,8 +1652,8 @@ mod tests {
1421
1652
  fs::write(host.0.join("f"), "hello").expect("the host file must be written");
1422
1653
  let tmpfs = || [("f", "hello")].into_iter().collect::<Tmpfs>();
1423
1654
  let overlay = Overlay::new(
1424
- vec![Filesystem::new(Arc::new(tmpfs())).expect("the instance must stand")],
1425
- Some(Filesystem::new(Arc::new(Tmpfs::new())).expect("the instance must stand")),
1655
+ vec![Filesystem::new(tmpfs()).expect("the instance must stand")],
1656
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
1426
1657
  )
1427
1658
  .expect("the Overlay must stack");
1428
1659
  let root = |filesystem: Arc<dyn FileSystemType>| {
@@ -1447,7 +1678,6 @@ mod tests {
1447
1678
  }
1448
1679
 
1449
1680
  // @behavior FS-141
1450
- #[cfg(unix)]
1451
1681
  #[test]
1452
1682
  fn a_file_removed_while_open_still_reports_itself() {
1453
1683
  use crate::vfs::{self, OpenHow};
@@ -1469,14 +1699,13 @@ mod tests {
1469
1699
  &buf
1470
1700
  ),
1471
1701
  (Some(5), Ok(5), b"hello"),
1472
- "File::getattr and File::pread of a file whose name \
1473
- vfs::filename_unlinkat removed on a {name} must answer what it holds"
1702
+ "a stat and a read of an open file on a {name} whose name was removed must \
1703
+ answer what it holds"
1474
1704
  );
1475
1705
  }
1476
1706
  }
1477
1707
 
1478
1708
  // @behavior FS-142
1479
- #[cfg(unix)]
1480
1709
  #[test]
1481
1710
  fn a_file_removed_while_open_can_still_be_sized() {
1482
1711
  use crate::vfs::{self, OpenHow};
@@ -1497,8 +1726,8 @@ mod tests {
1497
1726
  file.getattr().map(|found| found.size).ok()
1498
1727
  ),
1499
1728
  (Ok(()), Some(2)),
1500
- "File::truncate of a file whose name vfs::filename_unlinkat removed on a {name} \
1501
- must size what it holds"
1729
+ "a truncate of an open file on a {name} whose name was removed must size what it \
1730
+ holds"
1502
1731
  );
1503
1732
  }
1504
1733
  }
@@ -1506,7 +1735,6 @@ mod tests {
1506
1735
  // A dentry the host replaced is dropped by its identity, so the path
1507
1736
  // reaches the new file while the open one keeps its own descriptor.
1508
1737
  // @behavior FS-143
1509
- #[cfg(unix)]
1510
1738
  #[test]
1511
1739
  fn a_file_replaced_while_open_answers_apart_from_its_path() {
1512
1740
  use crate::vfs::{self, OpenHow};
@@ -1529,8 +1757,8 @@ mod tests {
1529
1757
  file.getattr().map(|found| found.size).ok()
1530
1758
  ),
1531
1759
  (Some(7), Some(5)),
1532
- "vfs::vfs_fstatat of a path the host replaced under an open File must answer the new \
1533
- file, and File::getattr the one it holds"
1760
+ "a stat of a path the host replaced under an open file must answer the new file, and \
1761
+ a stat of the open file the one it holds"
1534
1762
  );
1535
1763
  }
1536
1764
 
@@ -1547,15 +1775,13 @@ mod tests {
1547
1775
  use crate::vfs::{self, OpenHow};
1548
1776
  let host = HostDir::new("overlay-replaced");
1549
1777
  fs::create_dir(host.0.join("a")).expect("the host directory must be made");
1550
- let lower = Filesystem::new(Arc::new(
1551
- Bind::new(&host.0).expect("the host directory must open"),
1552
- ))
1553
- .expect("the instance must stand");
1554
- let upper = Filesystem::new(Arc::new(Tmpfs::new())).expect("the instance must stand");
1778
+ let lower = Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
1779
+ .expect("the instance must stand");
1780
+ let upper = Filesystem::new(Tmpfs::new()).expect("the instance must stand");
1555
1781
  let overlay = Overlay::new(vec![lower], Some(upper)).expect("the Overlay must stack");
1556
1782
  let mount = Mount::new(
1557
1783
  "/data",
1558
- Filesystem::new(Arc::new(overlay)).expect("the instance must stand"),
1784
+ Filesystem::new(overlay).expect("the instance must stand"),
1559
1785
  Access::Read,
1560
1786
  )
1561
1787
  .expect("/data is a guest path");
@@ -1595,12 +1821,12 @@ mod tests {
1595
1821
  fn a_directory_that_cannot_open_answers_why() {
1596
1822
  let host = HostDir::new("gone-before-open");
1597
1823
  fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1598
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1824
+ let filesystem = crate::filesystem::Filesystem::new(
1599
1825
  Bind::new(&host.0).expect("the host directory must open"),
1600
- ))
1826
+ )
1601
1827
  .expect("the instance must stand");
1602
1828
  let dentries = filesystem.dentries();
1603
- let root = filesystem.s_root();
1829
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1604
1830
  let dir = dentries
1605
1831
  .alloc_parallel(&root, "a")
1606
1832
  .expect("no other walk holds the name");
@@ -1613,7 +1839,7 @@ mod tests {
1613
1839
  .open(&dir, &OpenHow::default());
1614
1840
  assert_eq!(
1615
1841
  answer.err(),
1616
- Some(FilesystemError::NotFound),
1842
+ Some(Errno::NotFound),
1617
1843
  "InodeOperations::open of a Bind's directory the host removed must answer ENOENT"
1618
1844
  );
1619
1845
  }
@@ -1626,12 +1852,12 @@ mod tests {
1626
1852
  fn a_directory_the_host_replaced_is_not_walked_to_in_its_place() {
1627
1853
  let host = HostDir::new("replaced-before-walk");
1628
1854
  fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1629
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1855
+ let filesystem = crate::filesystem::Filesystem::new(
1630
1856
  Bind::new(&host.0).expect("the host directory must open"),
1631
- ))
1857
+ )
1632
1858
  .expect("the instance must stand");
1633
1859
  let dentries = filesystem.dentries();
1634
- let root = filesystem.s_root();
1860
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1635
1861
  let dir = dentries
1636
1862
  .alloc_parallel(&root, "a")
1637
1863
  .expect("no other walk holds the name");
@@ -1641,7 +1867,7 @@ mod tests {
1641
1867
  fs::create_dir(host.0.join("a")).expect("the host must make another");
1642
1868
  assert_eq!(
1643
1869
  dir.getattr().err(),
1644
- Some(FilesystemError::NotFound),
1870
+ Some(Errno::NotFound),
1645
1871
  "InodeOperations::getattr of a Bind directory the host replaced must answer ENOENT \
1646
1872
  rather than what stands there now"
1647
1873
  );
@@ -1654,12 +1880,12 @@ mod tests {
1654
1880
  fn a_filesystem_taking_no_rename_flag_refuses_one() {
1655
1881
  let host = HostDir::new("rename-flag");
1656
1882
  fs::write(host.0.join("a"), "a").expect("the host file must be written");
1657
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1883
+ let filesystem = crate::filesystem::Filesystem::new(
1658
1884
  Bind::new(&host.0).expect("the host directory must open"),
1659
- ))
1885
+ )
1660
1886
  .expect("the instance must stand");
1661
1887
  let dentries = filesystem.dentries();
1662
- let root = filesystem.s_root();
1888
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1663
1889
  let dir = root.inode().expect("the root stands").ops().clone();
1664
1890
  let at = |name| {
1665
1891
  dentries
@@ -1674,7 +1900,7 @@ mod tests {
1674
1900
  );
1675
1901
  assert_eq!(
1676
1902
  (answer, host.0.join("a").exists()),
1677
- (Err(FilesystemError::InvalidInput), true),
1903
+ (Err(Errno::InvalidInput), true),
1678
1904
  "InodeOperations::rename of a Bind asked for a flag must answer EINVAL and move \
1679
1905
  nothing"
1680
1906
  );
@@ -1688,12 +1914,12 @@ mod tests {
1688
1914
  let host = HostDir::new("named-then-moved");
1689
1915
  fs::create_dir_all(host.0.join("a")).expect("the host directory must be made");
1690
1916
  fs::write(host.0.join("a/note"), "n").expect("the host file must be written");
1691
- let filesystem = crate::filesystem::Filesystem::new(Arc::new(
1917
+ let filesystem = crate::filesystem::Filesystem::new(
1692
1918
  Bind::new(&host.0).expect("the host directory must open"),
1693
- ))
1919
+ )
1694
1920
  .expect("the instance must stand");
1695
1921
  let dentries = filesystem.dentries();
1696
- let root = filesystem.s_root();
1922
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1697
1923
  let at = |dir: &Arc<Dentry>, name| {
1698
1924
  dentries
1699
1925
  .alloc_parallel(dir, name)
@@ -1706,7 +1932,7 @@ mod tests {
1706
1932
  assert!(
1707
1933
  matches!(
1708
1934
  root.inode().expect("the root stands").ops().lookup(&note),
1709
- Ok(Lookup::Found(inode)) if inode.kind() == FileType::RegFile
1935
+ Ok(Lookup::Found(inode)) if inode.file_type() == FileType::RegFile
1710
1936
  ),
1711
1937
  "a name looked up through Bind in a directory not yet opened, once its dentry moved \
1712
1938
  with it, must be found where the dentry stands"
@@ -1748,15 +1974,52 @@ mod tests {
1748
1974
  });
1749
1975
  assert_eq!(
1750
1976
  answered.recv_timeout(crate::sched::testing::MAX_WAIT),
1751
- Ok([
1752
- Some(FilesystemError::PermissionDenied),
1753
- Some(FilesystemError::PermissionDenied)
1754
- ]),
1977
+ Ok([Some(Errno::PermissionDenied), Some(Errno::PermissionDenied)]),
1755
1978
  "a FIFO and a device opened through Bind::open must be refused as permission \
1756
1979
  denied without waiting"
1757
1980
  );
1758
1981
  }
1759
1982
 
1983
+ // The host reports each open of an entry to a watch on its directory, and
1984
+ // an open by O_PATH opens nothing, so a refusal it reports no open for
1985
+ // never acted on the entry.
1986
+ // @behavior FS-208
1987
+ #[cfg(target_os = "linux")]
1988
+ #[test]
1989
+ fn an_entry_refused_as_no_file_is_never_opened() {
1990
+ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
1991
+
1992
+ let host = make_fifo_host("fifo-never-opened");
1993
+ let dir = Dir::open_ambient_dir(&host.0, cap_std::ambient_authority())
1994
+ .expect("the host directory must open");
1995
+ // SAFETY: inotify_init1 answers a descriptor nothing else owns, or -1.
1996
+ let watch = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) };
1997
+ assert!(watch >= 0, "the host must give an inotify descriptor");
1998
+ // SAFETY: `watch` was just made and is owned here alone.
1999
+ let watch = unsafe { OwnedFd::from_raw_fd(watch) };
2000
+ let path = std::ffi::CString::new(host.0.as_os_str().as_encoded_bytes())
2001
+ .expect("the host path holds no NUL");
2002
+ // SAFETY: `path` is NUL-terminated and outlives the call.
2003
+ let added =
2004
+ unsafe { libc::inotify_add_watch(watch.as_raw_fd(), path.as_ptr(), libc::IN_OPEN) };
2005
+ assert!(added >= 0, "the host directory must be watched");
2006
+ let read = OpenHow {
2007
+ read: true,
2008
+ ..OpenHow::default()
2009
+ };
2010
+ let refused = open_in(&dir, "pipe", &read, false).err();
2011
+ let mut events = [0u8; 256];
2012
+ // SAFETY: `events` is writable for its whole length.
2013
+ let reported =
2014
+ unsafe { libc::read(watch.as_raw_fd(), events.as_mut_ptr().cast(), events.len()) };
2015
+ assert_eq!(
2016
+ (refused, reported),
2017
+ (Some(Errno::PermissionDenied), -1),
2018
+ "a FIFO a Bind is asked to open must be refused as permission denied with no open \
2019
+ of it reported to a watch on its host directory"
2020
+ );
2021
+ }
2022
+
1760
2023
  // @behavior FS-091
1761
2024
  #[cfg(unix)]
1762
2025
  #[test]
@@ -1818,7 +2081,7 @@ mod tests {
1818
2081
  .expect("the host file must open");
1819
2082
  let mut buf = [0; 16];
1820
2083
  let read = file
1821
- .read_iter(&mut Kiocb::at(0), &mut buf)
2084
+ .read_iter(&mut Kiocb::new(0), &mut buf)
1822
2085
  .expect("the host file must read");
1823
2086
  assert_eq!(
1824
2087
  &buf[..read],
@@ -1841,7 +2104,7 @@ mod tests {
1841
2104
  },
1842
2105
  )
1843
2106
  .expect("a new file must be created")
1844
- .write_iter(&mut Kiocb::at(0), b"written")
2107
+ .write_iter(&mut Kiocb::new(0), b"written")
1845
2108
  .expect("the write must land");
1846
2109
  assert_eq!(
1847
2110
  fs::read(host.0.join("out.txt")).expect("the host file must exist"),
@@ -1850,35 +2113,6 @@ mod tests {
1850
2113
  );
1851
2114
  }
1852
2115
 
1853
- // The file is opened to write, so only the refusal keeps the append
1854
- // from taking the two steps another writer could land between.
1855
- // @behavior FS-093
1856
- #[cfg(windows)]
1857
- #[test]
1858
- fn a_directory_on_windows_refuses_to_append() {
1859
- let host = HostDir::new("append");
1860
- fs::write(host.0.join("f"), "x").expect("the host file must be written");
1861
- let directory = bind_host(&host.0);
1862
- let mut file = directory
1863
- .open(
1864
- "f",
1865
- &OpenHow {
1866
- write: true,
1867
- ..OpenHow::default()
1868
- },
1869
- )
1870
- .expect("the host file must open");
1871
- assert_eq!(
1872
- (
1873
- file.write_iter(&mut Kiocb::at(0).with_append(), b"y").err(),
1874
- fs::read(host.0.join("f")).expect("the host file must read")
1875
- ),
1876
- (Some(FilesystemError::Unsupported), b"x".to_vec()),
1877
- "an append through a Bind file on Windows must be refused as unsupported and \
1878
- leave the file as it was"
1879
- );
1880
- }
1881
-
1882
2116
  // The host file exists beneath `d`, so only the refusal can keep the
1883
2117
  // open from reaching it.
1884
2118
  // @behavior FS-029
@@ -1892,48 +2126,13 @@ mod tests {
1892
2126
  assert!(
1893
2127
  matches!(
1894
2128
  directory.open(r"d\f", &OpenHow::default()),
1895
- Err(FilesystemError::InvalidInput)
2129
+ Err(Errno::InvalidInput)
1896
2130
  ),
1897
2131
  "a path holding a backslash opened through a Bind on Windows must be refused as \
1898
2132
  invalid input"
1899
2133
  );
1900
2134
  }
1901
2135
 
1902
- // Judged on every host, as only Windows's own CI reaches the refusal, and
1903
- // what the host would do with each name is what no other host can show.
1904
- // @behavior FS-153
1905
- #[test]
1906
- fn a_name_windows_reads_as_another_is_told_apart() {
1907
- let aliases = [
1908
- "secret.",
1909
- "secret ",
1910
- "file:stream",
1911
- r"d\f",
1912
- "con",
1913
- "NUL.txt",
1914
- "conin$",
1915
- "com1 .log",
1916
- "a?",
1917
- "a*",
1918
- "a<",
1919
- "a|",
1920
- "a\"",
1921
- "a\u{1}",
1922
- ];
1923
- let plain = ["secret", "file.txt", "console", "com10", ".hidden", "a.b.c"];
1924
- assert_eq!(
1925
- (
1926
- aliases
1927
- .iter()
1928
- .filter(|name| !is_windows_alias(name))
1929
- .count(),
1930
- plain.iter().filter(|name| is_windows_alias(name)).count(),
1931
- ),
1932
- (0, 0),
1933
- "is_windows_alias must name every spelling Windows reads as another, and no plain name"
1934
- );
1935
- }
1936
-
1937
2136
  // @behavior FS-153
1938
2137
  #[cfg(windows)]
1939
2138
  #[test]
@@ -1946,7 +2145,7 @@ mod tests {
1946
2145
  .iter()
1947
2146
  .all(|name| matches!(
1948
2147
  directory.open(name, &OpenHow::default()),
1949
- Err(FilesystemError::InvalidInput)
2148
+ Err(Errno::InvalidInput)
1950
2149
  )),
1951
2150
  "a name Windows reads as another, opened through a Bind on Windows, must be refused \
1952
2151
  as invalid input"
@@ -1969,7 +2168,7 @@ mod tests {
1969
2168
  );
1970
2169
  assert_eq!(
1971
2170
  created.map(drop),
1972
- Err(FilesystemError::InvalidFilename),
2171
+ Err(Errno::InvalidFilename),
1973
2172
  "a name past the host's limit created through Bind::open must fail as \
1974
2173
  InvalidFilename, not as an unnamed failure"
1975
2174
  );
@@ -1977,19 +2176,122 @@ mod tests {
1977
2176
 
1978
2177
  // Which offset a host refuses depends on its filesystem: tmpfs, XFS and
1979
2178
  // overlay keep files up to `i64::MAX`. The host's own EFBIG, 27 on Linux
1980
- // and macOS alike, is what the Bind must name.
2179
+ // and macOS alike and `ERROR_FILE_TOO_LARGE` on Windows, is what the Bind
2180
+ // must name.
1981
2181
  // @behavior FS-068
1982
- #[cfg(any(target_os = "linux", target_os = "macos"))]
1983
2182
  #[test]
1984
2183
  fn a_directory_answers_a_host_file_too_large_as_too_large() {
2184
+ let too_large = if cfg!(windows) { 223 } else { 27 };
1985
2185
  assert_eq!(
1986
- to_error(io::Error::from_raw_os_error(27)),
1987
- FilesystemError::FileTooLarge,
2186
+ to_error(io::Error::from_raw_os_error(too_large)),
2187
+ Errno::FileTooLarge,
1988
2188
  "a host EFBIG through Bind's error mapping must fail as FileTooLarge, \
1989
2189
  not as an unnamed failure"
1990
2190
  );
1991
2191
  }
1992
2192
 
2193
+ // A host out of descriptors cannot be staged without starving the test
2194
+ // process, so the host's own EMFILE, 24 on Linux and macOS alike, is what
2195
+ // the Bind must name.
2196
+ // @behavior FS-209
2197
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
2198
+ #[test]
2199
+ fn a_directory_answers_a_host_out_of_descriptors_as_too_many_open_files() {
2200
+ assert_eq!(
2201
+ to_error(io::Error::from_raw_os_error(24)),
2202
+ Errno::TooManyOpenFiles,
2203
+ "a host EMFILE through a Bind must fail as too many open files, as a host \
2204
+ socket's does, not as an unnamed failure"
2205
+ );
2206
+ }
2207
+
2208
+ // A host refusal Rust folds into another kind is staged by its errno, as
2209
+ // an unlink in another user's sticky directory needs a second user.
2210
+ // @behavior FS-210
2211
+ #[cfg(unix)]
2212
+ #[test]
2213
+ fn a_directory_answers_a_host_refusal_by_the_errno_it_holds() {
2214
+ use rustix::io::Errno as HostErrno;
2215
+ let answers = [
2216
+ HostErrno::PERM,
2217
+ HostErrno::LOOP,
2218
+ HostErrno::BADF,
2219
+ HostErrno::OVERFLOW,
2220
+ HostErrno::NODEV,
2221
+ HostErrno::STALE,
2222
+ HostErrno::ILSEQ,
2223
+ HostErrno::NOTSUP,
2224
+ HostErrno::OPNOTSUPP,
2225
+ ]
2226
+ .map(|errno| to_error(io::Error::from_raw_os_error(errno.raw_os_error())));
2227
+ assert_eq!(
2228
+ answers,
2229
+ [
2230
+ Errno::NotPermitted,
2231
+ Errno::FilesystemLoop,
2232
+ Errno::BadDescriptor,
2233
+ Errno::ValueTooLarge,
2234
+ Errno::NoSuchDevice,
2235
+ Errno::StaleNetworkFileHandle,
2236
+ Errno::IllegalSequence,
2237
+ Errno::Unsupported,
2238
+ Errno::Unsupported,
2239
+ ],
2240
+ "a host EPERM, ELOOP, EBADF, EOVERFLOW, ENODEV, ESTALE, EILSEQ, ENOTSUP, or \
2241
+ EOPNOTSUPP through a Bind must fail under that same name, as Linux answers it, \
2242
+ not as permission denied or an unnamed failure"
2243
+ );
2244
+ }
2245
+
2246
+ // A quota, a file's link count, and a running program cannot be staged
2247
+ // on every host, so the host's own errno stands for each.
2248
+ // @behavior FS-212
2249
+ #[cfg(unix)]
2250
+ #[test]
2251
+ fn a_directory_answers_a_host_out_of_quota_links_or_a_busy_program_by_name() {
2252
+ use rustix::io::Errno as HostErrno;
2253
+ let answers = [HostErrno::DQUOT, HostErrno::MLINK, HostErrno::TXTBSY]
2254
+ .map(|errno| to_error(io::Error::from_raw_os_error(errno.raw_os_error())));
2255
+ assert_eq!(
2256
+ answers,
2257
+ [
2258
+ Errno::QuotaExceeded,
2259
+ Errno::TooManyLinks,
2260
+ Errno::ExecutableFileBusy,
2261
+ ],
2262
+ "a host EDQUOT, EMLINK, or ETXTBSY through a Bind must fail under that same name, \
2263
+ as Linux answers it, not as an unnamed failure"
2264
+ );
2265
+ }
2266
+
2267
+ // Another process holding the file open is staged by its Win32 code.
2268
+ // @behavior FS-211
2269
+ #[cfg(windows)]
2270
+ #[test]
2271
+ fn a_directory_answers_a_host_file_held_without_sharing_as_permission_denied() {
2272
+ let held = windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION as i32;
2273
+ assert_eq!(
2274
+ to_error(io::Error::from_raw_os_error(held)),
2275
+ Errno::PermissionDenied,
2276
+ "a Windows host file another process holds without sharing must fail through a \
2277
+ Bind as permission denied, as wasmtime-wasi answers it, not as an unnamed failure"
2278
+ );
2279
+ }
2280
+
2281
+ // A host down reaches a Bind only on a network filesystem, so the host's
2282
+ // own EHOSTDOWN stands for it here.
2283
+ #[cfg(unix)]
2284
+ #[test]
2285
+ fn a_directory_answers_a_host_down_as_ehostdown() {
2286
+ let down = io::Error::from_raw_os_error(rustix::io::Errno::HOSTDOWN.raw_os_error());
2287
+ assert_eq!(
2288
+ to_error(down),
2289
+ Errno::HostDown,
2290
+ "a host EHOSTDOWN through a Bind must fail as EHOSTDOWN, as Linux hands a network \
2291
+ filesystem's failure on, not as the unreachable host a socket's WASI code reads"
2292
+ );
2293
+ }
2294
+
1993
2295
  // A Bind's root is the directory cap-std opened for its path alone on Linux,
1994
2296
  // so a sync of the descriptor it holds would answer EBADF only there.
1995
2297
  // @behavior FS-171
@@ -1998,10 +2300,8 @@ mod tests {
1998
2300
  let host = HostDir::new("sync-root");
1999
2301
  let mount = crate::mount::Mount::new(
2000
2302
  "/data",
2001
- Filesystem::new(Arc::new(
2002
- Bind::new(&host.0).expect("the host directory must open"),
2003
- ))
2004
- .expect("the instance must stand"),
2303
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2304
+ .expect("the instance must stand"),
2005
2305
  crate::mount::Access::Read,
2006
2306
  )
2007
2307
  .expect("/data is a guest path");
@@ -2024,7 +2324,7 @@ mod tests {
2024
2324
  let refused = io::Error::new(io::ErrorKind::PermissionDenied, "a path led outside");
2025
2325
  assert_eq!(
2026
2326
  to_error(refused),
2027
- FilesystemError::NotFound,
2327
+ Errno::NotFound,
2028
2328
  "cap-std's refusal of a single name leading out of a Bind's directory must answer \
2029
2329
  ENOENT, as a move carried it away"
2030
2330
  );
@@ -2033,7 +2333,6 @@ mod tests {
2033
2333
  // Eviction leaves a walk to reach a directory from one far above it, so only
2034
2334
  // a path past what the host takes in one call shows it goes on by name.
2035
2335
  // @behavior FS-190
2036
- #[cfg(unix)]
2037
2336
  #[test]
2038
2337
  fn a_directory_past_the_hosts_path_limit_is_reached() {
2039
2338
  let host = HostDir::new("past-path-max");
@@ -2075,10 +2374,8 @@ mod tests {
2075
2374
  let enforced = fs::read_dir(&dir).is_err();
2076
2375
  let mount = crate::mount::Mount::new(
2077
2376
  "/data",
2078
- Filesystem::new(Arc::new(
2079
- Bind::new(&host.0).expect("the host directory must open"),
2080
- ))
2081
- .expect("the instance must stand"),
2377
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2378
+ .expect("the instance must stand"),
2082
2379
  crate::mount::Access::Read,
2083
2380
  )
2084
2381
  .expect("/data is a guest path");
@@ -2093,7 +2390,7 @@ mod tests {
2093
2390
  if enforced {
2094
2391
  assert_eq!(
2095
2392
  answer,
2096
- Some(FilesystemError::PermissionDenied),
2393
+ Some(Errno::PermissionDenied),
2097
2394
  "vfs::do_file_open to read a host directory no one may read must answer EACCES"
2098
2395
  );
2099
2396
  }
@@ -2139,10 +2436,8 @@ mod tests {
2139
2436
  .expect("the host directory's mode must be set");
2140
2437
  let mount = crate::mount::Mount::new(
2141
2438
  "/data",
2142
- Filesystem::new(Arc::new(
2143
- Bind::new(&host.0).expect("the host directory must open"),
2144
- ))
2145
- .expect("the instance must stand"),
2439
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2440
+ .expect("the instance must stand"),
2146
2441
  crate::mount::Access::Read,
2147
2442
  )
2148
2443
  .expect("/data is a guest path");
@@ -2170,10 +2465,8 @@ mod tests {
2170
2465
  }
2171
2466
  let mount = crate::mount::Mount::new(
2172
2467
  "/data",
2173
- Filesystem::new(Arc::new(
2174
- Bind::new(&host.0).expect("the host directory must open"),
2175
- ))
2176
- .expect("the instance must stand"),
2468
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2469
+ .expect("the instance must stand"),
2177
2470
  crate::mount::Access::ReadWrite,
2178
2471
  )
2179
2472
  .expect("/data is a guest path");
@@ -2183,18 +2476,11 @@ mod tests {
2183
2476
  .expect("the host directory must list")
2184
2477
  .map(|entry| entry.expect("the entry must read").file_name())
2185
2478
  .collect();
2186
- // Windows reports no inode, so nothing ties `A` to the stored `a` and
2187
- // the spelling is refused rather than followed.
2188
- let answered = match cfg!(windows) {
2189
- true => Err(FilesystemError::PermissionDenied),
2190
- false => Ok(()),
2191
- };
2192
2479
  assert_eq!(
2193
2480
  (renamed, stored),
2194
- (answered, vec![std::ffi::OsString::from("a")]),
2195
- "vfs::filename_renameat2 of `a` to `A` on a Bind of a host that folds case must \
2196
- leave `a` spelled as it was, as vfs_rename finds one entry, refusing it only \
2197
- where the host ties no spelling to the entry"
2481
+ (Ok(()), vec![std::ffi::OsString::from("a")]),
2482
+ "a rename of `a` to `A` on a Bind of a host that folds case must succeed and leave \
2483
+ `a` spelled as it was, since both spellings name one entry"
2198
2484
  );
2199
2485
  }
2200
2486
 
@@ -2217,10 +2503,8 @@ mod tests {
2217
2503
  let enforced = fs::read_dir(host.0.join("searched")).is_err();
2218
2504
  let mount = crate::mount::Mount::new(
2219
2505
  "/data",
2220
- Filesystem::new(Arc::new(
2221
- Bind::new(&host.0).expect("the host directory must open"),
2222
- ))
2223
- .expect("the instance must stand"),
2506
+ Filesystem::new(Bind::new(&host.0).expect("the host directory must open"))
2507
+ .expect("the instance must stand"),
2224
2508
  crate::mount::Access::Read,
2225
2509
  )
2226
2510
  .expect("/data is a guest path");
@@ -2231,27 +2515,35 @@ mod tests {
2231
2515
  if enforced {
2232
2516
  assert_eq!(
2233
2517
  found.err(),
2234
- Some(FilesystemError::PermissionDenied),
2518
+ Some(Errno::PermissionDenied),
2235
2519
  "vfs::vfs_fstatat of a file beneath a host directory only searchable must \
2236
2520
  answer EACCES, as the Bind reads the directory to spell the name"
2237
2521
  );
2238
2522
  }
2239
2523
  }
2240
2524
 
2241
- // Only Linux keeps a name that is not UTF-8; macOS refuses to make one.
2525
+ // Linux keeps a name of any bytes and Windows one of a lone UTF-16
2526
+ // surrogate, which no UTF-8 spells; macOS refuses to make either.
2242
2527
  // @behavior FS-066
2243
- #[cfg(target_os = "linux")]
2528
+ #[cfg(not(target_os = "macos"))]
2244
2529
  #[test]
2245
2530
  fn a_directory_refuses_to_list_a_host_name_that_is_not_utf8() {
2246
- use std::os::unix::ffi::OsStrExt;
2247
-
2531
+ #[cfg(unix)]
2532
+ let name = {
2533
+ use std::os::unix::ffi::OsStrExt;
2534
+ std::ffi::OsStr::from_bytes(b"\xff").to_os_string()
2535
+ };
2536
+ #[cfg(windows)]
2537
+ let name = {
2538
+ use std::os::windows::ffi::OsStringExt;
2539
+ std::ffi::OsString::from_wide(&[0xD800])
2540
+ };
2248
2541
  let host = HostDir::new("ilseq");
2249
- fs::write(host.0.join(std::ffi::OsStr::from_bytes(b"\xff")), "")
2250
- .expect("the host file must be written");
2542
+ fs::write(host.0.join(name), "").expect("the host file must be written");
2251
2543
  let directory = bind_host(&host.0);
2252
2544
  assert_eq!(
2253
2545
  directory.iterate_dir().map(drop),
2254
- Err(FilesystemError::IllegalSequence),
2546
+ Err(Errno::IllegalSequence),
2255
2547
  "a host name that is not UTF-8 listed through iterate_dir must fail as \
2256
2548
  IllegalSequence, not as an unnamed failure"
2257
2549
  );
@@ -2260,14 +2552,16 @@ mod tests {
2260
2552
  // The host file only reads, so a host open asking to write, as one that
2261
2553
  // creates must, would be refused where nothing is to be created.
2262
2554
  // @behavior FS-064
2263
- #[cfg(unix)]
2264
2555
  #[test]
2265
2556
  fn a_directory_opens_a_file_already_there_without_writing_to_create_it() {
2266
- use std::os::unix::fs::PermissionsExt;
2267
2557
  let host = HostDir::new("create-existing");
2268
- fs::write(host.0.join("note"), "x").expect("the host file must be written");
2269
- fs::set_permissions(host.0.join("note"), fs::Permissions::from_mode(0o444))
2270
- .expect("the host file must become read-only");
2558
+ let note = host.0.join("note");
2559
+ fs::write(&note, "x").expect("the host file must be written");
2560
+ let mut read_only = fs::metadata(&note)
2561
+ .expect("the host file must stand")
2562
+ .permissions();
2563
+ read_only.set_readonly(true);
2564
+ fs::set_permissions(&note, read_only).expect("the host file must become read-only");
2271
2565
  let directory = bind_host(&host.0);
2272
2566
  let creates = OpenHow {
2273
2567
  read: true,
@@ -2288,12 +2582,11 @@ mod tests {
2288
2582
  // The link's target is a readable file, so only the refusal of the
2289
2583
  // link itself keeps the open from reaching it.
2290
2584
  // @behavior FS-047
2291
- #[cfg(unix)]
2292
2585
  #[test]
2293
2586
  fn a_directory_opens_no_link() {
2294
2587
  let host = HostDir::new("nofollow");
2295
2588
  fs::write(host.0.join("target"), "x").expect("the host file must be written");
2296
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2589
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2297
2590
  let opened = bind_host(&host.0)
2298
2591
  .open(
2299
2592
  "link",
@@ -2305,7 +2598,7 @@ mod tests {
2305
2598
  .map(drop);
2306
2599
  assert_eq!(
2307
2600
  opened,
2308
- Err(FilesystemError::FilesystemLoop),
2601
+ Err(Errno::FilesystemLoop),
2309
2602
  "a host link opened through a Bind must be refused as a link, its target unreached"
2310
2603
  );
2311
2604
  }
@@ -2313,12 +2606,11 @@ mod tests {
2313
2606
  // The VFS refuses a link it found before asking the Bind, so only the
2314
2607
  // Bind's own open sees a link the host put in place after the lookup.
2315
2608
  // @behavior FS-047
2316
- #[cfg(unix)]
2317
2609
  #[test]
2318
2610
  fn a_directory_refuses_a_link_put_in_place_of_what_it_opens() {
2319
2611
  let host = HostDir::new("nofollow-swapped");
2320
2612
  fs::write(host.0.join("target"), "x").expect("the host file must be written");
2321
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2613
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2322
2614
  let dir = Dir::open_ambient_dir(&host.0, ambient_authority()).expect("the host directory");
2323
2615
  let read = OpenHow {
2324
2616
  read: true,
@@ -2326,7 +2618,7 @@ mod tests {
2326
2618
  };
2327
2619
  assert_eq!(
2328
2620
  open_in(&dir, "link", &read, false).map(drop),
2329
- Err(FilesystemError::FilesystemLoop),
2621
+ Err(Errno::FilesystemLoop),
2330
2622
  "a host link standing where a Bind opens a file must be refused as a link, its \
2331
2623
  target unreached"
2332
2624
  );
@@ -2335,12 +2627,11 @@ mod tests {
2335
2627
  // The target's five bytes would show as the link's size if a lookup
2336
2628
  // that follows none still followed it.
2337
2629
  // @behavior FS-048
2338
- #[cfg(unix)]
2339
2630
  #[test]
2340
2631
  fn a_directory_reports_a_link_a_lookup_does_not_follow_as_a_link() {
2341
2632
  let host = HostDir::new("lstat");
2342
2633
  fs::write(host.0.join("target"), "hello").expect("the host file must be written");
2343
- std::os::unix::fs::symlink("target", host.0.join("link")).expect("the link must be made");
2634
+ crate::filesystem::testing::symlink("target", host.0.join("link"));
2344
2635
  let directory = bind_host(&host.0);
2345
2636
  let listed = directory
2346
2637
  .iterate_dir()
@@ -2386,29 +2677,26 @@ mod tests {
2386
2677
  let directory = bind_host(&host.0);
2387
2678
  assert_eq!(
2388
2679
  directory.vfs_unlink("sub"),
2389
- Err(FilesystemError::IsADirectory),
2680
+ Err(Errno::IsADirectory),
2390
2681
  "a host directory beneath a Bind removed through vfs_unlink must answer EISDIR"
2391
2682
  );
2392
2683
  }
2393
2684
 
2394
2685
  /// A host directory holding `dir/sub/y` and `secret`, with `dir/in`
2395
2686
  /// linking to `sub` and `dir/up` to `../secret`.
2396
- #[cfg(unix)]
2397
2687
  fn make_links(name: &str) -> HostDir {
2398
2688
  let host = HostDir::new(name);
2399
2689
  fs::create_dir_all(host.0.join("dir/sub")).expect("the host directory must be created");
2400
2690
  fs::write(host.0.join("dir/sub/y"), "inner").expect("the inner file must be written");
2401
2691
  fs::write(host.0.join("secret"), "outer").expect("the outer file must be written");
2402
- std::os::unix::fs::symlink("sub", host.0.join("dir/in")).expect("the link must be made");
2403
- std::os::unix::fs::symlink("../secret", host.0.join("dir/up"))
2404
- .expect("the link must be made");
2692
+ crate::filesystem::testing::symlink("sub", host.0.join("dir/in"));
2693
+ crate::filesystem::testing::symlink("../secret", host.0.join("dir/up"));
2405
2694
  host
2406
2695
  }
2407
2696
 
2408
2697
  // The link leads to a directory inside the host directory, so only
2409
2698
  // refusing the link itself keeps it from being opened.
2410
2699
  // @behavior FS-099
2411
- #[cfg(unix)]
2412
2700
  #[test]
2413
2701
  fn a_directory_opens_no_link_as_a_directory_where_asked_not_to_follow() {
2414
2702
  let host = make_links("open-dir-nofollow");
@@ -2416,13 +2704,12 @@ mod tests {
2416
2704
  let dir = directory.open_dir("dir").expect("the directory must open");
2417
2705
  assert_eq!(
2418
2706
  dir.open_dir("in").map(drop),
2419
- Err(FilesystemError::FilesystemLoop),
2707
+ Err(Errno::FilesystemLoop),
2420
2708
  "a link to a directory opened through Bind::open_dir must be a link loop"
2421
2709
  );
2422
2710
  }
2423
2711
 
2424
2712
  // @behavior FS-114
2425
- #[cfg(unix)]
2426
2713
  #[test]
2427
2714
  fn a_directory_reads_where_a_link_points() {
2428
2715
  let host = make_links("read-link");
@@ -2430,24 +2717,82 @@ mod tests {
2430
2717
  let dir = directory.open_dir("dir").expect("the directory must open");
2431
2718
  assert_eq!(
2432
2719
  (dir.vfs_readlink("up"), dir.vfs_readlink("sub")),
2433
- (
2434
- Ok("../secret".to_string()),
2435
- Err(FilesystemError::InvalidInput)
2436
- ),
2720
+ (Ok("../secret".to_string()), Err(Errno::InvalidInput)),
2437
2721
  "vfs_readlink beneath a Bind must answer where a link points as stored, and refuse \
2438
2722
  a directory with EINVAL"
2439
2723
  );
2440
2724
  }
2441
2725
 
2726
+ // Windows removes a link to a directory only as a directory, so a file's
2727
+ // removal alone would leave it standing there.
2728
+ // @behavior FS-240
2729
+ #[test]
2730
+ fn a_directory_removes_a_link_to_a_directory_as_itself() {
2731
+ let host = make_links("unlink-dir-link");
2732
+ let directory = bind_host(&host.0);
2733
+ let dir = directory.open_dir("dir").expect("the directory must open");
2734
+ assert_eq!(
2735
+ (
2736
+ dir.vfs_unlink("in"),
2737
+ host.0.join("dir/in").symlink_metadata().is_err(),
2738
+ host.0.join("dir/sub/y").is_file()
2739
+ ),
2740
+ (Ok(()), true, true),
2741
+ "vfs_unlink of a link to a directory beneath a Bind must remove the link and leave \
2742
+ the directory it leads to and what that holds"
2743
+ );
2744
+ }
2745
+
2746
+ // A link to a directory is no directory, so rename(2) replaces it as it
2747
+ // would a file; a host taking it for its target would refuse the move.
2748
+ // @behavior FS-241
2749
+ #[test]
2750
+ fn a_directory_moves_a_file_onto_a_link_to_a_directory() {
2751
+ let host = make_links("rename-onto-dir-link");
2752
+ fs::write(host.0.join("dir/f"), "moved").expect("the host file must be written");
2753
+ let directory = bind_host(&host.0);
2754
+ let dir = directory.open_dir("dir").expect("the directory must open");
2755
+ assert_eq!(
2756
+ (
2757
+ dir.rename("f", &dir, "in"),
2758
+ fs::read_to_string(host.0.join("dir/in")).ok(),
2759
+ host.0.join("dir/sub/y").is_file()
2760
+ ),
2761
+ (Ok(()), Some("moved".to_string()), true),
2762
+ "a rename beneath a Bind of a file onto a link to a directory must put the file \
2763
+ in the link's place and leave the directory it led to"
2764
+ );
2765
+ }
2766
+
2767
+ // Windows stores each link's target with `\`, so only the Bind's reading
2768
+ // spells it as a guest path.
2769
+ // @behavior FS-239
2770
+ #[cfg(windows)]
2771
+ #[test]
2772
+ fn a_directory_reads_a_windows_link_as_a_guest_path() {
2773
+ let host = make_links("read-windows-link");
2774
+ crate::filesystem::testing::symlink(host.0.join("secret"), host.0.join("dir/far"));
2775
+ let directory = bind_host(&host.0);
2776
+ let dir = directory.open_dir("dir").expect("the directory must open");
2777
+ let far = dir.vfs_readlink("far").expect("the link must read");
2778
+ assert_eq!(
2779
+ (
2780
+ dir.vfs_readlink("up"),
2781
+ far.starts_with('/') && !far.contains('\\') && far.ends_with("/secret")
2782
+ ),
2783
+ (Ok("../secret".to_string()), true),
2784
+ "vfs_readlink of a Windows host link beneath a Bind must read `..\\secret` as \
2785
+ `../secret`, and a target on a drive as a path from `/`, not `{far}`"
2786
+ );
2787
+ }
2788
+
2442
2789
  // @behavior FS-007
2443
- #[cfg(unix)]
2444
2790
  #[test]
2445
2791
  fn a_directory_reaches_nothing_outside_its_host_directory() {
2446
2792
  let outside = HostDir::new("outside");
2447
2793
  fs::write(outside.0.join("secret"), "host").expect("the outside file must be written");
2448
2794
  let host = HostDir::new("confined");
2449
- std::os::unix::fs::symlink(outside.0.join("secret"), host.0.join("escape"))
2450
- .expect("the link must be created");
2795
+ crate::filesystem::testing::symlink(outside.0.join("secret"), host.0.join("escape"));
2451
2796
 
2452
2797
  let directory = bind_host(&host.0);
2453
2798
  assert!(
@@ -2464,22 +2809,44 @@ mod tests {
2464
2809
  );
2465
2810
  }
2466
2811
 
2467
- // @behavior FS-071
2812
+ /// The device and inode numbers the host gives `path`.
2468
2813
  #[cfg(unix)]
2469
- #[test]
2470
- fn a_directory_reports_the_identity_its_host_gives_a_path() {
2814
+ fn host_identity(path: &Path) -> (u64, u64) {
2471
2815
  use std::os::unix::fs::MetadataExt;
2816
+ let found = fs::metadata(path).expect("the host must stat it");
2817
+ (found.dev(), found.ino())
2818
+ }
2819
+
2820
+ /// The volume serial number and file index the host gives `path`, which
2821
+ /// Windows names only on a handle opened to it; std reads them on nightly
2822
+ /// alone.
2823
+ #[cfg(windows)]
2824
+ fn host_identity(path: &Path) -> (u64, u64) {
2825
+ use cap_fs_ext::MetadataExt;
2826
+ let parent = cap_std::fs::Dir::open_ambient_dir(
2827
+ path.parent().expect("the path has a parent"),
2828
+ cap_std::ambient_authority(),
2829
+ )
2830
+ .expect("the host directory must open");
2831
+ let found = parent
2832
+ .metadata(path.file_name().expect("the path names an entry"))
2833
+ .expect("the host must stat it");
2834
+ (found.dev(), found.ino())
2835
+ }
2472
2836
 
2837
+ // @behavior FS-071
2838
+ #[test]
2839
+ fn a_directory_reports_the_identity_its_host_gives_a_path() {
2473
2840
  let host = HostDir::new("identity");
2474
2841
  fs::create_dir(host.0.join("dir")).expect("the host directory must be made");
2475
- let expected = fs::metadata(host.0.join("dir")).expect("the host must stat it");
2842
+ let expected = host_identity(&host.0.join("dir"));
2476
2843
  let directory = bind_host(&host.0);
2477
2844
  let reported = directory
2478
2845
  .vfs_lstat("dir")
2479
2846
  .expect("the directory must stand");
2480
2847
  assert_eq!(
2481
2848
  (reported.dev, reported.ino),
2482
- (expected.dev(), expected.ino()),
2849
+ expected,
2483
2850
  "a host directory beneath a Bind looked up through vfs_lstat must carry the device \
2484
2851
  and inode numbers the host reports"
2485
2852
  );
@@ -2489,7 +2856,6 @@ mod tests {
2489
2856
  // length, then write there) loses about half the bytes to the other
2490
2857
  // handle's writes, so only an append the host places keeps them all.
2491
2858
  // @behavior FS-069
2492
- #[cfg(unix)]
2493
2859
  #[test]
2494
2860
  fn a_directory_appends_at_its_host_files_end_in_one_step() {
2495
2861
  let host = HostDir::new("append");
@@ -2509,7 +2875,7 @@ mod tests {
2509
2875
  .open("log.txt", &how)
2510
2876
  .expect("the host file must open to write");
2511
2877
  for _ in 0..10_000 {
2512
- file.write_iter(&mut Kiocb::at(0).with_append(), byte)
2878
+ file.write_iter(&mut Kiocb::new(0).with_append(), byte)
2513
2879
  .expect("the append must succeed");
2514
2880
  }
2515
2881
  })
@@ -2526,8 +2892,7 @@ mod tests {
2526
2892
  written.iter().filter(|&&b| b == b'b').count()
2527
2893
  ),
2528
2894
  (10_000, 10_000),
2529
- "two handles appending to one host file through a Bind's FileOperations::write_iter must each \
2530
- keep every byte"
2895
+ "two handles appending to one host file through a Bind must each keep every byte"
2531
2896
  );
2532
2897
  }
2533
2898