kobako 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +552 -10
  4. data/Cargo.lock +595 -139
  5. data/README.md +126 -564
  6. data/ROADMAP.md +3 -2
  7. data/crates/kobako-runtime/CHANGELOG.md +488 -1
  8. data/crates/kobako-runtime/Cargo.toml +73 -15
  9. data/crates/kobako-runtime/README.md +11 -4
  10. data/crates/kobako-runtime/src/cred.rs +124 -0
  11. data/crates/kobako-runtime/src/dispatch.rs +5 -6
  12. data/crates/kobako-runtime/src/endpoint/buffer.rs +301 -0
  13. data/crates/kobako-runtime/src/endpoint/dispatch.rs +292 -0
  14. data/crates/kobako-runtime/src/endpoint/invoke.rs +181 -0
  15. data/crates/kobako-runtime/src/endpoint.rs +267 -0
  16. data/crates/kobako-runtime/src/errno.rs +391 -0
  17. data/crates/kobako-runtime/src/error.rs +31 -10
  18. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  19. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +82 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +274 -0
  21. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +248 -0
  22. data/crates/kobako-runtime/src/filesystem/bind.rs +2857 -0
  23. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +89 -0
  24. data/crates/kobako-runtime/src/filesystem/overlay/inode.rs +106 -0
  25. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +263 -0
  26. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +128 -0
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +238 -0
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +135 -0
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +54 -0
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +316 -739
  31. data/crates/kobako-runtime/src/filesystem/overlay.rs +2627 -1154
  32. data/crates/kobako-runtime/src/filesystem/pipe.rs +224 -0
  33. data/crates/kobako-runtime/src/filesystem/rdir.rs +84 -0
  34. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  35. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +32 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +107 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +22 -0
  38. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +1997 -0
  39. data/crates/kobako-runtime/src/filesystem/wrap.rs +208 -0
  40. data/crates/kobako-runtime/src/filesystem.rs +25 -388
  41. data/crates/kobako-runtime/src/fork.rs +96 -0
  42. data/crates/kobako-runtime/src/grant.rs +3 -0
  43. data/crates/kobako-runtime/src/hashtable.rs +46 -0
  44. data/crates/kobako-runtime/src/lib.rs +27 -11
  45. data/crates/kobako-runtime/src/limits.rs +195 -0
  46. data/crates/kobako-runtime/src/locking/seqlock.rs +66 -0
  47. data/crates/kobako-runtime/src/locking.rs +228 -0
  48. data/crates/kobako-runtime/src/memcg.rs +383 -0
  49. data/crates/kobako-runtime/src/mount.rs +86 -101
  50. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  51. data/crates/kobako-runtime/src/net/connections.rs +179 -0
  52. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  53. data/crates/kobako-runtime/src/net/egress.rs +160 -0
  54. data/crates/kobako-runtime/src/net/family.rs +181 -0
  55. data/crates/kobako-runtime/src/net/http.rs +2733 -0
  56. data/crates/kobako-runtime/src/net/lookup.rs +285 -0
  57. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  58. data/crates/kobako-runtime/src/net/namespace.rs +1366 -0
  59. data/crates/kobako-runtime/src/net/reactor.rs +531 -0
  60. data/crates/kobako-runtime/src/net/resolv/darwin.rs +275 -0
  61. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +469 -0
  62. data/crates/kobako-runtime/src/net/resolv/stub.rs +536 -0
  63. data/crates/kobako-runtime/src/net/resolv/windows.rs +248 -0
  64. data/crates/kobako-runtime/src/net/resolv.rs +227 -0
  65. data/crates/kobako-runtime/src/net/socket.rs +870 -0
  66. data/crates/kobako-runtime/src/net/tcp.rs +1588 -0
  67. data/crates/kobako-runtime/src/net/tls.rs +58 -0
  68. data/crates/kobako-runtime/src/net/transport.rs +279 -0
  69. data/crates/kobako-runtime/src/net/udp.rs +1003 -0
  70. data/crates/kobako-runtime/src/net.rs +42 -0
  71. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  72. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  73. data/crates/kobako-runtime/src/network.rs +551 -0
  74. data/crates/kobako-runtime/src/policy.rs +16 -0
  75. data/crates/kobako-runtime/src/profile.rs +37 -16
  76. data/crates/kobako-runtime/src/runtime.rs +3 -5
  77. data/crates/kobako-runtime/src/sched.rs +311 -0
  78. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  79. data/crates/kobako-runtime/src/security/hooks.rs +242 -0
  80. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  81. data/crates/kobako-runtime/src/security.rs +601 -0
  82. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  83. data/crates/kobako-runtime/src/vfs/attr.rs +162 -0
  84. data/crates/kobako-runtime/src/vfs/dentry.rs +1466 -0
  85. data/crates/kobako-runtime/src/vfs/file.rs +1911 -0
  86. data/crates/kobako-runtime/src/vfs/inode.rs +425 -0
  87. data/crates/kobako-runtime/src/vfs/kern_path.rs +213 -0
  88. data/crates/kobako-runtime/src/vfs/mount.rs +60 -0
  89. data/crates/kobako-runtime/src/vfs/namei.rs +5837 -0
  90. data/crates/kobako-runtime/src/vfs/namespace.rs +162 -0
  91. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  92. data/crates/kobako-runtime/src/vfs/openat2.rs +116 -0
  93. data/crates/kobako-runtime/src/vfs/path.rs +64 -0
  94. data/crates/kobako-runtime/src/vfs/readdir.rs +163 -0
  95. data/crates/kobako-runtime/src/vfs/stat.rs +293 -0
  96. data/crates/kobako-runtime/src/vfs/super_block.rs +126 -0
  97. data/crates/kobako-runtime/src/vfs/utimes.rs +299 -0
  98. data/crates/kobako-runtime/src/vfs.rs +63 -0
  99. data/crates/kobako-runtime/src/wait.rs +356 -0
  100. data/crates/kobako-transport/CHANGELOG.md +39 -2
  101. data/crates/kobako-transport/Cargo.toml +3 -3
  102. data/crates/kobako-transport/README.md +8 -8
  103. data/crates/kobako-transport/src/abi.rs +78 -72
  104. data/crates/kobako-transport/src/envelope/bytes.rs +49 -30
  105. data/crates/kobako-transport/src/envelope/call.rs +37 -9
  106. data/crates/kobako-transport/src/envelope/compile_reply.rs +2 -2
  107. data/crates/kobako-transport/src/envelope/error_record.rs +24 -3
  108. data/crates/kobako-transport/src/envelope/fault.rs +2 -2
  109. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  110. data/crates/kobako-transport/src/envelope/outcome.rs +11 -11
  111. data/crates/kobako-transport/src/envelope/preamble.rs +34 -31
  112. data/crates/kobako-transport/src/envelope/reply.rs +29 -29
  113. data/crates/kobako-transport/src/envelope/request.rs +2 -2
  114. data/crates/kobako-transport/src/envelope/run.rs +1 -1
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +12 -12
  116. data/crates/kobako-transport/src/envelope.rs +15 -10
  117. data/crates/kobako-wasmtime/CHANGELOG.md +315 -8
  118. data/crates/kobako-wasmtime/Cargo.toml +35 -15
  119. data/crates/kobako-wasmtime/README.md +11 -6
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +19 -47
  123. data/crates/kobako-wasmtime/src/ambient.rs +33 -19
  124. data/crates/kobako-wasmtime/src/cache.rs +28 -20
  125. data/crates/kobako-wasmtime/src/config.rs +59 -60
  126. data/crates/kobako-wasmtime/src/driver.rs +63 -145
  127. data/crates/kobako-wasmtime/src/exports.rs +147 -32
  128. data/crates/kobako-wasmtime/src/guest.rs +44 -0
  129. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  130. data/crates/kobako-wasmtime/src/imports.rs +48 -18
  131. data/crates/kobako-wasmtime/src/instance_pre.rs +7 -7
  132. data/crates/kobako-wasmtime/src/invocation.rs +93 -51
  133. data/crates/kobako-wasmtime/src/lib.rs +6 -7
  134. data/crates/kobako-wasmtime/src/limiter.rs +52 -211
  135. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +309 -0
  136. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +70 -57
  137. data/crates/kobako-wasmtime/src/preview1/differential.rs +137 -27
  138. data/crates/kobako-wasmtime/src/preview1/errno.rs +90 -233
  139. data/crates/kobako-wasmtime/src/preview1/fd.rs +1301 -522
  140. data/crates/kobako-wasmtime/src/preview1/memory.rs +126 -150
  141. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +192 -0
  142. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +1989 -708
  143. data/crates/kobako-wasmtime/src/preview1/path.rs +181 -365
  144. data/crates/kobako-wasmtime/src/preview1/poll.rs +345 -173
  145. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -25
  146. data/crates/kobako-wasmtime/src/preview1/testsuite-expected.txt +6 -0
  147. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +147 -0
  148. data/crates/kobako-wasmtime/src/preview1.rs +471 -416
  149. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  150. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  151. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  152. data/crates/kobako-wasmtime/src/preview2/host.rs +3959 -0
  153. data/crates/kobako-wasmtime/src/preview2/http.rs +1503 -0
  154. data/crates/kobako-wasmtime/src/preview2/io.rs +315 -0
  155. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  156. data/crates/kobako-wasmtime/src/preview2/table.rs +305 -0
  157. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  158. data/crates/kobako-wasmtime/src/trap.rs +31 -16
  159. data/crates/kobako-wasmtime/src/wasi.rs +238 -93
  160. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  161. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  162. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  163. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  164. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  165. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  166. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  167. data/crates/kobako-wasmtime/witx/typenames.witx +750 -0
  168. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +441 -0
  169. data/data/kobako.wasm +0 -0
  170. data/ext/kobako/Cargo.toml +1 -1
  171. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +35 -27
  172. data/ext/kobako/src/escape.rs +98 -0
  173. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +36 -16
  174. data/ext/kobako/src/filesystem/ruby.rs +689 -0
  175. data/ext/kobako/src/filesystem.rs +217 -0
  176. data/ext/kobako/src/gvl.rs +306 -0
  177. data/ext/kobako/src/lib.rs +64 -3
  178. data/ext/kobako/src/network/mock.rs +187 -0
  179. data/ext/kobako/src/network.rs +591 -0
  180. data/ext/kobako/src/runtime/bridge.rs +31 -30
  181. data/ext/kobako/src/runtime/snapshot.rs +5 -5
  182. data/ext/kobako/src/runtime.rs +221 -138
  183. data/ext/kobako/src/wire.rs +42 -0
  184. data/lib/kobako/catalog/extensions.rb +19 -7
  185. data/lib/kobako/catalog/flags.rb +4 -6
  186. data/lib/kobako/catalog/grants.rb +5 -4
  187. data/lib/kobako/catalog/handles.rb +9 -31
  188. data/lib/kobako/catalog/mount.rb +12 -12
  189. data/lib/kobako/catalog/network.rb +35 -0
  190. data/lib/kobako/catalog/replacements.rb +28 -0
  191. data/lib/kobako/catalog/services.rb +7 -21
  192. data/lib/kobako/catalog/snippets.rb +10 -25
  193. data/lib/kobako/catalog.rb +4 -1
  194. data/lib/kobako/codec/{utils.rb → boundary.rb} +5 -3
  195. data/lib/kobako/codec/decoder.rb +12 -12
  196. data/lib/kobako/codec/ext_types.rb +5 -7
  197. data/lib/kobako/codec/handle_walk.rb +5 -47
  198. data/lib/kobako/codec/nesting.rb +7 -7
  199. data/lib/kobako/codec/value_budget.rb +134 -42
  200. data/lib/kobako/codec.rb +1 -1
  201. data/lib/kobako/context.rb +28 -15
  202. data/lib/kobako/errors.rb +15 -12
  203. data/lib/kobako/extension.rb +3 -2
  204. data/lib/kobako/filesystem.rb +53 -15
  205. data/lib/kobako/handle.rb +2 -2
  206. data/lib/kobako/names.rb +28 -0
  207. data/lib/kobako/network.rb +210 -0
  208. data/lib/kobako/outcome.rb +7 -7
  209. data/lib/kobako/payload/arguments.rb +2 -2
  210. data/lib/kobako/pool.rb +47 -25
  211. data/lib/kobako/runtime.rb +3 -2
  212. data/lib/kobako/sandbox.rb +113 -56
  213. data/lib/kobako/sandbox_options.rb +41 -107
  214. data/lib/kobako/snippet/bytecode.rb +1 -1
  215. data/lib/kobako/snippet/source.rb +1 -1
  216. data/lib/kobako/transport/argument_wrap.rb +64 -0
  217. data/lib/kobako/transport/block_failure.rb +1 -1
  218. data/lib/kobako/transport/dispatcher.rb +10 -10
  219. data/lib/kobako/transport/exposure.rb +28 -17
  220. data/lib/kobako/transport/reflection.rb +28 -11
  221. data/lib/kobako/transport/run.rb +13 -28
  222. data/lib/kobako/transport/yielder.rb +3 -10
  223. data/lib/kobako/transport.rb +1 -0
  224. data/lib/kobako/version.rb +1 -1
  225. data/lib/kobako.rb +38 -0
  226. data/release-please-config.json +16 -0
  227. data/sig/core/thread.rbs +6 -0
  228. data/sig/kobako/catalog/extensions.rbs +5 -3
  229. data/sig/kobako/catalog/grants.rbs +7 -4
  230. data/sig/kobako/catalog/handles.rbs +2 -4
  231. data/sig/kobako/catalog/mount.rbs +3 -5
  232. data/sig/kobako/catalog/network.rbs +20 -0
  233. data/sig/kobako/catalog/replacements.rbs +14 -0
  234. data/sig/kobako/catalog/services.rbs +1 -5
  235. data/sig/kobako/catalog/snippets.rbs +3 -5
  236. data/sig/kobako/catalog.rbs +1 -1
  237. data/sig/kobako/codec/boundary.rbs +9 -0
  238. data/sig/kobako/codec/decoder.rbs +1 -1
  239. data/sig/kobako/codec/handle_walk.rbs +0 -6
  240. data/sig/kobako/codec/nesting.rbs +2 -2
  241. data/sig/kobako/codec/value_budget.rbs +48 -5
  242. data/sig/kobako/codec.rbs +1 -2
  243. data/sig/kobako/context.rbs +4 -2
  244. data/sig/kobako/errors.rbs +4 -4
  245. data/sig/kobako/filesystem.rbs +38 -15
  246. data/sig/kobako/guest_yielder.rbs +1 -1
  247. data/sig/kobako/network.rbs +115 -0
  248. data/sig/kobako/outcome.rbs +1 -1
  249. data/sig/kobako/payload/arguments.rbs +1 -1
  250. data/sig/kobako/pool.rbs +8 -4
  251. data/sig/kobako/runtime.rbs +32 -3
  252. data/sig/kobako/sandbox.rbs +22 -7
  253. data/sig/kobako/sandbox_options.rbs +29 -38
  254. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  255. data/sig/kobako/transport/dispatcher.rbs +2 -2
  256. data/sig/kobako/transport/error.rbs +1 -1
  257. data/sig/kobako/transport/exposure.rbs +3 -5
  258. data/sig/kobako/transport/reflection.rbs +12 -2
  259. data/sig/kobako/transport/run.rbs +3 -5
  260. data/sig/kobako/transport/yielder.rbs +0 -3
  261. data/sig/kobako/transport.rbs +2 -2
  262. data/sig/kobako.rbs +13 -0
  263. metadata +131 -34
  264. data/crates/kobako-runtime/src/filesystem/directory/spelling.rs +0 -194
  265. data/crates/kobako-runtime/src/filesystem/directory.rs +0 -1082
  266. data/crates/kobako-runtime/src/filesystem/memory.rs +0 -1100
  267. data/crates/kobako-runtime/src/filesystem/overlay/exclusive.rs +0 -88
  268. data/crates/kobako-runtime/src/filesystem/path.rs +0 -60
  269. data/crates/kobako-runtime/src/filesystem/temporary.rs +0 -167
  270. data/crates/kobako-wasmtime/src/capture.rs +0 -96
  271. data/crates/kobako-wasmtime/src/descriptors.rs +0 -167
  272. data/crates/kobako-wasmtime/src/dispatch.rs +0 -125
  273. data/crates/kobako-wasmtime/src/guest_mem.rs +0 -271
  274. data/crates/kobako-wasmtime/src/io.rs +0 -89
  275. data/crates/kobako-wasmtime/src/preview1/args.rs +0 -60
  276. data/crates/kobako-wasmtime/src/preview1/beneath.rs +0 -188
  277. data/crates/kobako-wasmtime/tests/compile_posture.rs +0 -43
  278. data/crates/kobako-wasmtime/tests/guest_file.rs +0 -1054
  279. data/crates/kobako-wasmtime/tests/preamble_flags.rs +0 -70
  280. data/crates/kobako-wasmtime/tests/snippet_compile.rs +0 -95
  281. data/crates/kobako-wasmtime/tests/support/mod.rs +0 -30
  282. data/crates/kobako-wasmtime/tests/unanswered_call.rs +0 -86
  283. data/crates/kobako-wasmtime/tests/unsupported_call.rs +0 -51
  284. data/ext/kobako/src/runtime/escape.rs +0 -53
  285. data/ext/kobako/src/runtime/filesystem/ruby.rs +0 -400
  286. data/ext/kobako/src/runtime/filesystem.rs +0 -236
  287. data/ext/kobako/src/runtime/gvl.rs +0 -112
  288. data/lib/kobako/constant_name.rb +0 -8
  289. data/sig/kobako/codec/utils.rbs +0 -9
  290. data/sig/kobako/constant_name.rbs +0 -3
  291. /data/ext/kobako/src/{runtime/pinned_value.rs → pinned_value.rs} +0 -0
@@ -1,146 +1,402 @@
1
- //! `Overlay`: Layers stacked into one Filesystem, each read-only or
2
- //! writable on its own.
1
+ //! `Overlay`: read-only lower Layers under an upper Tmpfs, stacked into
2
+ //! one Filesystem, as Linux overlayfs stacks a mount's layers.
3
3
  //!
4
- //! The rules follow the union filesystems that allow writable Layers
5
- //! below the top, aufs among them. A removal hides what a read-only Layer
6
- //! still shows with a whiteout, and a directory made again where one was
7
- //! removed is marked opaque. Both markers take the OCI image layer
8
- //! format's names and live in the topmost writable Layer, so they last as
9
- //! long as it does. Every call holds the Overlay's lock, so a change
10
- //! across several Layers is never seen half made.
11
-
12
- mod exclusive;
4
+ //! The upper must be a Tmpfs, as gVisor takes only an upper that holds
5
+ //! its marks. A removal hides what a lower Layer still shows with a
6
+ //! whiteout, and a directory made again where one was removed is marked
7
+ //! opaque, each as Linux marks it, in the upper, so they last as long as
8
+ //! it does. The VFS holds each directory a call changes, as Linux's
9
+ //! `i_rwsem` does above overlayfs, and a copy up holds the lock of what
10
+ //! it copies, so a change across several Layers is never seen half made.
11
+
12
+ mod file;
13
+ mod inode;
14
+ mod path;
13
15
  mod stack;
14
16
 
17
+ use std::any::Any;
15
18
  use std::sync::Arc;
16
19
 
17
- pub use exclusive::Blocking;
18
-
20
+ use super::rdir::Rdir;
19
21
  use super::{
20
- Access, DirEntry, File, Filesystem, FilesystemError, Hold, Metadata, OpenOptions, Rename,
22
+ DentryOperations, Errno, FileOperations, FileSystemType, FileType, Filesystem, Iattr,
23
+ InodeOperations, Kstat, Lookup, OpenHow, RenameFlag, Tmpfs,
21
24
  };
22
- use exclusive::{Exclusive, Inline};
23
- use stack::Stack;
24
-
25
- /// Layers stacked into one Filesystem, the first one added on top. Its
26
- /// clones share its lock; two Overlays sharing a writable Layer are not
27
- /// serialized against each other, as overlayfs leaves two mounts sharing
28
- /// an upper directory undefined.
25
+ use crate::vfs::{
26
+ generic_file_llseek, generic_read_dir, notify_change, Dentry, DirContext, Inode, Whence,
27
+ NAME_MAX,
28
+ };
29
+ use inode::{OverlayDirInode, OverlayFileInode};
30
+ use path::OverlayPath;
31
+ use stack::OverlayFs;
32
+
33
+ /// Read-only lower Layers under an upper Tmpfs, stacked into one
34
+ /// Filesystem. Two Overlays sharing an upper are not serialized against
35
+ /// each other, as overlayfs leaves two mounts sharing an upper directory
36
+ /// undefined.
37
+ ///
38
+ /// Each directory of the view keeps each Layer's directory it stands for
39
+ /// on its dentry, so it is reached wherever those directories move, as a
40
+ /// descriptor reaches its directory, and a directory opened beneath it is
41
+ /// this Overlay asked about that dentry. overlayfs leaves a change made to
42
+ /// a Layer outside it undefined; here such a change is the host's, and a
43
+ /// directory reached before it keeps the Layers' directories it holds.
29
44
  #[derive(Clone)]
30
45
  pub struct Overlay {
31
- stack: Stack,
32
- lock: Arc<Exclusive>,
46
+ fs: OverlayFs,
47
+ /// How many Overlays stack here, itself among them, as Linux counts
48
+ /// a super block's `s_stack_depth`.
49
+ stack_depth: usize,
50
+ }
51
+
52
+ /// The deepest Overlays may stack, as Linux's `FILESYSTEM_MAX_STACK_DEPTH`
53
+ /// bounds it, so a call through them cannot run out of stack.
54
+ const MAX_STACK_DEPTH: usize = 2;
55
+
56
+ /// The most lower Layers an Overlay takes, as overlayfs's `OVL_MAX_STACK`.
57
+ const MAX_LOWER_LAYERS: usize = 500;
58
+
59
+ impl Overlay {
60
+ /// An Overlay of `lower`, topmost first, under `upper`. Each Layer is
61
+ /// asked through that Filesystem's dentries, as overlayfs asks each
62
+ /// layer by its own lookup. As overlayfs's mount does, it refuses no
63
+ /// lower Layer, a read-only view of fewer than two, too many lower
64
+ /// Layers, a stack too deep, and one instance as two Layers, as
65
+ /// overlayfs answers overlapping layers; as gVisor's does, it refuses an
66
+ /// upper that is no Tmpfs.
67
+ pub fn new(lower: Vec<Arc<Filesystem>>, upper: Option<Arc<Filesystem>>) -> Result<Self, Errno> {
68
+ let layers: Vec<_> = lower.iter().chain(&upper).collect();
69
+ let overlapping = layers
70
+ .iter()
71
+ .enumerate()
72
+ .any(|(at, layer)| layers[..at].iter().any(|seen| Arc::ptr_eq(seen, layer)));
73
+ if overlapping {
74
+ return Err(Errno::InvalidInput);
75
+ }
76
+ let too_few = if upper.is_some() { 1 } else { 2 };
77
+ let upper_tmpfs = upper.as_ref().is_none_or(|upper| {
78
+ upper
79
+ .root()
80
+ .and_then(|root| root.inode())
81
+ .is_some_and(|root| (root.ops().as_ref() as &dyn Any).is::<Tmpfs>())
82
+ });
83
+ let stack_depth = 1 + lower
84
+ .iter()
85
+ .filter_map(|layer| layer.root()?.inode())
86
+ .filter_map(|root| {
87
+ let overlay = (root.ops().as_ref() as &dyn Any).downcast_ref::<Self>()?;
88
+ Some(overlay.stack_depth)
89
+ })
90
+ .max()
91
+ .unwrap_or(0);
92
+ if !(too_few..=MAX_LOWER_LAYERS).contains(&lower.len())
93
+ || !upper_tmpfs
94
+ || stack_depth > MAX_STACK_DEPTH
95
+ {
96
+ return Err(Errno::InvalidInput);
97
+ }
98
+ Ok(Self {
99
+ fs: OverlayFs::new(lower, upper)?,
100
+ stack_depth,
101
+ })
102
+ }
33
103
  }
34
104
 
35
- impl Default for Overlay {
36
- fn default() -> Self {
37
- Self::new()
105
+ /// The Layer's dentry the entry `dentry` answers through, and the inode the view
106
+ /// recorded, as `ovl_getattr` asks the real path.
107
+ fn real_of(dentry: &Dentry) -> Option<(Arc<Dentry>, Arc<Inode>)> {
108
+ let inode = dentry.inode()?;
109
+ let real = OverlayFileInode::of(&inode)?.real();
110
+ Some((real, inode))
111
+ }
112
+
113
+ /// Whether `real`, a Layer's dentry, still names what it recorded, as
114
+ /// `ovl_revalidate_real` asks it.
115
+ fn ovl_revalidate_real(real: &Dentry) -> Result<bool, Errno> {
116
+ match real.ops() {
117
+ Some(ops) => ops.revalidate(real.parent().inode_ops()?.as_ref(), real),
118
+ None => Ok(true),
38
119
  }
39
120
  }
40
121
 
41
- impl Overlay {
42
- /// An Overlay with no Layer yet.
43
- pub fn new() -> Self {
44
- Self {
45
- stack: Stack::default(),
46
- lock: Arc::new(Exclusive::new(Arc::new(Inline))),
122
+ /// A name stays valid while each Layer's dentry its entry keeps does, as
123
+ /// `ovl_dentry_revalidate` asks each real dentry, and while a directory still
124
+ /// stands for what each Layer holds there, as `ovl_clear_empty` drops a dentry
125
+ /// whose upper no longer matches.
126
+ impl DentryOperations for Overlay {
127
+ fn revalidate(&self, _dir: &dyn InodeOperations, dentry: &Dentry) -> Result<bool, Errno> {
128
+ let Some(inode) = dentry.inode() else {
129
+ return Ok(matches!(self.lookup(dentry)?, Lookup::Absent));
130
+ };
131
+ if let Some(kept) = OverlayFileInode::of(&inode) {
132
+ return ovl_revalidate_real(&kept.real());
47
133
  }
134
+ let Some(kept) = OverlayDirInode::of(&inode) else {
135
+ return Ok(true);
136
+ };
137
+ let shown = kept.level();
138
+ for layer in shown.iter().flatten() {
139
+ if !ovl_revalidate_real(layer.dentry())? {
140
+ return Ok(false);
141
+ }
142
+ }
143
+ let name = dentry.name();
144
+ let above = self.fs.parent(dentry)?.level();
145
+ Ok(above.iter().zip(&shown).all(|pair| match pair {
146
+ (Some(layer), Some(shown)) => layer.matches_real(&name, shown.dentry()),
147
+ _ => true,
148
+ }))
48
149
  }
49
150
 
50
- /// This Overlay with `filesystem` as a new Layer beneath the ones
51
- /// already added, allowing `access` there. It takes a lock of its own,
52
- /// so an Overlay holding the one it was built from as a Layer does not
53
- /// wait on itself.
54
- pub fn layer(mut self, filesystem: Arc<dyn Filesystem>, access: Access) -> Self {
55
- self.stack.push(filesystem, access);
56
- self.lock = Arc::new(Exclusive::new(self.lock.blocking()));
57
- self
151
+ /// A name goes once nothing holds it where any Layer behind it would let
152
+ /// its own go, since its `revalidate` answers only as those Layers do.
153
+ fn delete(&self, dentry: &Dentry) -> bool {
154
+ let Some(inode) = dentry.inode() else {
155
+ return false;
156
+ };
157
+ if let Some(kept) = OverlayFileInode::of(&inode) {
158
+ return kept.real().goes_when_unused();
159
+ }
160
+ OverlayDirInode::of(&inode).is_some_and(|kept| {
161
+ kept.level()
162
+ .iter()
163
+ .flatten()
164
+ .any(|layer| layer.dentry().goes_when_unused())
165
+ })
58
166
  }
167
+ }
59
168
 
60
- /// This Overlay waiting for its lock through `blocking`.
61
- pub fn with_blocking(self, blocking: Arc<dyn Blocking>) -> Self {
62
- Self {
63
- lock: Arc::new(Exclusive::new(blocking)),
64
- ..self
65
- }
169
+ /// A file of the view, or an entry a Layer holds that is none of the others, as
170
+ /// `ovl_file_inode_operations` answers for one.
171
+ struct OverlayRegular(Overlay);
172
+
173
+ /// A link of the view, as `ovl_symlink_inode_operations` answers for one.
174
+ struct OverlayLink(Overlay);
175
+
176
+ impl Overlay {
177
+ /// The operations an entry of `kind` answers through.
178
+ fn ops_of(&self, kind: FileType) -> Arc<dyn InodeOperations> {
179
+ match kind {
180
+ FileType::Dir => Arc::new(self.clone()),
181
+ FileType::Symlink => Arc::new(OverlayLink(self.clone())),
182
+ _ => Arc::new(OverlayRegular(self.clone())),
183
+ }
184
+ }
185
+
186
+ /// What the Layer the entry's name is found in reports, under the identity
187
+ /// the view recorded.
188
+ fn real_getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
189
+ let (real, inode) = real_of(dentry).ok_or(Errno::NotFound)?;
190
+ let found = real.getattr()?;
191
+ Ok(match inode.identity() {
192
+ Some(identity) => identity.onto(found),
193
+ None => found,
194
+ })
195
+ }
196
+ }
197
+
198
+ impl InodeOperations for OverlayRegular {
199
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
200
+ self.0.real_getattr(dentry)
201
+ }
202
+
203
+ /// Copied up first, as `ovl_setattr` does, so a lower Layer stays as it
204
+ /// was whatever its Filesystem would keep.
205
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
206
+ let overlay = &self.0;
207
+ overlay
208
+ .fs
209
+ .copy_up_file(&overlay.fs.parent(dentry)?, dentry, false)?;
210
+ let (real, _) = real_of(dentry).ok_or(Errno::NotFound)?;
211
+ // The open's truncate never reached the upper's open, so the upper must
212
+ // empty the file itself, and the view's open file is none of the upper's,
213
+ // as `ovl_setattr` clears `ATTR_OPEN` and `ATTR_FILE`.
214
+ let held = real.inode_lock()?;
215
+ notify_change(
216
+ &real,
217
+ &held,
218
+ &Iattr {
219
+ open: false,
220
+ file: None,
221
+ ..*attr
222
+ },
223
+ )
224
+ }
225
+
226
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
227
+ let fs = &self.0.fs;
228
+ fs.open(&fs.parent(dentry)?, dentry, how)
66
229
  }
67
230
  }
68
231
 
69
- impl Filesystem for Overlay {
70
- fn open(&self, path: &str, options: &OpenOptions) -> Result<Box<dyn File>, FilesystemError> {
71
- let _held = self.lock.hold()?;
72
- self.stack.open(path, options)
232
+ impl InodeOperations for OverlayLink {
233
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
234
+ self.0.real_getattr(dentry)
73
235
  }
74
236
 
75
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
76
- let _held = self.lock.hold()?;
77
- self.stack.metadata(path)
237
+ /// Where the link points, as `ovl_get_link` asks the real dentry.
238
+ fn get_link(&self, dentry: &Dentry) -> Result<String, Errno> {
239
+ let (real, _) = real_of(dentry).ok_or(Errno::NotFound)?;
240
+ real.get_link()
78
241
  }
242
+ }
79
243
 
80
- fn symlink_metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
81
- let _held = self.lock.hold()?;
82
- self.stack.symlink_metadata(path)
244
+ impl FileSystemType for Overlay {
245
+ /// With no upper nothing can change, as `ovl_fill_super` sets `SB_RDONLY`.
246
+ /// Its root takes the identity its topmost Layer's root recorded, as
247
+ /// `ovl_get_root` reads a real root's `i_ino`, so making the view asks no
248
+ /// Layer anything.
249
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
250
+ sb.set_default_d_op(self.clone());
251
+ if !self.fs.has_upper() {
252
+ sb.set_rdonly();
253
+ }
254
+ let root = Kstat::new(FileType::Dir, 0);
255
+ let root = match self.fs.root_identity() {
256
+ Some(identity) => identity.onto(root),
257
+ None => root,
258
+ };
259
+ let root_dir = self.fs.root_dir();
260
+ let root = Inode::new(&root, self);
261
+ inode::ovl_inode_init(&root, root_dir);
262
+ sb.d_make_root(root);
263
+ Ok(())
83
264
  }
265
+ }
84
266
 
85
- fn stored_path(&self, path: &str) -> Result<String, FilesystemError> {
86
- let _held = self.lock.hold()?;
87
- self.stack.stored_path(path)
267
+ /// A directory of the view, finding what a call is about through the dentry it
268
+ /// is handed, as `ovl_dir_inode_operations` answers for one.
269
+ impl InodeOperations for Overlay {
270
+ /// It reports its merged Layers.
271
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
272
+ self.fs.dir_getattr(&self.fs.dir(dentry)?.level())
273
+ }
274
+
275
+ /// Copied up first, as `ovl_setattr` does for any entry, so a lower Layer
276
+ /// stays as it was.
277
+ fn setattr(&self, dentry: &Dentry, attr: &Iattr) -> Result<(), Errno> {
278
+ let upper = self.fs.upper_dir(&self.fs.dir(dentry)?)?;
279
+ let held = upper.dentry().inode_lock()?;
280
+ notify_change(upper.dentry(), &held, attr)
281
+ }
282
+
283
+ /// The entry as a Layer spells it, as `ovl_lookup` hands
284
+ /// `d_splice_alias` the inode it made, a name no Layer could hold refused
285
+ /// before any is asked, as it compares `namelen`.
286
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
287
+ let level = self.fs.parent(dentry)?.level();
288
+ let name = dentry.name();
289
+ if name.len() > NAME_MAX {
290
+ return Err(Errno::InvalidFilename);
291
+ }
292
+ let Some(found) = self.fs.lookup_layer(&level, &name)? else {
293
+ return Ok(Lookup::Absent);
294
+ };
295
+ let stored_name = found.1.stored_name().to_string();
296
+ let inode = self
297
+ .fs
298
+ .lookup(&level, &stored_name, found, |kind| self.ops_of(kind))?;
299
+ match stored_name == name {
300
+ true => Ok(Lookup::Found(inode)),
301
+ false => Ok(Lookup::Spelled {
302
+ name: stored_name,
303
+ inode,
304
+ }),
305
+ }
306
+ }
307
+
308
+ fn open(&self, dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
309
+ let _real = self
310
+ .fs
311
+ .dir(dentry)?
312
+ .level()
313
+ .iter()
314
+ .flatten()
315
+ .map(OverlayPath::open_real)
316
+ .collect::<Result<_, _>>()?;
317
+ let fs = self.fs.clone();
318
+ Ok(Box::new(OverlayDir {
319
+ fs,
320
+ _real,
321
+ cache: Rdir::default(),
322
+ }))
88
323
  }
89
324
 
90
- fn canonicalize_beneath(&self, base: &str, path: &str) -> Result<String, FilesystemError> {
91
- let _held = self.lock.hold()?;
92
- self.stack.canonicalize_beneath(base, path)
325
+ /// What was made is found through the view's own lookup, as `ovl_instantiate`
326
+ /// records the inode for the real dentry.
327
+ fn create(&self, dentry: &Dentry) -> Result<(), Errno> {
328
+ self.fs.create(&self.fs.parent(dentry)?, &dentry.name())?;
329
+ match self.lookup(dentry)? {
330
+ Lookup::Found(inode) => dentry.add(Some(inode)),
331
+ _ => return Err(Errno::NotFound),
332
+ }
333
+ Ok(())
93
334
  }
94
335
 
95
- fn hold_directory(&self, path: &str) -> Result<Option<Hold>, FilesystemError> {
96
- let _held = self.lock.hold()?;
97
- self.stack.hold_directory(path)
336
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
337
+ self.fs.mkdir(&self.fs.parent(dentry)?, &dentry.name())
98
338
  }
99
339
 
100
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
101
- let _held = self.lock.hold()?;
102
- self.stack.read_dir(path)
340
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
341
+ self.fs.rmdir(&self.fs.parent(dentry)?, dentry)
103
342
  }
104
343
 
105
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
106
- let _held = self.lock.hold()?;
107
- self.stack.create_dir(path)
344
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
345
+ self.fs.unlink(&self.fs.parent(dentry)?, dentry)
108
346
  }
109
347
 
110
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
111
- let _held = self.lock.hold()?;
112
- self.stack.remove_dir(path)
348
+ /// Both directories lie in one Overlay, however many directories of
349
+ /// it are open. Only its upper takes a flag, which it asks itself.
350
+ fn rename(
351
+ &self,
352
+ old: &Dentry,
353
+ _new_dir: &dyn InodeOperations,
354
+ new: &Dentry,
355
+ flags: Option<RenameFlag>,
356
+ ) -> Result<(), Errno> {
357
+ if flags.is_some() {
358
+ return Err(Errno::InvalidInput);
359
+ }
360
+ self.fs
361
+ .rename(&self.fs.parent(old)?, old, &self.fs.parent(new)?, new)
113
362
  }
363
+ }
364
+
365
+ /// A directory of the view, open: it merges its Layers each time it is
366
+ /// listed, finding them through the dentry it is handed, and holds each Layer's
367
+ /// directory open while it is, as `struct ovl_dir_file` holds its `realfile`.
368
+ struct OverlayDir {
369
+ fs: OverlayFs,
370
+ _real: Vec<Box<dyn FileOperations>>,
371
+ /// What a listing merged, held until it ends, as `ovl_dir_cache` holds it.
372
+ cache: Rdir,
373
+ }
114
374
 
115
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
116
- let _held = self.lock.hold()?;
117
- self.stack.remove_file(path)
375
+ impl FileOperations for OverlayDir {
376
+ fn llseek(
377
+ &mut self,
378
+ dentry: &Dentry,
379
+ pos: u64,
380
+ offset: i64,
381
+ whence: Whence,
382
+ ) -> Result<u64, Errno> {
383
+ generic_file_llseek(dentry, pos, offset, whence)
118
384
  }
119
385
 
120
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
121
- let _held = self.lock.hold()?;
122
- self.stack.rename(from, to, rename)
386
+ fn read_iter(&mut self, _iocb: &mut super::Kiocb, _buf: &mut [u8]) -> Result<usize, Errno> {
387
+ generic_read_dir()
123
388
  }
124
389
 
125
- /// A fresh Overlay when any Layer starts each Invocation fresh, over
126
- /// each Layer's own next Filesystem. It keeps this Overlay's lock,
127
- /// since the Layers it shares are the same.
128
- fn for_invocation(&self) -> Option<Arc<dyn Filesystem>> {
129
- let stack = self.stack.for_invocation()?;
130
- Some(Arc::new(Self {
131
- stack,
132
- lock: self.lock.clone(),
133
- }))
390
+ fn iterate_shared(&mut self, dentry: &Dentry, ctx: &mut DirContext<'_>) -> Result<(), Errno> {
391
+ let (fs, cache) = (&self.fs, &mut self.cache);
392
+ cache.iterate_shared(dentry, ctx, || fs.dir_read_merged(&fs.dir(dentry)?.level()))
134
393
  }
135
394
 
136
- /// An Overlay over each Layer's own Filesystem for a Policy, keeping
137
- /// this Overlay's lock, since the Layers it shares are the same.
138
- fn for_policy(&self) -> Option<Arc<dyn Filesystem>> {
139
- let stack = self.stack.for_policy()?;
140
- Some(Arc::new(Self {
141
- stack,
142
- lock: self.lock.clone(),
143
- }))
395
+ /// Its Layers answer for what they hold, and its upper is a Tmpfs, so
396
+ /// nothing is left to make durable, as `ovl_dir_fsync` finds with no upper
397
+ /// of its own to sync.
398
+ fn fsync(&mut self, _datasync: bool) -> Result<(), Errno> {
399
+ Ok(())
144
400
  }
145
401
  }
146
402
 
@@ -151,96 +407,167 @@ mod tests {
151
407
  use std::thread;
152
408
  use std::time::{Duration, Instant};
153
409
 
154
- use super::super::memory::Memory;
155
- use super::super::temporary::Temporary;
156
- use super::super::{FileType, Hold};
410
+ use super::super::tmpfs::Tmpfs;
411
+ use super::super::wrap::{Hook, Wrap};
412
+ use super::super::{FileType, Finish, Kiocb};
157
413
  use super::*;
414
+ use crate::vfs::kern_path::{kern_path, KernPath};
415
+ use crate::vfs::Mask;
158
416
 
159
- /// The answer of a test Filesystem holding no links.
160
- macro_rules! holds_no_links {
161
- () => {
162
- fn symlink_metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
163
- self.metadata(path)
164
- }
417
+ /// `filesystem` reached through the VFS.
418
+ fn at(filesystem: impl FileSystemType) -> KernPath {
419
+ kern_path(Arc::new(filesystem))
420
+ }
165
421
 
166
- fn canonicalize_beneath(
167
- &self,
168
- _base: &str,
169
- path: &str,
170
- ) -> Result<String, FilesystemError> {
171
- Ok(path.to_string())
172
- }
422
+ /// The Filesystem `filesystem` holds, reached through the VFS.
423
+ fn on<F: FileSystemType>(filesystem: &Arc<F>) -> KernPath {
424
+ kern_path(filesystem.clone())
425
+ }
173
426
 
174
- fn for_policy(&self) -> Option<Arc<dyn Filesystem>> {
175
- None
176
- }
177
- };
427
+ #[derive(Default)]
428
+ struct CountsLookups(AtomicUsize);
429
+
430
+ impl Hook for CountsLookups {
431
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
432
+ self.0.fetch_add(1, Ordering::SeqCst);
433
+ inner.lookup(dentry)
434
+ }
178
435
  }
179
436
 
180
- /// The answer of a test Filesystem matching names byte for byte.
181
- macro_rules! matches_names_exactly {
182
- () => {
183
- fn stored_path(&self, path: &str) -> Result<String, FilesystemError> {
184
- Ok(path.to_string())
185
- }
437
+ // A Filesystem written in Ruby pays for each ask and keeps no dentry, so a
438
+ // name found absent, which no Filesystem keeps, shows how often a Layer is
439
+ // asked by itself.
440
+ // @behavior FS-184
441
+ #[test]
442
+ fn a_lookup_asks_each_layer_once_for_a_name() {
443
+ let lower: Tmpfs = [("file", "x")].into_iter().collect();
444
+ let counts = Arc::new(CountsLookups::default());
445
+ let view = at(Overlay::new(
446
+ vec![Filesystem::new(Wrap::new(Arc::new(lower), counts.clone()))
447
+ .expect("the instance must stand")],
448
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
449
+ )
450
+ .expect("the Overlay must stack"));
451
+ let asks = |path: &str| {
452
+ counts.0.store(0, Ordering::SeqCst);
453
+ let _ = view.vfs_lstat(path);
454
+ counts.0.load(Ordering::SeqCst)
186
455
  };
456
+ assert_eq!(
457
+ (asks("missing"), asks("file")),
458
+ (1, 1),
459
+ "a stat through an Overlay of a name its lower Layer lacks, and of one it holds, \
460
+ must ask that Layer once"
461
+ );
187
462
  }
188
463
 
189
- /// The answer of a test Filesystem whose identities never repeat.
190
- macro_rules! never_repeats_identities {
191
- () => {
192
- fn hold_directory(&self, _path: &str) -> Result<Option<Hold>, FilesystemError> {
193
- Ok(None)
194
- }
195
- };
464
+ // Only the upper could refuse the name once the directory was copied up, so
465
+ // the directory standing nowhere in the upper is what shows no change began.
466
+ // @behavior FS-183
467
+ #[test]
468
+ fn a_name_past_name_max_answers_too_long_and_copies_nothing_up() {
469
+ let upper = Arc::new(Tmpfs::new());
470
+ let (view, _lower) = overlay_on(upper.clone());
471
+ let long = format!("dir/{}", "n".repeat(NAME_MAX + 1));
472
+ assert_eq!(
473
+ (
474
+ view.vfs_lstat(&long).err(),
475
+ view.vfs_mkdir(&long).err(),
476
+ on(&upper).vfs_lstat("upper/dir").err(),
477
+ ),
478
+ (
479
+ Some(Errno::InvalidFilename),
480
+ Some(Errno::InvalidFilename),
481
+ Some(Errno::NotFound),
482
+ ),
483
+ "a stat and a make of a name past NAME_MAX in a lower directory, through an Overlay, \
484
+ must answer ENAMETOOLONG and leave that directory uncopied"
485
+ );
196
486
  }
197
487
 
198
- /// The answer of a test Filesystem every Invocation shares.
199
- macro_rules! is_shared {
200
- () => {
201
- fn for_invocation(&self) -> Option<Arc<dyn Filesystem>> {
202
- None
203
- }
204
- };
488
+ // @behavior FS-140
489
+ #[test]
490
+ fn a_file_with_nothing_to_flush_syncs() {
491
+ let lower: Tmpfs = [("file", "x")].into_iter().collect();
492
+ let upper = Tmpfs::new();
493
+ let overlay = at(Overlay::new(
494
+ vec![Filesystem::new(lower).expect("the instance must stand")],
495
+ Some(Filesystem::new(upper).expect("the instance must stand")),
496
+ )
497
+ .expect("the Overlay must stack"));
498
+ assert_eq!(
499
+ open_to_read(&overlay, "file").fsync(false),
500
+ Ok(()),
501
+ "FileOperations::fsync on an Overlay's file open to read from a Tmpfs Layer must \
502
+ succeed"
503
+ );
504
+ let tmpfs = at([("file", "x")].into_iter().collect::<Tmpfs>());
505
+ assert_eq!(
506
+ open_to_read(&tmpfs, "file").fsync(false),
507
+ Ok(()),
508
+ "FileOperations::fsync on a Tmpfs file must succeed"
509
+ );
205
510
  }
206
511
 
207
- fn read(fs: &dyn Filesystem, path: &str) -> Vec<u8> {
208
- let mut file = fs
209
- .open(
210
- path,
211
- &OpenOptions {
212
- read: true,
213
- ..OpenOptions::default()
214
- },
215
- )
216
- .expect("the file must open");
512
+ fn open_to_read(fs: &KernPath, path: &str) -> Box<dyn FileOperations> {
513
+ fs.open(
514
+ path,
515
+ &OpenHow {
516
+ read: true,
517
+ ..OpenHow::default()
518
+ },
519
+ )
520
+ .expect("the file must open to read")
521
+ }
522
+
523
+ fn read_from(file: &mut dyn FileOperations) -> Vec<u8> {
217
524
  let mut buf = vec![0; 64];
218
- let read = file.read_at(&mut buf, 0).expect("the file must read");
525
+ let read = file
526
+ .read_iter(&mut Kiocb::new(0), &mut buf)
527
+ .expect("the file must read");
219
528
  buf.truncate(read);
220
529
  buf
221
530
  }
222
531
 
223
- fn write(fs: &dyn Filesystem, path: &str, contents: &[u8]) -> Result<(), FilesystemError> {
224
- fs.open(
532
+ fn read(fs: &KernPath, path: &str) -> Vec<u8> {
533
+ read_from(open_to_read(fs, path).as_mut())
534
+ }
535
+
536
+ fn write(fs: &KernPath, path: &str, contents: &[u8]) -> Result<(), Errno> {
537
+ fs.open_or_create(
225
538
  path,
226
- &OpenOptions {
539
+ &OpenHow {
227
540
  write: true,
228
- create: true,
229
541
  truncate: true,
230
- ..OpenOptions::default()
542
+ ..OpenHow::default()
231
543
  },
232
544
  )?
233
- .write_at(contents, 0)
545
+ .write_iter(&mut Kiocb::new(0), contents)
234
546
  .map(drop)
235
547
  }
236
548
 
237
- fn overwrite(fs: &dyn Filesystem, path: &str, contents: &[u8]) {
549
+ /// Write at the start of what stands at `path`, so a copy up brings its
550
+ /// bytes along.
551
+ fn write_over(fs: &KernPath, path: &str, contents: &[u8]) -> Result<(), Errno> {
552
+ let how = OpenHow {
553
+ write: true,
554
+ ..OpenHow::default()
555
+ };
556
+ fs.open(path, &how)?
557
+ .write_iter(&mut Kiocb::new(0), contents)
558
+ .map(drop)
559
+ }
560
+
561
+ fn overwrite(fs: &KernPath, path: &str, contents: &[u8]) {
238
562
  write(fs, path, contents).expect("the write must land");
239
563
  }
240
564
 
241
- fn names(fs: &dyn Filesystem, path: &str) -> Vec<String> {
242
- let mut names: Vec<String> = fs
243
- .read_dir(path)
565
+ fn names(fs: &KernPath, path: &str) -> Vec<String> {
566
+ let listed = match path {
567
+ "" => fs.iterate_dir(),
568
+ path => fs.open_dir(path).and_then(|dir| dir.iterate_dir()),
569
+ };
570
+ let mut names: Vec<String> = listed
244
571
  .expect("the directory must list")
245
572
  .into_iter()
246
573
  .map(|entry| entry.name)
@@ -249,18 +576,83 @@ mod tests {
249
576
  names
250
577
  }
251
578
 
252
- fn memory_with(path: &str, contents: &str) -> Arc<Memory> {
579
+ fn tmpfs_with(path: &str, contents: &str) -> Arc<Tmpfs> {
253
580
  Arc::new([(path, contents)].into_iter().collect())
254
581
  }
255
582
 
256
- /// A writable `upper` over a read-only Memory holding `dir/file` =
257
- /// "lower".
258
- fn overlay_on(upper: Arc<dyn Filesystem>) -> (Overlay, Arc<Memory>) {
259
- let lower = memory_with("dir/file", "lower");
260
- let overlay = Overlay::new()
261
- .layer(upper, Access::ReadWrite)
262
- .layer(lower.clone(), Access::Read);
263
- (overlay, lower)
583
+ // A helper beneath the VFS skips the super block's read-only answer, so only
584
+ // the view's own upper standing empty keeps the change off its lower Layers.
585
+ // @behavior FS-197
586
+ #[test]
587
+ fn a_change_reaching_an_overlay_with_no_upper_leaves_its_lower_layers_as_they_are() {
588
+ let top = tmpfs_with("dir/file", "top");
589
+ let overlay = at(lowers(top.clone(), Arc::new(Tmpfs::new())));
590
+ assert_eq!(
591
+ (
592
+ overlay.vfs_mkdir("made").err(),
593
+ on(&top).vfs_lstat("made").err()
594
+ ),
595
+ (Some(Errno::ReadOnlyFilesystem), Some(Errno::NotFound)),
596
+ "OverlayFs::mkdir with no upper, reached beneath the VFS's read-only answer, must \
597
+ answer EROFS and make nothing in its topmost lower Layer"
598
+ );
599
+ }
600
+
601
+ /// A security module recording the name of each directory it is asked to
602
+ /// let change.
603
+ struct RecordsChanges(Arc<Mutex<Vec<String>>>);
604
+
605
+ impl crate::security::SecurityOperations for RecordsChanges {
606
+ fn inode_permission(&self, dentry: &Dentry, mask: crate::vfs::Mask) -> Result<(), Errno> {
607
+ if mask.contains(crate::vfs::Mask::WRITE) {
608
+ self.0.lock().expect("never poisoned").push(dentry.name());
609
+ }
610
+ Ok(())
611
+ }
612
+ }
613
+
614
+ // A Layer's directories carry names of their own, so a module asked about
615
+ // one would record more than the view's root.
616
+ // @behavior FS-198
617
+ #[test]
618
+ fn a_call_through_an_overlay_asks_a_module_of_the_view_alone() {
619
+ let overlay = over(tmpfs_with("f", "x"), Arc::new(Tmpfs::new()));
620
+ let mount = crate::mount::Mount::new(
621
+ "/data",
622
+ Filesystem::new(overlay).expect("the instance must stand"),
623
+ crate::mount::Access::ReadWrite,
624
+ )
625
+ .expect("/data is a guest path");
626
+ let asked = Arc::new(Mutex::new(Vec::new()));
627
+ let cred = crate::cred::Cred::new(vec![Arc::new(RecordsChanges(asked.clone()))]);
628
+ let root = crate::vfs::Path::root(mount.mnt());
629
+ let made = crate::vfs::filename_mkdirat(&cred, &root, "d");
630
+ assert_eq!(
631
+ (made, asked.lock().expect("never poisoned").clone()),
632
+ (Ok(()), vec![String::new()]),
633
+ "vfs::filename_mkdirat through an Overlay must ask a security module of the view's \
634
+ directory alone, as overlayfs makes its Layers' calls with its creator_cred"
635
+ );
636
+ }
637
+
638
+ /// `upper` over the one lower Layer `lower`.
639
+ fn over(lower: Arc<dyn FileSystemType>, upper: Arc<Tmpfs>) -> Overlay {
640
+ let instance = |fs| Filesystem::new(fs).expect("the instance must stand");
641
+ Overlay::new(vec![instance(lower)], Some(instance(upper)))
642
+ .expect("an upper over a lower Layer must make a view")
643
+ }
644
+
645
+ /// The lower Layers `top` over `bottom`, with no upper.
646
+ fn lowers(top: Arc<dyn FileSystemType>, bottom: Arc<dyn FileSystemType>) -> Overlay {
647
+ let instance = |fs| Filesystem::new(fs).expect("the instance must stand");
648
+ Overlay::new(vec![instance(top), instance(bottom)], None)
649
+ .expect("two lower Layers must make a view")
650
+ }
651
+
652
+ /// `upper` over a lower Tmpfs holding `dir/file` = "lower".
653
+ fn overlay_on(upper: Arc<Tmpfs>) -> (KernPath, Arc<Tmpfs>) {
654
+ let lower = tmpfs_with("dir/file", "lower");
655
+ (at(over(lower.clone(), upper)), lower)
264
656
  }
265
657
 
266
658
  /// A host directory holding `target`, `dir/inner`, and the links `link`
@@ -288,74 +680,67 @@ mod tests {
288
680
  Self(path)
289
681
  }
290
682
 
291
- /// A writable Memory over the host directory as a read-only Layer.
292
- fn overlay(&self) -> Overlay {
293
- let lower =
294
- super::super::Directory::new(&self.0).expect("the host directory must open");
295
- Overlay::new()
296
- .layer(Arc::new(Memory::new()), Access::ReadWrite)
297
- .layer(Arc::new(lower), Access::Read)
683
+ /// An empty upper over the host directory as the lower Layer.
684
+ fn overlay(&self) -> KernPath {
685
+ self.under(Arc::new(Tmpfs::new()))
298
686
  }
299
- }
300
687
 
301
- #[cfg(unix)]
302
- impl Drop for LinkTree {
303
- fn drop(&mut self) {
304
- let _ = std::fs::remove_dir_all(&self.0);
688
+ /// The host directory as the lower Layer beneath `upper`.
689
+ fn under(&self, upper: Arc<Tmpfs>) -> KernPath {
690
+ at(over(Arc::new(self.bind()), upper))
691
+ }
692
+
693
+ fn bind(&self) -> super::super::Bind {
694
+ super::super::Bind::new(&self.0).expect("the host directory must open")
305
695
  }
306
696
  }
307
697
 
308
- // The link points at a file in the same Layer, so only a lookup that
309
- // reaches the Layer's own `symlink_metadata` can answer a link.
310
- // The links stand in the Directory Layer beneath a Memory one, so only
311
- // the merged view handing them to the Layer holding them resolves them.
312
- // @behavior FS-098
698
+ // The upper Layer's `dirlink` is a directory and the lower one's a link,
699
+ // so only merging directory over directory keeps the lower link's
700
+ // target out of the view.
701
+ // @behavior FS-113
313
702
  #[cfg(unix)]
314
703
  #[test]
315
- fn an_overlay_follows_a_link_beneath_a_directory_within_the_layer_holding_it() {
316
- let host = LinkTree::new("beneath");
317
- std::fs::create_dir_all(host.0.join("dir/sub"))
318
- .expect("the host directory must be created");
319
- std::fs::write(host.0.join("dir/sub/y"), "inner").expect("the inner file must be written");
320
- std::os::unix::fs::symlink("sub", host.0.join("dir/in")).expect("the link must be made");
321
- std::os::unix::fs::symlink("../target", host.0.join("dir/up"))
322
- .expect("the link must be made");
323
- let overlay = host.overlay();
704
+ fn a_lower_layers_link_beneath_an_upper_directory_is_not_merged() {
705
+ let tree = LinkTree::new("not-merged");
706
+ let overlay = tree.under(tmpfs_with("upper/dirlink/.keep", ""));
707
+ overlay
708
+ .vfs_unlink("dirlink/.keep")
709
+ .expect("the seed must go");
324
710
  assert_eq!(
325
711
  (
326
- overlay.canonicalize_beneath("dir", "in/y"),
327
- overlay.canonicalize_beneath("dir", "up"),
712
+ kind(&overlay, "dirlink/inner"),
713
+ names(&overlay, "dirlink").len()
328
714
  ),
329
- (Ok("sub/y".to_string()), Err(FilesystemError::NotPermitted)),
330
- "a link a Directory Layer holds within `dir`, resolved through \
331
- Overlay::canonicalize_beneath, must resolve to where it leads, and one leading out \
332
- of `dir` must not be permitted"
715
+ (Err(Errno::NotFound), 0),
716
+ "a name beneath a directory an upper Layer holds, where a lower Layer holds a link, \
717
+ through vfs_lstat and its listing must show nothing the link leads to"
333
718
  );
334
719
  }
335
720
 
336
- // The link stands in the Directory Layer beneath a Memory one, so only
337
- // the Overlay handing each Layer's own Filesystem for a Policy refuses it.
721
+ #[cfg(unix)]
722
+ impl Drop for LinkTree {
723
+ fn drop(&mut self) {
724
+ let _ = std::fs::remove_dir_all(&self.0);
725
+ }
726
+ }
727
+
728
+ // The link stands in the Bind Layer beneath a Tmpfs one, so only
729
+ // the Overlay asking that Layer without following refuses it.
338
730
  // @behavior FS-100
339
731
  #[cfg(unix)]
340
732
  #[test]
341
- fn an_overlay_for_a_policy_follows_no_link_in_any_layer() {
342
- let host = LinkTree::new("for-policy");
733
+ fn an_overlay_opens_no_link_as_a_directory_where_asked_not_to_follow() {
734
+ let host = LinkTree::new("nofollow");
343
735
  let overlay = host.overlay();
344
- let reading = OpenOptions {
345
- read: true,
346
- ..OpenOptions::default()
347
- };
348
- let for_policy = overlay
349
- .for_policy()
350
- .expect("an Overlay over a Directory has a Filesystem for a Policy");
351
736
  assert_eq!(
352
737
  (
353
- overlay.open("dirlink/inner", &reading).map(drop),
354
- for_policy.open("dirlink/inner", &reading).map(drop),
738
+ overlay.open_dir("dirlink").map(drop),
739
+ overlay.vfs_readlink("dirlink")
355
740
  ),
356
- (Ok(()), Err(FilesystemError::FilesystemLoop)),
357
- "a path through a link a Directory Layer holds, opened through an Overlay's \
358
- for_policy, must be a link loop, where the Overlay itself reaches it"
741
+ (Err(Errno::FilesystemLoop), Ok("dir".to_string())),
742
+ "a link a Bind Layer holds, opened through Overlay::open_dir, must be a \
743
+ link loop, and through vfs_readlink must answer where it points"
359
744
  );
360
745
  }
361
746
 
@@ -365,16 +750,12 @@ mod tests {
365
750
  fn an_overlay_reports_a_link_its_layer_holds_as_a_link() {
366
751
  let host = LinkTree::new("lstat");
367
752
  let overlay = host.overlay();
368
- let file_type = |path| {
369
- overlay
370
- .symlink_metadata(path)
371
- .map(|metadata| metadata.file_type)
372
- };
753
+ let file_type = |path| kind(&overlay, path);
373
754
  assert_eq!(
374
755
  (file_type("link"), file_type("dangling")),
375
756
  (Ok(FileType::Symlink), Ok(FileType::Symlink)),
376
- "a link a Directory Layer holds, pointing at a file or at nothing, looked up through \
377
- Overlay::symlink_metadata must be reported as a link"
757
+ "a link a Bind Layer holds, pointing at a file or at nothing, looked up through \
758
+ vfs_lstat must be reported as a link"
378
759
  );
379
760
  }
380
761
 
@@ -387,11 +768,11 @@ mod tests {
387
768
  let host = LinkTree::new("unlink");
388
769
  let overlay = host.overlay();
389
770
  let removed = (
390
- overlay.remove_dir("dirlink"),
391
- overlay.remove_file("dirlink"),
392
- overlay.remove_file("dangling"),
771
+ overlay.vfs_rmdir("dirlink"),
772
+ overlay.vfs_unlink("dirlink"),
773
+ overlay.vfs_unlink("dangling"),
393
774
  );
394
- let gone = |path| overlay.symlink_metadata(path).err();
775
+ let gone = |path| overlay.vfs_lstat(path).err();
395
776
  assert_eq!(
396
777
  (
397
778
  removed,
@@ -400,13 +781,13 @@ mod tests {
400
781
  host.0.join("dirlink").is_symlink()
401
782
  ),
402
783
  (
403
- (Err(FilesystemError::NotADirectory), Ok(()), Ok(())),
404
- Some(FilesystemError::NotFound),
405
- Some(FilesystemError::NotFound),
784
+ (Err(Errno::NotADirectory), Ok(()), Ok(())),
785
+ Some(Errno::NotFound),
786
+ Some(Errno::NotFound),
406
787
  true
407
788
  ),
408
- "a link a read-only Directory Layer holds, removed through Overlay::remove_dir and \
409
- Overlay::remove_file, must be refused as no directory and then removed as itself, \
789
+ "a link a read-only Bind Layer holds, removed through vfs_rmdir and \
790
+ vfs_unlink, must be refused as no directory and then removed as itself, \
410
791
  leaving the Layer as it was"
411
792
  );
412
793
  }
@@ -428,13 +809,10 @@ mod tests {
428
809
  assert_eq!(
429
810
  (
430
811
  write(&overlay, "pipe", b"upper"),
431
- overlay.rename("pipe", "moved", Rename::File)
432
- ),
433
- (
434
- Err(FilesystemError::PermissionDenied),
435
- Err(FilesystemError::CrossesDevices)
812
+ overlay.rename("pipe", &overlay, "moved")
436
813
  ),
437
- "a FIFO a read-only Directory Layer holds, written or renamed through an Overlay, must \
814
+ (Err(Errno::PermissionDenied), Err(Errno::CrossesDevices)),
815
+ "a FIFO a read-only Bind Layer holds, written or renamed through an Overlay, must \
438
816
  be refused as permission denied and as crossing devices"
439
817
  );
440
818
  }
@@ -454,181 +832,282 @@ mod tests {
454
832
  assert!(made.success(), "the FIFO must be made");
455
833
  let overlay = host.overlay();
456
834
  overlay
457
- .create_dir("made")
458
- .expect("a directory must be made in the writable Layer");
459
- let file_type = |path| overlay.metadata(path).map(|metadata| metadata.file_type);
835
+ .vfs_mkdir("made")
836
+ .expect("a directory must be made in the upper");
837
+ let file_type = |path| kind(&overlay, path);
460
838
  assert_eq!(
461
839
  (
462
- overlay.rename("pipe", "dir", Rename::Any),
463
- overlay.rename("made", "pipe", Rename::Any),
840
+ overlay.rename("pipe", &overlay, "dir"),
841
+ overlay.rename("made", &overlay, "pipe"),
464
842
  file_type("pipe"),
465
843
  file_type("made"),
466
844
  ),
467
845
  (
468
- Err(FilesystemError::IsADirectory),
469
- Err(FilesystemError::NotADirectory),
470
- Ok(FileType::Unknown),
471
- Ok(FileType::Directory)
846
+ Err(Errno::IsADirectory),
847
+ Err(Errno::NotADirectory),
848
+ Ok(FileType::Fifo),
849
+ Ok(FileType::Dir)
472
850
  ),
473
851
  "a FIFO renamed onto a directory through an Overlay must be refused as a directory, \
474
852
  and a directory renamed onto a FIFO as no directory, leaving both in place"
475
853
  );
476
854
  }
477
855
 
478
- // Each change would land in the writable Memory, which holds no link,
479
- // so only refusing it keeps the write from parting with its target.
856
+ /// A lower Layer whose one file, `file`, would keep any time it is asked
857
+ /// to, recording that it was.
858
+ struct KeepsTimes(Arc<AtomicUsize>);
859
+
860
+ impl FileSystemType for KeepsTimes {
861
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
862
+ sb.d_make_root(Inode::new(&Kstat::new(FileType::Dir, 0), self));
863
+ Ok(())
864
+ }
865
+ }
866
+
867
+ impl InodeOperations for KeepsTimes {
868
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
869
+ Ok(match dentry.name().as_str() {
870
+ "file" => Kstat::new(FileType::RegFile, 0).with_identity(1, 2),
871
+ _ => Kstat::new(FileType::Dir, 0).with_identity(1, 1),
872
+ })
873
+ }
874
+
875
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
876
+ Ok(match dentry.name().as_str() {
877
+ "file" => Lookup::Found(Inode::new(
878
+ &Kstat::new(FileType::RegFile, 0).with_identity(1, 2),
879
+ Arc::new(Self(self.0.clone())),
880
+ )),
881
+ _ => Lookup::Absent,
882
+ })
883
+ }
884
+
885
+ fn setattr(&self, _dentry: &Dentry, _attr: &Iattr) -> Result<(), Errno> {
886
+ self.0.fetch_add(1, Ordering::SeqCst);
887
+ Ok(())
888
+ }
889
+
890
+ fn open(&self, _dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
891
+ struct Empty;
892
+ impl FileOperations for Empty {
893
+ fn read_iter(
894
+ &mut self,
895
+ _iocb: &mut Kiocb,
896
+ _buf: &mut [u8],
897
+ ) -> Result<usize, Errno> {
898
+ Ok(0)
899
+ }
900
+ }
901
+ Ok(Box::new(Empty))
902
+ }
903
+ }
904
+
905
+ // A lower Layer that would keep the time shows the call stopped at the upper.
906
+ // @behavior FS-147
907
+ #[test]
908
+ fn a_time_set_through_an_overlay_leaves_its_lower_layer_as_it_was() {
909
+ let asked = Arc::new(AtomicUsize::new(0));
910
+ let upper = Arc::new(Tmpfs::new());
911
+ let overlay = Overlay::new(
912
+ vec![Filesystem::new(KeepsTimes(asked.clone())).expect("the instance must stand")],
913
+ Some(Filesystem::new(upper.clone()).expect("the instance must stand")),
914
+ )
915
+ .unwrap_or_else(|_| panic!("the Overlay must make"));
916
+ let mount = crate::mount::Mount::new(
917
+ "/data",
918
+ Filesystem::new(overlay).expect("the instance must stand"),
919
+ crate::mount::Access::ReadWrite,
920
+ )
921
+ .expect("/data is a guest path");
922
+ let answer = crate::vfs::do_utimes_path(
923
+ &Arc::default(),
924
+ &crate::vfs::Path::root(mount.mnt()),
925
+ "file",
926
+ false,
927
+ &Iattr::for_times(None, Some(crate::filesystem::SetTime::Now)),
928
+ );
929
+ assert_eq!(
930
+ (
931
+ answer,
932
+ asked.load(Ordering::SeqCst),
933
+ kern_path(upper).vfs_lstat("upper/file").is_ok()
934
+ ),
935
+ (Ok(()), 0, true),
936
+ "vfs::do_utimes_paththrough an Overlay on a file of its lower Layer must copy the file \
937
+ up, set the time there, and never ask the lower Layer"
938
+ );
939
+ }
940
+
941
+ // A recursive climb needs more than this stack at this depth, in a build
942
+ // of any optimization, so only a loop passes.
943
+ // @behavior FS-146
944
+ #[test]
945
+ fn a_change_copies_up_however_deep_it_lands() {
946
+ let deep = vec!["a"; 1500].join("/");
947
+ let lower: Tmpfs = [(format!("{deep}/file"), "x")].into_iter().collect();
948
+ let overlay = Overlay::new(
949
+ vec![Filesystem::new(lower).expect("the instance must stand")],
950
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
951
+ )
952
+ .unwrap_or_else(|_| panic!("the Overlay must make"));
953
+ let made = std::thread::Builder::new()
954
+ .stack_size(256 * 1024)
955
+ .spawn(move || {
956
+ let view = kern_path(Arc::new(overlay));
957
+ view.vfs_mkdir(&format!("{deep}/made"))?;
958
+ view.vfs_lstat(&format!("{deep}/made"))
959
+ .map(|found| found.file_type)
960
+ })
961
+ .expect("the thread must start")
962
+ .join()
963
+ .expect("the thread must not panic");
964
+ assert_eq!(
965
+ made,
966
+ Ok(FileType::Dir),
967
+ "a directory made 1500 directories deep in a lower Layer, through an Overlay on a \
968
+ 256 KiB stack, must copy every directory above it up and stand"
969
+ );
970
+ }
971
+
972
+ // The upper is a Tmpfs, which holds no link, so a link cannot land there.
480
973
  // @behavior FS-051
481
974
  #[cfg(unix)]
482
975
  #[test]
483
- fn an_overlay_refuses_a_change_through_a_link_its_read_only_layer_holds() {
976
+ fn an_overlay_refuses_to_move_a_link_its_read_only_layer_holds() {
484
977
  let host = LinkTree::new("through");
485
978
  let overlay = host.overlay();
486
- let creates = OpenOptions {
487
- write: true,
488
- create: true,
489
- ..OpenOptions::default()
490
- };
491
- let refused = [
492
- write(&overlay, "link", b"upper"),
493
- overlay.open("dirlink/new", &creates).map(drop),
494
- overlay.open("dangling", &creates).map(drop),
495
- overlay.rename("link", "moved", Rename::Any),
496
- ];
497
979
  assert_eq!(
498
- (refused, read(&overlay, "target")),
499
980
  (
500
- [
501
- Err(FilesystemError::CrossesDevices),
502
- Err(FilesystemError::CrossesDevices),
503
- Err(FilesystemError::CrossesDevices),
504
- Err(FilesystemError::CrossesDevices)
505
- ],
506
- b"lower".to_vec()
981
+ overlay.rename("link", &overlay, "moved"),
982
+ read(&overlay, "target")
507
983
  ),
508
- "a write, a create, and a rename reaching through a link a read-only Directory Layer \
509
- holds, through an Overlay, must be refused as crossing devices and leave the target \
510
- as it was"
984
+ (Err(Errno::CrossesDevices), b"lower".to_vec()),
985
+ "a rename of a link a read-only Bind Layer holds, through an Overlay, must be refused \
986
+ as crossing devices and leave the target as it was"
511
987
  );
512
988
  }
513
989
 
514
- // The lower Memory holds a readable `dangling`, so only the upper
990
+ // The lower Tmpfs holds a readable `dangling`, so only the upper
515
991
  // link standing at that path can keep the read from reaching it.
516
992
  // @behavior FS-053
517
993
  #[cfg(unix)]
518
994
  #[test]
519
995
  fn a_link_a_layer_holds_hides_what_the_layers_below_hold_there() {
520
996
  let host = LinkTree::new("shadow");
521
- let upper = super::super::Directory::new(&host.0).expect("the host directory must open");
522
- let overlay = Overlay::new()
523
- .layer(Arc::new(upper), Access::ReadWrite)
524
- .layer(memory_with("dangling", "lower"), Access::Read);
997
+ let overlay = at(lowers(
998
+ Arc::new(host.bind()),
999
+ tmpfs_with("dangling", "lower"),
1000
+ ));
525
1001
  assert_eq!(
526
1002
  overlay
527
1003
  .open(
528
1004
  "dangling",
529
- &OpenOptions {
1005
+ &OpenHow {
530
1006
  read: true,
531
- ..OpenOptions::default()
1007
+ ..OpenHow::default()
532
1008
  }
533
1009
  )
534
1010
  .map(drop),
535
- Err(FilesystemError::NotFound),
536
- "a lower file beneath a dangling link a higher Directory Layer holds at its path, \
537
- opened through Overlay::open, must not be found"
1011
+ Err(Errno::FilesystemLoop),
1012
+ "a lower file beneath a dangling link a higher Bind Layer holds at its path, \
1013
+ opened through Overlay::open, must be refused as the link, the file unreached"
538
1014
  );
539
1015
  }
540
1016
 
541
- // The lower Memory holds `dirlink/x` beside where the upper link points,
1017
+ // The lower Tmpfs holds `dirlink/x` beside where the upper link points,
542
1018
  // so only the link hiding everything beneath it keeps `x` out.
543
1019
  // @behavior FS-057
544
1020
  #[cfg(unix)]
545
1021
  #[test]
546
1022
  fn a_link_a_layer_holds_hides_what_the_layers_below_hold_beneath_it() {
547
1023
  let host = LinkTree::new("shadow-beneath");
548
- let upper = super::super::Directory::new(&host.0).expect("the host directory must open");
549
- let overlay = Overlay::new()
550
- .layer(Arc::new(upper), Access::ReadWrite)
551
- .layer(memory_with("dirlink/x", "lower"), Access::Read);
552
- let found = overlay
553
- .metadata("dirlink/x")
554
- .map(|metadata| metadata.file_type);
1024
+ let overlay = at(lowers(
1025
+ Arc::new(host.bind()),
1026
+ tmpfs_with("dirlink/x", "lower"),
1027
+ ));
555
1028
  assert_eq!(
556
- (names(&overlay, "dirlink"), found),
557
- (vec!["inner".to_string()], Err(FilesystemError::NotFound)),
558
- "a directory a higher Directory Layer holds as a link, listed and looked into through \
559
- an Overlay, must show only where the link points and none of a lower Layer's entries"
1029
+ (
1030
+ overlay
1031
+ .vfs_lstat("dirlink")
1032
+ .map(|metadata| metadata.file_type),
1033
+ overlay.open_dir("dirlink").map(drop)
1034
+ ),
1035
+ (Ok(FileType::Symlink), Err(Errno::FilesystemLoop)),
1036
+ "a directory a higher Bind Layer holds as a link, looked up and opened through an \
1037
+ Overlay, must stand as the link, so none of a lower Layer's entries beneath it show"
560
1038
  );
561
1039
  }
562
1040
 
563
- // The lower directory sits in a writable Layer, so only the whiteout,
564
- // not a removal that cannot take a directory, keeps the view whole.
1041
+ // The lower directory stays in its Layer, so only the whiteout keeps
1042
+ // it from showing once the upper file goes.
565
1043
  // @behavior FS-058
566
1044
  #[test]
567
1045
  fn removing_a_file_over_a_lower_directory_leaves_it_hidden() {
568
- let lower = memory_with("f/g", "lower");
569
- let overlay = Overlay::new()
570
- .layer(memory_with("f", "upper"), Access::ReadWrite)
571
- .layer(lower.clone(), Access::ReadWrite);
572
- let removed = overlay.remove_file("f");
1046
+ let lower = tmpfs_with("f/g", "lower");
1047
+ let overlay = at(over(lower.clone(), tmpfs_with("upper/f", "upper")));
1048
+ let removed = overlay.vfs_unlink("f");
573
1049
  assert_eq!(
574
1050
  (
575
1051
  removed,
576
- overlay.symlink_metadata("f").err(),
577
- lower.metadata("f/g").is_ok()
1052
+ overlay.vfs_lstat("f").err(),
1053
+ on(&lower).vfs_lstat("f/g").is_ok()
578
1054
  ),
579
- (Ok(()), Some(FilesystemError::NotFound), true),
1055
+ (Ok(()), Some(Errno::NotFound), true),
580
1056
  "a file a higher Layer holds over a lower Layer's directory, removed through \
581
- Overlay::remove_file, must leave the path gone from the view and the lower \
1057
+ vfs_unlink, must leave the path gone from the view and the lower \
582
1058
  directory as it was"
583
1059
  );
584
1060
  }
585
1061
 
586
- // The writable Layer's `dir` holds only the whiteout hiding `file`, so
1062
+ // The upper's `dir` holds only the whiteout hiding `file`, so
587
1063
  // only judging the view, not that copy, lets the move go.
588
1064
  // @behavior FS-059
589
1065
  #[test]
590
1066
  fn a_directory_moves_onto_one_holding_only_markers() {
591
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1067
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
592
1068
  overlay
593
- .remove_file("dir/file")
1069
+ .vfs_unlink("dir/file")
594
1070
  .expect("the file must be removed");
595
1071
  overlay
596
- .create_dir("new")
1072
+ .vfs_mkdir("new")
597
1073
  .expect("the directory must be made");
598
1074
  overwrite(&overlay, "new/made", b"made");
599
- let moved = overlay.rename("new", "dir", Rename::Directory);
1075
+ let moved = overlay.rename("new", &overlay, "dir");
600
1076
  assert_eq!(
601
1077
  (moved, names(&overlay, "dir")),
602
1078
  (Ok(()), vec!["made".to_string()]),
603
1079
  "a directory renamed through Overlay::rename onto one the view shows empty, whose \
604
- writable copy holds only a whiteout, must take its place and show only its own entries"
1080
+ upper copy holds only a whiteout, must take its place and show only its own entries"
605
1081
  );
606
1082
  }
607
1083
 
608
- // The directory made again is marked opaque in the writable Layer, so
609
- // only that mark tells it apart from one the read-only Layer still holds.
1084
+ // The directory made again is marked opaque in the upper, so only that
1085
+ // mark tells it apart from one the lower Layer still holds.
610
1086
  // @behavior FS-060
611
1087
  #[test]
612
- fn a_directory_made_again_moves_as_the_writable_layers_own() {
613
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1088
+ fn a_directory_made_again_moves_as_the_uppers_own() {
1089
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
614
1090
  overlay
615
- .remove_file("dir/file")
1091
+ .vfs_unlink("dir/file")
616
1092
  .expect("the file must be removed");
617
1093
  overlay
618
- .remove_dir("dir")
1094
+ .vfs_rmdir("dir")
619
1095
  .expect("the directory must be removed");
620
1096
  overlay
621
- .create_dir("dir")
1097
+ .vfs_mkdir("dir")
622
1098
  .expect("the directory must be made again");
623
- let moved = overlay.rename("dir", "moved", Rename::Directory);
1099
+ let moved = overlay.rename("dir", &overlay, "moved");
624
1100
  assert_eq!(
625
1101
  (
626
1102
  moved,
627
- overlay.metadata("dir").err(),
628
- overlay.read_dir("moved").map(|entries| entries.len())
1103
+ overlay.vfs_lstat("dir").err(),
1104
+ overlay
1105
+ .open_dir("moved")
1106
+ .and_then(|dir| dir.iterate_dir())
1107
+ .map(|entries| entries.len())
629
1108
  ),
630
- (Ok(()), Some(FilesystemError::NotFound), Ok(0)),
631
- "a directory made again through an Overlay where a read-only Layer's one was removed, \
1109
+ (Ok(()), Some(Errno::NotFound), Ok(0)),
1110
+ "a directory made again through an Overlay where a lower Layer's one was removed, \
632
1111
  renamed through Overlay::rename, must move and leave nothing of the lower one behind"
633
1112
  );
634
1113
  }
@@ -636,10 +1115,10 @@ mod tests {
636
1115
  // @behavior FS-061
637
1116
  #[test]
638
1117
  fn an_overlay_refuses_a_file_moved_beneath_itself_as_no_directory() {
639
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1118
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
640
1119
  assert_eq!(
641
- overlay.rename("dir/file", "dir/file/x", Rename::Any),
642
- Err(FilesystemError::NotADirectory),
1120
+ overlay.rename("dir/file", &overlay, "dir/file/x"),
1121
+ Err(Errno::NotADirectory),
643
1122
  "a file renamed through Overlay::rename to a path beneath itself must be refused as \
644
1123
  no directory, as rename(2) refuses it"
645
1124
  );
@@ -653,21 +1132,17 @@ mod tests {
653
1132
  fn an_overlay_finds_a_dangling_link_where_a_new_entry_would_go() {
654
1133
  let host = LinkTree::new("dangling");
655
1134
  let overlay = host.overlay();
656
- let exclusive = OpenOptions {
1135
+ let exclusive = OpenHow {
657
1136
  write: true,
658
- create_new: true,
659
- ..OpenOptions::default()
1137
+ ..OpenHow::default()
660
1138
  };
661
1139
  assert_eq!(
662
1140
  (
663
- overlay.open("dangling", &exclusive).map(drop),
664
- overlay.create_dir("dangling")
1141
+ overlay.create("dangling", &exclusive).map(drop),
1142
+ overlay.vfs_mkdir("dangling")
665
1143
  ),
666
- (
667
- Err(FilesystemError::AlreadyExists),
668
- Err(FilesystemError::AlreadyExists)
669
- ),
670
- "an exclusive create and a create_dir at a dangling link a read-only Directory Layer \
1144
+ (Err(Errno::AlreadyExists), Err(Errno::AlreadyExists)),
1145
+ "an exclusive create and a create_dir at a dangling link a lower Bind Layer \
671
1146
  holds, through an Overlay, must find it already there"
672
1147
  );
673
1148
  }
@@ -675,7 +1150,7 @@ mod tests {
675
1150
  // @behavior FS-008
676
1151
  #[test]
677
1152
  fn an_overlay_reads_through_to_a_lower_layer() {
678
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1153
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
679
1154
  assert_eq!(
680
1155
  read(&overlay, "dir/file"),
681
1156
  b"lower",
@@ -685,67 +1160,53 @@ mod tests {
685
1160
 
686
1161
  // @behavior FS-009
687
1162
  #[test]
688
- fn a_write_to_a_read_only_layers_file_lands_in_the_nearest_writable_layer_above_it() {
689
- let upper = Arc::new(Memory::new());
1163
+ fn a_write_to_a_lower_layers_file_lands_in_the_upper() {
1164
+ let upper = Arc::new(Tmpfs::new());
690
1165
  let (overlay, _) = overlay_on(upper.clone());
691
1166
  overwrite(&overlay, "dir/file", b"upper");
692
1167
  assert_eq!(
693
- read(upper.as_ref(), "dir/file"),
1168
+ read(&on(&upper), "upper/dir/file"),
694
1169
  b"upper",
695
- "a read-only Layer's file written through Overlay::open must land in the writable Layer above it"
1170
+ "a lower Layer's file written through Overlay::open must land in the upper"
696
1171
  );
697
1172
  }
698
1173
 
699
1174
  // @behavior FS-010
700
1175
  #[test]
701
- fn an_overlay_leaves_a_read_only_layer_as_it_was() {
702
- let (overlay, lower) = overlay_on(Arc::new(Memory::new()));
1176
+ fn an_overlay_leaves_a_lower_layer_as_it_was() {
1177
+ let (overlay, lower) = overlay_on(Arc::new(Tmpfs::new()));
703
1178
  overwrite(&overlay, "dir/file", b"upper");
704
1179
  overlay
705
- .remove_file("dir/file")
1180
+ .vfs_unlink("dir/file")
706
1181
  .expect("the file must be removed");
707
1182
  assert_eq!(
708
- read(lower.as_ref(), "dir/file"),
1183
+ read(&on(&lower), "dir/file"),
709
1184
  b"lower",
710
- "a read-only Layer's file written and removed through an Overlay must stay as it was"
1185
+ "a lower Layer's file written and removed through an Overlay must stay as it was"
711
1186
  );
712
1187
  }
713
1188
 
714
1189
  // @behavior FS-011
715
1190
  #[test]
716
1191
  fn a_file_removed_through_an_overlay_is_gone_from_its_view() {
717
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1192
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
718
1193
  overlay
719
- .remove_file("dir/file")
1194
+ .vfs_unlink("dir/file")
720
1195
  .expect("the file must be removed");
721
1196
  assert_eq!(
722
- overlay.metadata("dir/file"),
723
- Err(FilesystemError::NotFound),
724
- "a lower file removed through Overlay::remove_file must no longer be found there"
725
- );
726
- }
727
-
728
- // @behavior FS-012
729
- #[test]
730
- fn an_overlay_over_a_temporary_starts_every_invocation_from_its_lower_layers() {
731
- let (overlay, _) = overlay_on(Arc::new(Temporary::new()));
732
- overwrite(&overlay, "dir/file", b"upper");
733
- let next = overlay
734
- .for_invocation()
735
- .expect("an Overlay over a Temporary must start each Invocation afresh");
736
- assert_eq!(
737
- read(next.as_ref(), "dir/file"),
738
- b"lower",
739
- "Overlay::for_invocation over a Temporary must hand the next Invocation the lower content"
1197
+ overlay.vfs_lstat("dir/file"),
1198
+ Err(Errno::NotFound),
1199
+ "a lower file removed through vfs_unlink must no longer be found there"
740
1200
  );
741
1201
  }
742
1202
 
743
1203
  // @behavior FS-013
744
1204
  #[test]
745
1205
  fn an_upper_layer_hides_the_same_path_in_a_lower_one() {
746
- let overlay = Overlay::new()
747
- .layer(memory_with("note", "upper"), Access::Read)
748
- .layer(memory_with("note", "lower"), Access::Read);
1206
+ let overlay = at(lowers(
1207
+ tmpfs_with("note", "upper"),
1208
+ tmpfs_with("note", "lower"),
1209
+ ));
749
1210
  assert_eq!(
750
1211
  read(&overlay, "note"),
751
1212
  b"upper",
@@ -755,267 +1216,571 @@ mod tests {
755
1216
 
756
1217
  // @behavior FS-014
757
1218
  #[test]
758
- fn a_write_to_a_writable_layers_file_changes_it_in_place() {
759
- let upper = Arc::new(Memory::new());
760
- let lower = memory_with("note", "lower");
761
- let overlay = Overlay::new()
762
- .layer(upper.clone(), Access::ReadWrite)
763
- .layer(lower.clone(), Access::ReadWrite);
1219
+ fn a_write_to_the_uppers_file_changes_it_in_place() {
1220
+ let upper = tmpfs_with("upper/note", "upper");
1221
+ let overlay = at(over(tmpfs_with("note", "lower"), upper.clone()));
764
1222
  overwrite(&overlay, "note", b"changed");
765
1223
  assert_eq!(
766
- (read(lower.as_ref(), "note"), upper.metadata("note")),
767
- (b"changed".to_vec(), Err(FilesystemError::NotFound)),
768
- "a writable lower Layer's file written through Overlay::open must change in that Layer alone"
1224
+ read(&on(&upper), "upper/note"),
1225
+ b"changed",
1226
+ "the upper's file written through Overlay::open must change in place"
769
1227
  );
770
1228
  }
771
1229
 
772
- // The lower Layer is writable, so only the refusal itself keeps the
773
- // move from landing in two Layers.
774
- // @behavior FS-088
1230
+ // @behavior FS-015
775
1231
  #[test]
776
- fn an_overlay_refuses_to_move_a_file_a_lower_writable_layer_holds() {
777
- let upper = Arc::new(Memory::new());
778
- let lower = memory_with("note", "lower");
779
- let overlay = Overlay::new()
780
- .layer(upper.clone(), Access::ReadWrite)
781
- .layer(lower.clone(), Access::ReadWrite);
1232
+ fn a_new_file_lands_in_the_upper() {
1233
+ let upper = Arc::new(Tmpfs::new());
1234
+ let lower = Arc::new(Tmpfs::new());
1235
+ let overlay = at(over(lower.clone(), upper.clone()));
1236
+ overwrite(&overlay, "new", b"made");
782
1237
  assert_eq!(
783
- (
784
- overlay.rename("note", "moved", Rename::File),
785
- read(lower.as_ref(), "note"),
786
- upper.read_dir("").map(|entries| entries.len())
787
- ),
788
- (Err(FilesystemError::CrossesDevices), b"lower".to_vec(), Ok(0)),
789
- "a file a lower writable Layer holds, renamed through Overlay::rename, must be refused \
790
- as crossing devices with nothing moved or copied"
1238
+ (read(&on(&upper), "upper/new"), on(&lower).vfs_lstat("new")),
1239
+ (b"made".to_vec(), Err(Errno::NotFound)),
1240
+ "a file created through Overlay::open must land in the upper alone"
791
1241
  );
792
1242
  }
793
1243
 
794
- // The writable Layer keeps the whiteout the removal left, so only a
795
- // call that answers by what landed rather than by the clean-up after
796
- // it succeeds.
797
- // @behavior FS-089
1244
+ // @behavior FS-016
798
1245
  #[test]
799
- fn an_overlay_change_that_lands_succeeds_though_its_whiteout_stays() {
800
- let (overlay, _) = overlay_on(Arc::new(KeepsWhiteouts(Memory::new())));
1246
+ fn a_removal_leaves_a_whiteout_in_the_upper() {
1247
+ let upper = Arc::new(Tmpfs::new());
1248
+ let (overlay, _) = overlay_on(upper.clone());
801
1249
  overlay
802
- .remove_file("dir/file")
1250
+ .vfs_unlink("dir/file")
803
1251
  .expect("the file must be removed");
804
1252
  assert_eq!(
805
- write(&overlay, "dir/file", b"again").map(|()| read(&overlay, "dir/file")),
806
- Ok(b"again".to_vec()),
807
- "a file made again through Overlay::open where it was removed, while the writable \
808
- Layer refuses to remove the whiteout, must succeed and show the new file"
1253
+ on(&upper)
1254
+ .vfs_lstat("upper/dir/file")
1255
+ .map(|metadata| metadata.file_type),
1256
+ Ok(FileType::Chrdev),
1257
+ "a lower Layer's file removed through vfs_unlink must leave a whiteout, a \
1258
+ device of no kind the guest opens, at its name in the upper"
809
1259
  );
810
1260
  }
811
1261
 
812
- // @behavior FS-015
1262
+ // The Layer changes behind the view between the lookup and the listing, so
1263
+ // only Layers bound as the name is found keep the directory it found, as
1264
+ // they cannot be taken for another one by a move in that window.
1265
+ // @behavior FS-165
813
1266
  #[test]
814
- fn a_new_file_lands_in_the_topmost_writable_layer() {
815
- let first = Arc::new(Memory::new());
816
- let second = Arc::new(Memory::new());
817
- let overlay = Overlay::new()
818
- .layer(Arc::new(Memory::new()), Access::Read)
819
- .layer(first.clone(), Access::ReadWrite)
820
- .layer(second.clone(), Access::ReadWrite);
821
- overwrite(&overlay, "new", b"made");
1267
+ fn a_directory_found_stands_for_the_layers_it_was_found_in() {
1268
+ use crate::vfs::lookup_one_unlocked;
1269
+ let lower = Arc::new([("dir/old", "x")].into_iter().collect::<Tmpfs>());
1270
+ let overlay = Arc::new(over(lower.clone(), Arc::new(Tmpfs::new())));
1271
+ let filesystem = Filesystem::new(overlay.clone()).expect("the instance must stand");
1272
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1273
+ let dir = lookup_one_unlocked(&Default::default(), &filesystem, &root, "dir")
1274
+ .expect("the directory must be found");
1275
+ let layer = on(&lower);
1276
+ layer
1277
+ .rename("dir", &layer, "moved")
1278
+ .expect("the Layer's directory must move");
1279
+ layer.vfs_mkdir("dir").expect("another must be made");
1280
+ overwrite(&layer, "dir/new", b"y");
1281
+ let names: Vec<String> = overlay
1282
+ .fs
1283
+ .dir_read_merged(
1284
+ &overlay
1285
+ .fs
1286
+ .dir(&dir)
1287
+ .expect("the directory must stand")
1288
+ .level(),
1289
+ )
1290
+ .expect("the directory must list")
1291
+ .into_iter()
1292
+ .map(|entry| entry.name)
1293
+ .collect();
822
1294
  assert_eq!(
823
- (read(first.as_ref(), "new"), second.metadata("new")),
824
- (b"made".to_vec(), Err(FilesystemError::NotFound)),
825
- "a file created through Overlay::open must land in the topmost writable Layer"
1295
+ names,
1296
+ ["old"],
1297
+ "OverlayFs::dir_read_merged of a directory OverlayFs found before its Layer changed must list \
1298
+ the Layer's directory found with it"
826
1299
  );
827
1300
  }
828
1301
 
829
- // @behavior FS-016
1302
+ // What fails after the exchange only a second writer's use of the inodes
1303
+ // can force, so the exchange is called alone: the next walk must find the
1304
+ // empty directory rather than the dentry whose upper no longer matches.
1305
+ // @behavior FS-164
830
1306
  #[test]
831
- fn a_removal_leaves_a_whiteout_in_the_topmost_writable_layer() {
832
- let upper = Arc::new(Memory::new());
833
- let (overlay, _) = overlay_on(upper.clone());
834
- overlay
835
- .remove_file("dir/file")
1307
+ fn a_directory_emptied_for_its_removal_stays_empty_should_the_removal_fail() {
1308
+ use crate::vfs::{lookup_one_unlocked, vfs_unlink};
1309
+ let lower = Arc::new([("dir/file", "x")].into_iter().collect::<Tmpfs>());
1310
+ let overlay = Arc::new(over(lower, Arc::new(Tmpfs::new())));
1311
+ let filesystem = Filesystem::new(overlay.clone()).expect("the instance must stand");
1312
+ let root = filesystem.root().expect(crate::vfs::MADE_ROOT).clone();
1313
+ let dir = lookup_one_unlocked(&Default::default(), &filesystem, &root, "dir")
1314
+ .expect("the directory must be found");
1315
+ let file = lookup_one_unlocked(&Default::default(), &filesystem, &dir, "file")
1316
+ .expect("the file must be found");
1317
+ vfs_unlink(&Default::default(), &filesystem, &dir, &file)
836
1318
  .expect("the file must be removed");
1319
+ let upper_root = overlay.fs.dir(&root).expect("the root must stand").level()[0]
1320
+ .clone()
1321
+ .expect("the upper shows the root");
1322
+ overlay
1323
+ .fs
1324
+ .clear_empty(&upper_root, "dir")
1325
+ .expect("the directory must be exchanged");
1326
+ let walked = lookup_one_unlocked(&Default::default(), &filesystem, &root, "dir")
1327
+ .expect("the directory must be found again");
1328
+ let names = overlay.fs.dir_read_merged(
1329
+ &overlay
1330
+ .fs
1331
+ .dir(&walked)
1332
+ .expect("the directory must stand")
1333
+ .level(),
1334
+ );
837
1335
  assert_eq!(
838
- upper.metadata("dir/.wh.file").map(|metadata| metadata.file_type),
839
- Ok(FileType::File),
840
- "a read-only Layer's file removed through Overlay::remove_file must leave .wh.file beside it in the writable Layer"
1336
+ names.map(|entries| entries.len()),
1337
+ Ok(0),
1338
+ "OverlayFs::dir_read_merged of a directory found by a walk after OverlayFs::clear_empty \
1339
+ replaced it must show nothing of the lower Layer below it"
841
1340
  );
842
1341
  }
843
1342
 
844
1343
  // @behavior FS-017
845
1344
  #[test]
846
- fn a_whiteout_lasts_as_long_as_its_writable_layer() {
847
- let upper = Arc::new(Memory::new());
1345
+ fn a_whiteout_lasts_as_long_as_the_upper() {
1346
+ let upper = Arc::new(Tmpfs::new());
848
1347
  let (overlay, lower) = overlay_on(upper.clone());
849
1348
  overlay
850
- .remove_file("dir/file")
1349
+ .vfs_unlink("dir/file")
851
1350
  .expect("the file must be removed");
852
- let rebuilt = Overlay::new()
853
- .layer(upper, Access::ReadWrite)
854
- .layer(lower, Access::Read);
1351
+ let rebuilt = at(over(lower, upper));
855
1352
  assert_eq!(
856
- rebuilt.metadata("dir/file"),
857
- Err(FilesystemError::NotFound),
858
- "a lower file removed through an Overlay over a Memory must stay gone from a new Overlay over the same Layers"
1353
+ rebuilt.vfs_lstat("dir/file"),
1354
+ Err(Errno::NotFound),
1355
+ "a lower file removed through an Overlay over a Tmpfs must stay gone from a new Overlay over the same Layers"
859
1356
  );
860
1357
  }
861
1358
 
862
1359
  // @behavior FS-018
863
1360
  #[test]
864
1361
  fn a_directory_made_again_where_one_was_removed_shows_nothing_from_below() {
865
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1362
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
866
1363
  overlay
867
- .remove_file("dir/file")
1364
+ .vfs_unlink("dir/file")
868
1365
  .expect("the file must be removed");
869
1366
  overlay
870
- .remove_dir("dir")
1367
+ .vfs_rmdir("dir")
871
1368
  .expect("the directory must be removed");
872
1369
  overlay
873
- .create_dir("dir")
1370
+ .vfs_mkdir("dir")
874
1371
  .expect("the directory must be made");
875
1372
  assert_eq!(
876
1373
  names(&overlay, "dir"),
877
1374
  Vec::<String>::new(),
878
- "a directory made again through Overlay::create_dir must list nothing from the read-only Layer"
1375
+ "a directory made again through vfs_mkdir must list nothing from the lower Layer"
879
1376
  );
880
1377
  }
881
1378
 
882
1379
  // @behavior FS-019
883
1380
  #[test]
884
1381
  fn an_overlay_lists_none_of_its_markers() {
885
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1382
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
886
1383
  overwrite(&overlay, "dir/new", b"made");
887
1384
  overlay
888
- .remove_file("dir/file")
1385
+ .vfs_unlink("dir/file")
889
1386
  .expect("the file must be removed");
890
1387
  assert_eq!(
891
1388
  names(&overlay, "dir"),
892
1389
  ["new"],
893
- "a directory holding a whiteout listed through Overlay::read_dir must show no .wh. entry"
1390
+ "a directory holding a whiteout listed through Overlay::read_dir must not list the \
1391
+ whited-out name"
894
1392
  );
895
1393
  }
896
1394
 
897
- // @behavior FS-020
1395
+ // Linux's `ovl_rename` answers ESTALE once the upper moved beneath it; the
1396
+ // view is undefined here, so the promise is only that the call answers,
1397
+ // and the bound turns a hang into a failure.
1398
+ // @behavior FS-204
1399
+ #[test]
1400
+ fn an_upper_changed_beside_its_overlay_still_answers() {
1401
+ use crate::vfs;
1402
+ let (overlay, upper) = beside_its_upper(
1403
+ [("upper/a/x", "x"), ("upper/a/k", "k")]
1404
+ .into_iter()
1405
+ .collect(),
1406
+ );
1407
+ let cred = Arc::default();
1408
+ vfs::vfs_fstatat(&cred, &overlay, "a/x", false).expect("a/x must stand");
1409
+ vfs::filename_renameat2(&cred, &upper, "upper/a", &upper, "upper/b")
1410
+ .expect("the upper's directory must move");
1411
+ let answered = crate::sched::testing::within_max_wait(|| {
1412
+ vfs::filename_renameat2(&cred, &overlay, "a/x", &overlay, "a/y").err()
1413
+ });
1414
+ assert_ne!(
1415
+ answered,
1416
+ Some(Errno::Interrupted),
1417
+ "vfs::filename_renameat2 through an Overlay whose upper another Mount changed must \
1418
+ answer within its bound"
1419
+ );
1420
+ }
1421
+
1422
+ // The lower Layer is a Tmpfs seen through a wrapper, so it reports the
1423
+ // device a whiteout is, yet is no Tmpfs whose marks the Overlay reads.
1424
+ // @behavior FS-203
898
1425
  #[test]
899
- fn an_overlay_refuses_a_name_reserved_for_its_markers() {
900
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1426
+ fn an_overlay_reads_a_whiteout_only_from_a_tmpfs() {
1427
+ let tmpfs = Tmpfs::new();
1428
+ tmpfs.whiteout("device").expect("the device must be made");
1429
+ let lower = Wrap::new(Arc::new(tmpfs), Arc::new(CountsLookups::default()));
1430
+ let overlay = at(over(Arc::new(lower), Arc::new(Tmpfs::new())));
901
1431
  assert_eq!(
902
- write(&overlay, "dir/.wh.note", b"x"),
903
- Err(FilesystemError::InvalidInput),
904
- "a file named .wh.note created through Overlay::open must be refused"
1432
+ (
1433
+ names(&overlay, ""),
1434
+ overlay.vfs_lstat("device").map(|found| found.file_type)
1435
+ ),
1436
+ (vec!["device".to_string()], Ok(FileType::Chrdev)),
1437
+ "a character device in a lower Layer that is no Tmpfs, listed and stated through an \
1438
+ Overlay, must be listed and found rather than read as a whiteout"
905
1439
  );
906
1440
  }
907
1441
 
908
- // A Layer folding case would hold `.WH.note` as the marker hiding `note`.
909
- // @behavior FS-056
1442
+ // A whiteout is a device rather than a name, so no name is the
1443
+ // Overlay's to reserve.
1444
+ // @behavior FS-020
910
1445
  #[test]
911
- fn an_overlay_refuses_its_reserved_name_in_any_case() {
912
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
1446
+ fn a_name_starting_with_wh_is_an_ordinary_name() {
1447
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
1448
+ overwrite(&overlay, "dir/.wh.file", b"made");
913
1449
  assert_eq!(
914
- write(&overlay, "dir/.WH.note", b"x"),
915
- Err(FilesystemError::InvalidInput),
916
- "a file named .WH.note created through Overlay::open must be refused"
1450
+ (read(&overlay, "dir/.wh.file"), read(&overlay, "dir/file")),
1451
+ (b"made".to_vec(), b"lower".to_vec()),
1452
+ "a file named .wh.file created through Overlay::open must be made, and must hide \
1453
+ nothing"
917
1454
  );
918
1455
  }
919
1456
 
1457
+ /// An Overlay of two lower Layers and no upper on a Mount allowing writes,
1458
+ /// and the root of that Mount.
1459
+ fn mounted_with_no_upper() -> (crate::mount::Mount, crate::vfs::Path) {
1460
+ let overlay = lowers(tmpfs_with("dir/file", "lower"), Arc::new(Tmpfs::new()));
1461
+ let mount = crate::mount::Mount::new(
1462
+ "/data",
1463
+ Filesystem::new(overlay).expect("the instance must stand"),
1464
+ crate::mount::Access::ReadWrite,
1465
+ )
1466
+ .expect("/data is a guest path");
1467
+ let root = crate::vfs::Path::root(mount.mnt());
1468
+ (mount, root)
1469
+ }
1470
+
920
1471
  // @behavior FS-021
921
1472
  #[test]
922
- fn an_overlay_with_no_writable_layer_refuses_every_change_as_read_only() {
923
- let overlay = Overlay::new().layer(memory_with("dir/file", "lower"), Access::Read);
1473
+ fn an_overlay_with_no_upper_refuses_every_change_as_read_only() {
1474
+ let (mount, root) = mounted_with_no_upper();
1475
+ let how = crate::vfs::OpenHow {
1476
+ write: true,
1477
+ ..Default::default()
1478
+ };
1479
+ let written = crate::vfs::kern_path::filp_open(&Arc::default(), &root, "dir/file", &how);
924
1480
  assert_eq!(
925
- write(&overlay, "dir/file", b"x"),
926
- Err(FilesystemError::ReadOnlyFilesystem),
927
- "a file written through an Overlay of read-only Layers must be refused as read-only"
1481
+ (written.err(), mount.mnt().is_readonly()),
1482
+ (Some(Errno::ReadOnlyFilesystem), true),
1483
+ "a file opened to write through an Overlay with no upper on a read-write Mount must \
1484
+ be refused as read-only"
928
1485
  );
929
1486
  }
930
1487
 
1488
+ /// A Layer holding a name past what it can hold, as a Layer on a host with
1489
+ /// a shorter limit answers one.
1490
+ struct RefusesLongName;
1491
+
1492
+ impl crate::filesystem::wrap::Hook for RefusesLongName {
1493
+ fn lookup(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Lookup, Errno> {
1494
+ match dentry.name().as_str() {
1495
+ "long" => Err(Errno::InvalidFilename),
1496
+ _ => inner.lookup(dentry),
1497
+ }
1498
+ }
1499
+ }
1500
+
1501
+ // `ovl_lookup_single` moves on from ENAMETOOLONG, so a name one Layer cannot
1502
+ // hold is only absent there, and the upper takes it.
1503
+ // @behavior FS-174
931
1504
  #[test]
932
- fn an_overlay_lists_every_layer_without_what_it_hid() {
933
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
934
- overwrite(&overlay, "dir/new", b"made");
935
- assert_eq!(names(&overlay, "dir"), ["file", "new"]);
1505
+ fn a_name_too_long_for_a_lower_layer_lands_in_the_upper() {
1506
+ let lower =
1507
+ crate::filesystem::wrap::Wrap::new(Arc::new(Tmpfs::new()), Arc::new(RefusesLongName));
1508
+ let upper = Arc::new(Tmpfs::new());
1509
+ let overlay = at(over(Arc::new(lower), upper.clone()));
1510
+ assert_eq!(
1511
+ (
1512
+ overlay.vfs_mkdir("long"),
1513
+ on(&upper)
1514
+ .vfs_lstat("upper/long")
1515
+ .map(|found| found.file_type)
1516
+ ),
1517
+ (Ok(()), Ok(FileType::Dir)),
1518
+ "a directory made through an Overlay at a name a lower Layer answers ENAMETOOLONG for \
1519
+ must land in the upper"
1520
+ );
936
1521
  }
937
1522
 
1523
+ // Replacing the target needs an inode only where it holds whiteouts to clear
1524
+ // away, so with none left only a rename leaving an empty one alone lands.
1525
+ // @behavior FS-175
938
1526
  #[test]
939
- fn a_lower_file_renamed_through_an_overlay_moves_into_the_writable_layer() {
940
- let upper = Arc::new(Memory::new());
941
- let (overlay, lower) = overlay_on(upper.clone());
1527
+ fn a_rename_onto_an_empty_upper_directory_builds_no_replacement() {
1528
+ let upper = Arc::new(Tmpfs::new().with_nr_inodes(Some(5)));
1529
+ let lower: Tmpfs = [("base", "x")].into_iter().collect();
1530
+ let overlay = at(over(Arc::new(lower), upper));
1531
+ overlay.vfs_mkdir("from").expect("the source must be made");
1532
+ overlay.vfs_mkdir("to").expect("the target must be made");
1533
+ assert_eq!(
1534
+ overlay.rename("from", &overlay, "to"),
1535
+ Ok(()),
1536
+ "a rename through an Overlay of an upper directory onto an empty upper directory, with \
1537
+ no inode left in the upper, must land, as ovl_rename_upper clears only what holds \
1538
+ whiteouts"
1539
+ );
1540
+ }
1541
+
1542
+ // overlayfs's `ovl_path_lower` is the topmost lower layer, and its stat of a
1543
+ // merged directory is the real one's, so a Layer's entries change the size.
1544
+ // @behavior FS-176
1545
+ #[test]
1546
+ fn a_merged_directory_reports_its_topmost_layer_under_the_lowers_identity() {
1547
+ let lower: Arc<Tmpfs> = Arc::new([("dir/a", "x"), ("dir/b", "x")].into_iter().collect());
1548
+ let upper = Arc::new(Tmpfs::new());
1549
+ let overlay = at(over(lower.clone(), upper));
942
1550
  overlay
943
- .rename("dir/file", "dir/moved", Rename::Any)
944
- .expect("the file must move");
1551
+ .vfs_mkdir("dir/made")
1552
+ .expect("the directory must be made");
1553
+ let found = overlay.vfs_lstat("dir").expect("the directory must stand");
1554
+ let below = on(&lower)
1555
+ .vfs_lstat("dir")
1556
+ .expect("the directory must stand");
1557
+ assert_eq!(
1558
+ (found.ino, found.dev, found.nlink, found.size),
1559
+ (below.ino, below.dev, 1, 3 * 20),
1560
+ "a directory two Layers show, stated through an Overlay, must report the lower \
1561
+ Layer's identity, one name, and the size of the upper's directory holding one entry"
1562
+ );
1563
+ }
1564
+
1565
+ // Bind reports the same identity for both names, so without the view keeping
1566
+ // them apart the VFS would answer the move as having nothing to do.
1567
+ // @behavior FS-170
1568
+ #[cfg(unix)]
1569
+ #[test]
1570
+ fn a_lower_layers_hard_link_moves_onto_the_other_as_two_entries() {
1571
+ let host = LinkTree::new("hard-link");
1572
+ std::fs::write(host.0.join("a"), "one").expect("the host file must be written");
1573
+ std::fs::hard_link(host.0.join("a"), host.0.join("b")).expect("the host link must be made");
1574
+ let overlay = at(over(Arc::new(host.bind()), Arc::new(Tmpfs::new())));
1575
+ write(&overlay, "a", b"two").expect("the file must copy up and be written");
1576
+ overlay
1577
+ .rename("a", &overlay, "b")
1578
+ .expect("the move must land");
945
1579
  assert_eq!(
946
1580
  (
947
- read(&overlay, "dir/moved"),
948
- overlay.metadata("dir/file"),
949
- read(lower.as_ref(), "dir/file"),
1581
+ overlay.vfs_lstat("a").map(drop),
1582
+ read(&overlay, "b"),
1583
+ std::fs::read(host.0.join("b")).expect("the host file must be read"),
950
1584
  ),
1585
+ (Err(Errno::NotFound), b"two".to_vec(), b"one".to_vec()),
1586
+ "a hard link in a lower Layer written and moved onto its other name through an \
1587
+ Overlay must leave only the new name, holding what was written, and the lower Layer \
1588
+ as it was"
1589
+ );
1590
+ }
1591
+
1592
+ // overlayfs's super block is read-only with no upper, so `mnt_want_write`
1593
+ // answers before anything looks at what stands at the name.
1594
+ // @behavior FS-169
1595
+ #[test]
1596
+ fn an_overlay_with_no_upper_refuses_a_change_before_what_stands_answers() {
1597
+ use crate::vfs::{filename_renameat2, filename_rmdir, filename_unlinkat};
1598
+ let (_mount, root) = mounted_with_no_upper();
1599
+ let cred = Arc::default();
1600
+ let read_only = || Err(Errno::ReadOnlyFilesystem);
1601
+ assert_eq!(
951
1602
  (
952
- b"lower".to_vec(),
953
- Err(FilesystemError::NotFound),
954
- b"lower".to_vec()
1603
+ filename_renameat2(&cred, &root, "dir/file", &root, "dir/file"),
1604
+ filename_unlinkat(&cred, &root, "missing"),
1605
+ filename_rmdir(&cred, &root, "dir"),
955
1606
  ),
1607
+ (read_only(), read_only(), read_only()),
1608
+ "a move onto its own name, a removal of nothing, and a removal of a directory holding \
1609
+ an entry through an Overlay with no upper must each answer EROFS"
956
1610
  );
957
1611
  }
958
1612
 
959
- /// A Memory that, the first time it lists a directory, starts another
960
- /// call through `overlay` on a thread of its own and gives it a while
961
- /// to finish, recording whether it did before this call returned.
962
- struct Interleaves {
963
- memory: Memory,
964
- overlay: Mutex<Option<Overlay>>,
965
- finished_inside: Mutex<Option<bool>>,
966
- other: Mutex<Option<thread::JoinHandle<()>>>,
1613
+ /// Why `Overlay::new` refuses `lower` under `upper`, or `None`.
1614
+ fn refusal(
1615
+ lower: Vec<Arc<dyn FileSystemType>>,
1616
+ upper: Option<Arc<dyn FileSystemType>>,
1617
+ ) -> Option<Errno> {
1618
+ let instance = |fs| Filesystem::new(fs).expect("the instance must stand");
1619
+ Overlay::new(
1620
+ lower.into_iter().map(instance).collect(),
1621
+ upper.map(instance),
1622
+ )
1623
+ .err()
967
1624
  }
968
1625
 
969
- impl Filesystem for Interleaves {
970
- holds_no_links!();
971
- never_repeats_identities!();
972
- is_shared!();
973
- matches_names_exactly!();
974
-
975
- fn open(
976
- &self,
977
- path: &str,
978
- options: &OpenOptions,
979
- ) -> Result<Box<dyn File>, FilesystemError> {
980
- self.memory.open(path, options)
981
- }
1626
+ // gVisor takes only an upper that holds its markers, and only a
1627
+ // Tmpfs does here.
1628
+ // @behavior FS-123
1629
+ #[test]
1630
+ fn an_overlay_refuses_an_upper_that_is_no_tmpfs() {
1631
+ let host = std::env::temp_dir();
1632
+ let bind = super::super::Bind::new(&host).expect("the host directory must open");
1633
+ assert_eq!(
1634
+ refusal(vec![Arc::new(Tmpfs::new())], Some(Arc::new(bind))),
1635
+ Some(Errno::InvalidInput),
1636
+ "Overlay::new with a Bind as its upper must be refused as invalid input"
1637
+ );
1638
+ }
982
1639
 
983
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
984
- self.memory.metadata(path)
985
- }
1640
+ // Nothing else tells these apart: every other rule holds of each list, and
1641
+ // a view over them would show the upper's own workdir.
1642
+ // @behavior FS-148
1643
+ #[test]
1644
+ fn an_overlay_refuses_one_instance_as_two_layers() {
1645
+ let instance = || Filesystem::new(Tmpfs::new()).expect("the instance must stand");
1646
+ let (shared, doubled) = (instance(), instance());
1647
+ assert_eq!(
1648
+ (
1649
+ Overlay::new(vec![shared.clone()], Some(shared)).err(),
1650
+ Overlay::new(vec![doubled.clone(), doubled, instance()], None).err(),
1651
+ ),
1652
+ (Some(Errno::InvalidInput), Some(Errno::InvalidInput),),
1653
+ "Overlay::new with one instance as its upper and a lower Layer, or as two lower \
1654
+ Layers, must be refused as invalid input"
1655
+ );
1656
+ }
986
1657
 
987
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
988
- if let Some(overlay) = self.overlay.lock().unwrap().take() {
989
- let finished = Arc::new(AtomicUsize::new(0));
990
- let marker = finished.clone();
991
- let handle = thread::spawn(move || {
992
- let _ = write(&overlay, "dir/new", b"made");
993
- marker.store(1, Ordering::SeqCst);
994
- });
995
- let deadline = Instant::now() + Duration::from_millis(200);
996
- while finished.load(Ordering::SeqCst) == 0 && Instant::now() < deadline {
997
- thread::sleep(Duration::from_millis(5));
998
- }
999
- *self.finished_inside.lock().unwrap() = Some(finished.load(Ordering::SeqCst) == 1);
1000
- *self.other.lock().unwrap() = Some(handle);
1001
- }
1002
- self.memory.read_dir(path)
1003
- }
1658
+ // @behavior FS-124
1659
+ #[test]
1660
+ fn an_overlay_without_an_upper_needs_two_lower_layers() {
1661
+ assert_eq!(
1662
+ refusal(vec![Arc::new(Tmpfs::new())], None),
1663
+ Some(Errno::InvalidInput),
1664
+ "Overlay::new with one lower Layer and no upper must be refused as invalid input"
1665
+ );
1666
+ }
1004
1667
 
1005
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1006
- self.memory.create_dir(path)
1007
- }
1668
+ // Two Overlays deep is what Linux allows, so only a third is refused.
1669
+ // @behavior FS-126
1670
+ #[test]
1671
+ fn an_overlay_stacks_at_most_two_deep() {
1672
+ let first: Arc<dyn FileSystemType> =
1673
+ Arc::new(lowers(Arc::new(Tmpfs::new()), Arc::new(Tmpfs::new())));
1674
+ let second: Arc<dyn FileSystemType> = Arc::new(over(first.clone(), Arc::new(Tmpfs::new())));
1675
+ assert_eq!(
1676
+ (
1677
+ refusal(vec![first], Some(Arc::new(Tmpfs::new()))),
1678
+ refusal(vec![second], Some(Arc::new(Tmpfs::new())))
1679
+ ),
1680
+ (None, Some(Errno::InvalidInput)),
1681
+ "Overlay::new over an Overlay must make a view, and over an Overlay over an Overlay \
1682
+ must be refused as invalid input"
1683
+ );
1684
+ }
1008
1685
 
1009
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1010
- self.memory.remove_dir(path)
1011
- }
1686
+ // @behavior FS-127
1687
+ #[test]
1688
+ fn an_overlay_takes_at_most_five_hundred_lower_layers() {
1689
+ let layers = |count: usize| -> Vec<Arc<dyn FileSystemType>> {
1690
+ (0..count)
1691
+ .map(|_| Arc::new(Tmpfs::new()) as Arc<dyn FileSystemType>)
1692
+ .collect()
1693
+ };
1694
+ assert_eq!(
1695
+ (refusal(layers(500), None), refusal(layers(501), None)),
1696
+ (None, Some(Errno::InvalidInput)),
1697
+ "Overlay::new must take 500 lower Layers and refuse 501 as invalid input"
1698
+ );
1699
+ }
1012
1700
 
1013
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1014
- self.memory.remove_file(path)
1701
+ // @behavior FS-125
1702
+ #[test]
1703
+ fn an_overlay_needs_a_lower_layer() {
1704
+ assert_eq!(
1705
+ refusal(Vec::new(), Some(Arc::new(Tmpfs::new()))),
1706
+ Some(Errno::InvalidInput),
1707
+ "Overlay::new with an upper and no lower Layer must be refused as invalid input"
1708
+ );
1709
+ }
1710
+
1711
+ #[test]
1712
+ fn an_overlay_lists_every_layer_without_what_it_hid() {
1713
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
1714
+ overwrite(&overlay, "dir/new", b"made");
1715
+ assert_eq!(names(&overlay, "dir"), ["file", "new"]);
1716
+ }
1717
+
1718
+ #[test]
1719
+ fn a_lower_file_renamed_through_an_overlay_moves_into_the_upper() {
1720
+ let upper = Arc::new(Tmpfs::new());
1721
+ let (overlay, lower) = overlay_on(upper.clone());
1722
+ overlay
1723
+ .rename("dir/file", &overlay, "dir/moved")
1724
+ .expect("the file must move");
1725
+ assert_eq!(
1726
+ (
1727
+ read(&overlay, "dir/moved"),
1728
+ overlay.vfs_lstat("dir/file"),
1729
+ read(&on(&lower), "dir/file"),
1730
+ ),
1731
+ (b"lower".to_vec(), Err(Errno::NotFound), b"lower".to_vec()),
1732
+ );
1733
+ }
1734
+
1735
+ /// Another call through the VFS at `overlay`, started once on a thread
1736
+ /// of its own and given a while to finish, recording whether it did
1737
+ /// before the call starting it went on.
1738
+ #[derive(Default)]
1739
+ struct Interleave {
1740
+ overlay: Mutex<Option<crate::vfs::Path>>,
1741
+ finished_inside: Mutex<Option<bool>>,
1742
+ other: Mutex<Option<thread::JoinHandle<()>>>,
1743
+ }
1744
+
1745
+ impl Interleave {
1746
+ fn start(&self) {
1747
+ let Some(overlay) = self.overlay.lock().unwrap().take() else {
1748
+ return;
1749
+ };
1750
+ let finished = Arc::new(AtomicUsize::new(0));
1751
+ let marker = finished.clone();
1752
+ let handle = thread::spawn(move || {
1753
+ let how = crate::vfs::OpenHow {
1754
+ write: true,
1755
+ create: true,
1756
+ ..crate::vfs::OpenHow::default()
1757
+ };
1758
+ let _ =
1759
+ crate::vfs::kern_path::filp_open(&Arc::default(), &overlay, "dir/new", &how);
1760
+ marker.store(1, Ordering::SeqCst);
1761
+ });
1762
+ let deadline = Instant::now() + Duration::from_millis(200);
1763
+ while finished.load(Ordering::SeqCst) == 0 && Instant::now() < deadline {
1764
+ thread::sleep(Duration::from_millis(5));
1765
+ }
1766
+ *self.finished_inside.lock().unwrap() = Some(finished.load(Ordering::SeqCst) == 1);
1767
+ *self.other.lock().unwrap() = Some(handle);
1015
1768
  }
1769
+ }
1016
1770
 
1017
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1018
- self.memory.rename(from, to, rename)
1771
+ /// A Tmpfs whose directory beneath its root starts `Interleave` the first
1772
+ /// time one is listed, as a removal's emptiness check lists it.
1773
+ impl Hook for Interleave {
1774
+ fn open(
1775
+ &self,
1776
+ inner: &dyn InodeOperations,
1777
+ dentry: &Dentry,
1778
+ how: &OpenHow,
1779
+ ) -> Result<Box<dyn FileOperations>, Errno> {
1780
+ if dentry.file_type() == Ok(FileType::Dir) && !dentry.is_root() {
1781
+ self.start();
1782
+ }
1783
+ inner.open(dentry, how)
1019
1784
  }
1020
1785
  }
1021
1786
 
@@ -1025,113 +1790,112 @@ mod tests {
1025
1790
  // @behavior FS-037
1026
1791
  #[test]
1027
1792
  fn a_change_through_an_overlay_waits_for_the_one_in_progress() {
1028
- let upper = Arc::new(Interleaves {
1029
- memory: [("dir/.keep", "")].into_iter().collect(),
1030
- overlay: Mutex::new(None),
1031
- finished_inside: Mutex::new(None),
1032
- other: Mutex::new(None),
1033
- });
1034
- upper
1035
- .memory
1036
- .remove_file("dir/.keep")
1793
+ let tmpfs = tmpfs_with("dir/.keep", "");
1794
+ let interleave = Arc::new(Interleave::default());
1795
+ on(&tmpfs)
1796
+ .vfs_unlink("dir/.keep")
1037
1797
  .expect("the seed must go");
1038
- let overlay = Overlay::new().layer(upper.clone(), Access::ReadWrite);
1039
- *upper.overlay.lock().unwrap() = Some(overlay.clone());
1040
- let removed = overlay.remove_dir("dir");
1041
- upper
1798
+ let mount = crate::mount::Mount::new(
1799
+ "/data",
1800
+ Filesystem::new(over(
1801
+ Arc::new(Wrap::new(tmpfs, interleave.clone())),
1802
+ Arc::new(Tmpfs::new()),
1803
+ ))
1804
+ .expect("the instance must stand"),
1805
+ crate::mount::Access::ReadWrite,
1806
+ )
1807
+ .expect("/data is a guest path");
1808
+ let root = crate::vfs::Path::root(mount.mnt());
1809
+ *interleave.overlay.lock().unwrap() = Some(root.clone());
1810
+ let removed = crate::vfs::filename_rmdir(&Arc::default(), &root, "dir").is_ok();
1811
+ let other = interleave
1042
1812
  .other
1043
1813
  .lock()
1044
1814
  .unwrap()
1045
1815
  .take()
1046
- .expect("the other call must have started")
1047
- .join()
1048
- .expect("the other call must not panic");
1816
+ .expect("the other call must have started");
1817
+ crate::sched::testing::join("the other call", other);
1049
1818
  assert_eq!(
1050
- (removed, *upper.finished_inside.lock().unwrap(), overlay.metadata("dir/new").is_ok()),
1051
- (Ok(()), Some(false), false),
1052
- "a change through Overlay::open started while Overlay::remove_dir runs must wait for it, \
1053
- failing rather than landing in the directory being removed"
1819
+ (
1820
+ removed,
1821
+ *interleave.finished_inside.lock().unwrap(),
1822
+ crate::vfs::vfs_fstatat(&Arc::default(), &root, "dir/new", false).is_ok()
1823
+ ),
1824
+ (true, Some(false), false),
1825
+ "a create through vfs::do_file_open into an Overlay directory vfs::filename_rmdir is removing must \
1826
+ wait for it, failing rather than landing in the directory being removed"
1054
1827
  );
1055
1828
  }
1056
1829
 
1057
1830
  // @behavior FS-038
1058
1831
  #[test]
1059
- fn a_call_through_an_overlay_from_inside_one_answers_a_deadlock() {
1832
+ fn a_change_through_an_overlay_from_inside_one_answers_a_deadlock() {
1833
+ type Answers = (bool, Result<(), Errno>);
1834
+
1060
1835
  struct Reenters {
1061
- memory: Memory,
1062
- overlay: Mutex<Option<Overlay>>,
1063
- answer: Mutex<Option<Result<Metadata, FilesystemError>>>,
1836
+ overlay: Mutex<Option<crate::vfs::Path>>,
1837
+ answer: Mutex<Option<Answers>>,
1064
1838
  }
1065
1839
 
1066
- impl Filesystem for Reenters {
1067
- holds_no_links!();
1068
- never_repeats_identities!();
1069
- is_shared!();
1070
- matches_names_exactly!();
1071
-
1072
- fn open(
1840
+ impl Hook for Reenters {
1841
+ fn getattr(
1073
1842
  &self,
1074
- path: &str,
1075
- options: &OpenOptions,
1076
- ) -> Result<Box<dyn File>, FilesystemError> {
1077
- self.memory.open(path, options)
1078
- }
1079
-
1080
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1081
- if let Some(overlay) = self.overlay.lock().unwrap().take() {
1082
- *self.answer.lock().unwrap() = Some(overlay.metadata(path));
1843
+ inner: &dyn InodeOperations,
1844
+ dentry: &Dentry,
1845
+ ) -> Result<Kstat, Errno> {
1846
+ let reentering = self.overlay.lock().unwrap().take();
1847
+ if let Some(overlay) = reentering {
1848
+ *self.answer.lock().unwrap() = Some((
1849
+ crate::vfs::vfs_fstatat(&Arc::default(), &overlay, &dentry.name(), false)
1850
+ .is_ok(),
1851
+ crate::vfs::filename_mkdirat(&Arc::default(), &overlay, "made"),
1852
+ ));
1083
1853
  }
1084
- self.memory.metadata(path)
1085
- }
1086
-
1087
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1088
- self.memory.read_dir(path)
1089
- }
1090
-
1091
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1092
- self.memory.create_dir(path)
1093
- }
1094
-
1095
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1096
- self.memory.remove_dir(path)
1097
- }
1098
-
1099
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1100
- self.memory.remove_file(path)
1101
- }
1102
-
1103
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1104
- self.memory.rename(from, to, rename)
1854
+ inner.getattr(dentry)
1105
1855
  }
1106
1856
  }
1107
1857
 
1108
1858
  let layer = Arc::new(Reenters {
1109
- memory: [("note", "x")].into_iter().collect(),
1110
1859
  overlay: Mutex::new(None),
1111
1860
  answer: Mutex::new(None),
1112
1861
  });
1113
- let overlay = Overlay::new().layer(layer.clone(), Access::Read);
1114
- *layer.overlay.lock().unwrap() = Some(overlay.clone());
1115
- overlay
1116
- .metadata("note")
1862
+ let tmpfs: Tmpfs = [("note", "x")].into_iter().collect();
1863
+ let mount = crate::mount::Mount::new(
1864
+ "/data",
1865
+ Filesystem::new(over(
1866
+ Arc::new(Wrap::new(Arc::new(tmpfs), layer.clone())),
1867
+ Arc::new(Tmpfs::new()),
1868
+ ))
1869
+ .expect("the instance must stand"),
1870
+ crate::mount::Access::ReadWrite,
1871
+ )
1872
+ .expect("/data is a guest path");
1873
+ let root = crate::vfs::Path::root(mount.mnt());
1874
+ *layer.overlay.lock().unwrap() = Some(root.clone());
1875
+ crate::vfs::vfs_fstatat(&Arc::default(), &root, "note", false)
1117
1876
  .expect("the outer call must answer");
1877
+ let answers = layer.answer.lock().unwrap().take();
1118
1878
  assert_eq!(
1119
- layer.answer.lock().unwrap().take(),
1120
- Some(Err(FilesystemError::Deadlock)),
1121
- "a call through an Overlay made from inside one of its own calls on the same thread \
1122
- must answer Deadlock rather than wait forever"
1879
+ answers,
1880
+ Some((true, Err(Errno::Deadlock))),
1881
+ "a read through an Overlay made from inside one of its own reads on the same thread \
1882
+ must answer, and a change must answer Deadlock rather than wait forever"
1123
1883
  );
1124
1884
  }
1125
1885
 
1126
- /// A writable Memory seeded with `files` and room for `inodes`, over a
1127
- /// read-only one holding `dir/file` = "lower".
1128
- fn full_over_lower(files: &[(&str, &str)], inodes: usize) -> (Overlay, Arc<Memory>) {
1129
- let upper = Memory::from_iter(files.iter().copied()).with_inodes(Some(inodes));
1886
+ /// An upper whose `upper` is seeded with `files`, with room for
1887
+ /// `inodes` more than its root, `upper`, and `work` take, over a lower
1888
+ /// Tmpfs holding `dir/file` = "lower".
1889
+ fn full_over_lower(files: &[(&str, &str)], inodes: usize) -> (KernPath, Arc<Tmpfs>) {
1890
+ let seeded = files
1891
+ .iter()
1892
+ .map(|(path, contents)| (format!("upper/{path}"), *contents));
1893
+ let upper = Tmpfs::from_iter(seeded).with_nr_inodes(Some(inodes + 3));
1130
1894
  let upper = Arc::new(upper);
1131
- let overlay = Overlay::new()
1132
- .layer(upper.clone(), Access::ReadWrite)
1133
- .layer(memory_with("dir/file", "lower"), Access::Read);
1134
- (overlay, upper)
1895
+ (
1896
+ at(over(tmpfs_with("dir/file", "lower"), upper.clone())),
1897
+ upper,
1898
+ )
1135
1899
  }
1136
1900
 
1137
1901
  // The upper copy is all the room there is, so the whiteout cannot be
@@ -1139,32 +1903,34 @@ mod tests {
1139
1903
  // @behavior FS-040
1140
1904
  #[test]
1141
1905
  fn a_removal_that_cannot_leave_its_whiteout_removes_nothing() {
1142
- let (overlay, _) = full_over_lower(&[("dir/file", "upper")], 3);
1906
+ let (overlay, _) = full_over_lower(&[("dir/file", "upper")], 2);
1143
1907
  assert_eq!(
1144
- (overlay.remove_file("dir/file"), read(&overlay, "dir/file")),
1145
- (Err(FilesystemError::StorageFull), b"upper".to_vec()),
1146
- "a file removed through Overlay::remove_file whose whiteout finds no room must stay as \
1908
+ (overlay.vfs_unlink("dir/file"), read(&overlay, "dir/file")),
1909
+ (Err(Errno::StorageFull), b"upper".to_vec()),
1910
+ "a file removed through vfs_unlink whose whiteout finds no room must stay as \
1147
1911
  it was"
1148
1912
  );
1149
1913
  }
1150
1914
 
1915
+ // The directory is built in the workdir before it replaces the
1916
+ // whiteout, so a workdir with no room leaves the whiteout standing.
1151
1917
  // @behavior FS-041
1152
1918
  #[test]
1153
- fn a_directory_that_cannot_be_marked_opaque_is_not_made() {
1154
- let (overlay, upper) = full_over_lower(&[(".wh.dir", "")], 3);
1919
+ fn a_directory_made_over_a_whiteout_without_room_is_not_made() {
1920
+ let lower = Arc::new(Tmpfs::new());
1921
+ on(&lower)
1922
+ .vfs_mkdir("gone")
1923
+ .expect("the directory must be made");
1924
+ let upper = Arc::new(Tmpfs::new().with_nr_inodes(Some(4)));
1925
+ let overlay = at(over(lower, upper));
1926
+ overlay
1927
+ .vfs_rmdir("gone")
1928
+ .expect("the directory must be removed");
1155
1929
  assert_eq!(
1156
- (
1157
- overlay.create_dir("dir"),
1158
- overlay.metadata("dir"),
1159
- upper.metadata("dir")
1160
- ),
1161
- (
1162
- Err(FilesystemError::StorageFull),
1163
- Err(FilesystemError::NotFound),
1164
- Err(FilesystemError::NotFound)
1165
- ),
1166
- "a directory made through Overlay::create_dir where one was removed, with no room for \
1167
- its opaque marker, must not be made, nor its whiteout lifted"
1930
+ (overlay.vfs_mkdir("gone"), overlay.vfs_lstat("gone")),
1931
+ (Err(Errno::StorageFull), Err(Errno::NotFound)),
1932
+ "a directory made through vfs_mkdir over a whiteout, with no room left, \
1933
+ must be refused as out of space and leave the name hidden"
1168
1934
  );
1169
1935
  }
1170
1936
 
@@ -1173,16 +1939,16 @@ mod tests {
1173
1939
  // @behavior FS-042
1174
1940
  #[test]
1175
1941
  fn a_rename_that_cannot_leave_its_whiteout_moves_nothing() {
1176
- let (overlay, _) = full_over_lower(&[], 3);
1942
+ let (overlay, _) = full_over_lower(&[], 2);
1177
1943
  assert_eq!(
1178
1944
  (
1179
- overlay.rename("dir/file", "dir/moved", Rename::Any),
1180
- overlay.metadata("dir/moved"),
1945
+ overlay.rename("dir/file", &overlay, "dir/moved"),
1946
+ overlay.vfs_lstat("dir/moved"),
1181
1947
  read(&overlay, "dir/file")
1182
1948
  ),
1183
1949
  (
1184
- Err(FilesystemError::StorageFull),
1185
- Err(FilesystemError::NotFound),
1950
+ Err(Errno::StorageFull),
1951
+ Err(Errno::NotFound),
1186
1952
  b"lower".to_vec()
1187
1953
  ),
1188
1954
  "a file renamed through Overlay::rename whose whiteout finds no room must stay where \
@@ -1190,204 +1956,257 @@ mod tests {
1190
1956
  );
1191
1957
  }
1192
1958
 
1193
- // The lower writable copy still holds the file the upper whiteout
1194
- // hides, so it cannot be removed; removing the upper copy first would
1195
- // show the file again.
1196
- // @behavior FS-074
1959
+ // @behavior FS-043
1197
1960
  #[test]
1198
- fn a_directory_a_lower_writable_layer_still_fills_is_removed_behind_a_whiteout() {
1199
- let lower = memory_with("dir/file", "lower");
1200
- let overlay = Overlay::new()
1201
- .layer(memory_with("dir/.wh.file", ""), Access::ReadWrite)
1202
- .layer(lower.clone(), Access::ReadWrite);
1961
+ fn a_directory_a_lower_layer_holds_does_not_move_through_an_overlay() {
1962
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::new()));
1203
1963
  assert_eq!(
1204
1964
  (
1205
- overlay.remove_dir("dir"),
1206
- overlay.metadata("dir").err(),
1207
- read(lower.as_ref(), "dir/file")
1965
+ overlay.rename("dir", &overlay, "moved"),
1966
+ overlay.vfs_lstat("moved")
1208
1967
  ),
1209
- (Ok(()), Some(FilesystemError::NotFound), b"lower".to_vec()),
1210
- "a directory the view shows empty, removed through Overlay::remove_dir while a lower \
1211
- writable Layer still holds a whited-out file in it, must leave the view and stay \
1212
- below unseen"
1968
+ (Err(Errno::CrossesDevices), Err(Errno::NotFound)),
1969
+ "a directory a lower Layer holds renamed through Overlay::rename must be refused \
1970
+ as crossing devices, as overlayfs refuses it"
1213
1971
  );
1214
1972
  }
1215
1973
 
1216
- // The marker is the one entry past the room the upper Layer has, so
1217
- // marking after the move would leave the directory moved.
1218
- // @behavior FS-075
1974
+ // The directory shows only from the lower Layer, so only a check of
1975
+ // the whole view finds it in the way.
1976
+ // @behavior FS-044
1219
1977
  #[test]
1220
- fn a_rename_that_cannot_mark_its_directory_opaque_moves_nothing() {
1221
- let upper = Arc::new(Memory::new().with_inodes(Some(2)));
1222
- upper
1223
- .create_dir("moving")
1978
+ fn a_rename_onto_what_an_overlay_shows_is_checked_against_the_view() {
1979
+ let upper = Arc::new(Tmpfs::new());
1980
+ let (overlay, _) = overlay_on(upper.clone());
1981
+ overwrite(&overlay, "note", b"x");
1982
+ overlay
1983
+ .vfs_mkdir("empty")
1224
1984
  .expect("the directory must be made");
1225
- let lower = Arc::new(Memory::new());
1226
- lower.create_dir("dir").expect("the directory must be made");
1227
- let overlay = Overlay::new()
1228
- .layer(upper.clone(), Access::ReadWrite)
1229
- .layer(lower, Access::Read);
1230
1985
  assert_eq!(
1231
1986
  (
1232
- overlay.rename("moving", "dir", Rename::Directory),
1233
- upper.metadata("moving").map(|metadata| metadata.file_type),
1234
- upper.metadata("dir").err()
1987
+ overlay.rename("note", &overlay, "dir"),
1988
+ overlay.rename("empty", &overlay, "dir"),
1989
+ read(&overlay, "dir/file")
1235
1990
  ),
1236
1991
  (
1237
- Err(FilesystemError::StorageFull),
1238
- Ok(FileType::Directory),
1239
- Some(FilesystemError::NotFound)
1992
+ Err(Errno::IsADirectory),
1993
+ Err(Errno::DirectoryNotEmpty),
1994
+ b"lower".to_vec()
1240
1995
  ),
1241
- "a directory renamed through Overlay::rename over one a lower Layer holds, with no \
1242
- room for its opaque marker, must stay where it was"
1996
+ "a rename through Overlay::rename onto a directory only a lower Layer shows must \
1997
+ be refused as rename(2) refuses it, leaving that directory as it was"
1243
1998
  );
1244
1999
  }
1245
2000
 
1246
- // The writable Layer sits between two read-only ones, so a rename
1247
- // landing in it beneath the top Layer's `to` would vanish from view.
1248
- // @behavior FS-076
2001
+ // A directory moved over an empty one a lower Layer holds must not take
2002
+ // up what that Layer later shows there.
2003
+ // @behavior FS-045
1249
2004
  #[test]
1250
- fn a_rename_a_read_only_layer_above_would_cover_is_refused() {
1251
- let overlay = Overlay::new()
1252
- .layer(memory_with("to", "top"), Access::Read)
1253
- .layer(Arc::new(Memory::new()), Access::ReadWrite)
1254
- .layer(memory_with("from", "moved"), Access::Read);
2005
+ fn a_directory_moved_over_a_lower_one_is_marked_opaque() {
2006
+ let upper = Arc::new(Tmpfs::new());
2007
+ let lower: Arc<Tmpfs> = Arc::new([("dir/.keep", "")].into_iter().collect());
2008
+ on(&lower)
2009
+ .vfs_unlink("dir/.keep")
2010
+ .expect("the seed must go");
2011
+ let overlay = at(over(lower.clone(), upper.clone()));
2012
+ overlay
2013
+ .vfs_mkdir("made")
2014
+ .expect("the directory must be made");
2015
+ overlay
2016
+ .rename("made", &overlay, "dir")
2017
+ .expect("the directory must move over the empty one");
2018
+ overwrite(&on(&lower), "dir/later", b"lower");
1255
2019
  assert_eq!(
1256
- (
1257
- overlay.rename("from", "to", Rename::Any),
1258
- read(&overlay, "from"),
1259
- read(&overlay, "to")
1260
- ),
1261
- (
1262
- Err(FilesystemError::ReadOnlyFilesystem),
1263
- b"moved".to_vec(),
1264
- b"top".to_vec()
1265
- ),
1266
- "a file renamed through Overlay::rename onto a name a read-only Layer above the \
1267
- writable one holds must be refused as read-only and move nothing"
2020
+ names(&overlay, "dir"),
2021
+ Vec::<String>::new(),
2022
+ "a directory moved through Overlay::rename over one a lower Layer holds must be \
2023
+ marked opaque, so a file the lower Layer gains there later does not show"
1268
2024
  );
1269
2025
  }
1270
2026
 
1271
- // @behavior FS-077
2027
+ // A change is built in `work` before it lands, so `work` holds nothing
2028
+ // once each change is done, and only `upper` holds what the view shows.
2029
+ // @behavior FS-128
1272
2030
  #[test]
1273
- fn a_name_a_read_only_layer_above_hides_is_not_made() {
1274
- let upper = Arc::new(Memory::new());
1275
- let overlay = Overlay::new()
1276
- .layer(
1277
- Arc::new(
1278
- [(".wh.file", ""), (".wh.dir", "")]
1279
- .into_iter()
1280
- .collect::<Memory>(),
1281
- ),
1282
- Access::Read,
1283
- )
1284
- .layer(upper.clone(), Access::ReadWrite);
2031
+ fn an_overlay_keeps_its_changes_in_its_tmpfss_upper() {
2032
+ let upper = Arc::new(Tmpfs::new());
2033
+ let (overlay, _) = overlay_on(upper.clone());
2034
+ overwrite(&overlay, "dir/file", b"changed");
2035
+ overlay
2036
+ .vfs_unlink("dir/file")
2037
+ .expect("the file must be removed");
1285
2038
  assert_eq!(
2039
+ (names(&on(&upper), ""), names(&on(&upper), "work")),
1286
2040
  (
1287
- write(&overlay, "file", b"new"),
1288
- overlay.create_dir("dir"),
1289
- upper.metadata("file").err(),
1290
- upper.metadata("dir").err()
1291
- ),
1292
- (
1293
- Err(FilesystemError::ReadOnlyFilesystem),
1294
- Err(FilesystemError::ReadOnlyFilesystem),
1295
- Some(FilesystemError::NotFound),
1296
- Some(FilesystemError::NotFound)
2041
+ vec!["upper".to_string(), "work".to_string()],
2042
+ Vec::<String>::new()
1297
2043
  ),
1298
- "a file and a directory made through an Overlay where a read-only Layer above the \
1299
- writable one holds their whiteouts must be refused as read-only and not made"
2044
+ "an Overlay's upper Tmpfs, after a copy up and a removal through it, must hold only \
2045
+ upper and an empty work"
1300
2046
  );
1301
2047
  }
1302
2048
 
1303
- // @behavior FS-043
2049
+ // The upper's `dir` holds the whiteout the file's removal left, so only
2050
+ // clearing it before the removal lets what is exchanged out go.
2051
+ // @behavior FS-134
1304
2052
  #[test]
1305
- fn a_directory_a_lower_layer_holds_does_not_move_through_an_overlay() {
1306
- let (overlay, _) = overlay_on(Arc::new(Memory::new()));
2053
+ fn a_directory_removed_through_an_overlay_leaves_nothing_in_its_workdir() {
2054
+ let upper = Arc::new(Tmpfs::new());
2055
+ let (overlay, _) = overlay_on(upper.clone());
2056
+ overlay
2057
+ .vfs_unlink("dir/file")
2058
+ .expect("the file must be removed");
2059
+ overlay
2060
+ .vfs_rmdir("dir")
2061
+ .expect("the emptied directory must be removed");
1307
2062
  assert_eq!(
1308
- (
1309
- overlay.rename("dir", "moved", Rename::Any),
1310
- overlay.metadata("moved")
1311
- ),
1312
- (
1313
- Err(FilesystemError::CrossesDevices),
1314
- Err(FilesystemError::NotFound)
1315
- ),
1316
- "a directory a read-only Layer holds renamed through Overlay::rename must be refused \
1317
- as crossing devices, as overlayfs refuses it"
2063
+ (names(&on(&upper), "work"), kind(&overlay, "dir")),
2064
+ (Vec::<String>::new(), Err(Errno::NotFound)),
2065
+ "vfs_rmdir of a lower directory whose file vfs_unlink removed \
2066
+ must leave the upper Tmpfs's work empty and the directory gone"
1318
2067
  );
1319
2068
  }
1320
2069
 
1321
- // The directory shows only from the read-only Layer, so only a check of
1322
- // the whole view finds it in the way.
1323
- // @behavior FS-044
2070
+ // The open writes nothing, so only the copy taking the lower file's
2071
+ // times, rather than the time it was made, keeps them.
2072
+ // @behavior FS-129
1324
2073
  #[test]
1325
- fn a_rename_onto_what_an_overlay_shows_is_checked_against_the_view() {
1326
- let upper = Arc::new(Memory::new());
1327
- let (overlay, _) = overlay_on(upper.clone());
1328
- overwrite(&overlay, "note", b"x");
2074
+ fn a_copy_up_keeps_the_lower_files_times() {
2075
+ let lower = tmpfs_with("dir/file", "lower");
2076
+ let before = on(&lower)
2077
+ .vfs_lstat("dir/file")
2078
+ .expect("the lower file must stand");
2079
+ std::thread::sleep(Duration::from_millis(10));
2080
+ let overlay = at(over(lower, Arc::new(Tmpfs::new())));
1329
2081
  overlay
1330
- .create_dir("empty")
1331
- .expect("the directory must be made");
2082
+ .open(
2083
+ "dir/file",
2084
+ &OpenHow {
2085
+ write: true,
2086
+ ..OpenHow::default()
2087
+ },
2088
+ )
2089
+ .expect("the open must copy the file up");
1332
2090
  assert_eq!(
1333
- (
1334
- overlay.rename("note", "dir", Rename::Any),
1335
- overlay.rename("empty", "dir", Rename::Any),
1336
- read(&overlay, "dir/file")
1337
- ),
1338
- (
1339
- Err(FilesystemError::IsADirectory),
1340
- Err(FilesystemError::DirectoryNotEmpty),
1341
- b"lower".to_vec()
1342
- ),
1343
- "a rename through Overlay::rename onto a directory only a read-only Layer shows must \
1344
- be refused as rename(2) refuses it, leaving that directory as it was"
2091
+ overlay.vfs_lstat("dir/file").map(|stat| stat.mtime),
2092
+ Ok(before.mtime),
2093
+ "a lower file opened to write through Overlay::open, writing nothing, must keep the \
2094
+ lower file's modified time once copied up"
1345
2095
  );
1346
2096
  }
1347
2097
 
1348
- // A directory moved over an empty one a lower Layer holds must not take
1349
- // up what that Layer later shows there.
1350
- // @behavior FS-045
2098
+ // The second copy up lands in a directory the first made, so only
2099
+ // restoring its times leaves what the view reports unchanged.
2100
+ // @behavior FS-130
1351
2101
  #[test]
1352
- fn a_directory_moved_over_a_lower_one_is_marked_opaque() {
1353
- let upper = Arc::new(Memory::new());
1354
- let lower: Arc<Memory> = Arc::new([("dir/.keep", "")].into_iter().collect());
1355
- lower.remove_file("dir/.keep").expect("the seed must go");
1356
- let overlay = Overlay::new()
1357
- .layer(upper.clone(), Access::ReadWrite)
1358
- .layer(lower.clone(), Access::Read);
2102
+ fn a_copy_up_leaves_its_directorys_times_as_they_were() {
2103
+ let lower: Arc<Tmpfs> = Arc::new([("dir/a", "a"), ("dir/b", "b")].into_iter().collect());
2104
+ let overlay = at(over(lower, Arc::new(Tmpfs::new())));
2105
+ overwrite(&overlay, "dir/a", b"changed");
2106
+ let before = overlay
2107
+ .vfs_lstat("dir")
2108
+ .expect("the directory must stand")
2109
+ .mtime;
2110
+ std::thread::sleep(Duration::from_millis(10));
1359
2111
  overlay
1360
- .create_dir("made")
1361
- .expect("the directory must be made");
1362
- overlay
1363
- .rename("made", "dir", Rename::Any)
1364
- .expect("the directory must move over the empty one");
2112
+ .open(
2113
+ "dir/b",
2114
+ &OpenHow {
2115
+ write: true,
2116
+ ..OpenHow::default()
2117
+ },
2118
+ )
2119
+ .expect("the open must copy the file up");
1365
2120
  assert_eq!(
1366
- upper
1367
- .metadata("dir/.wh..wh..opq")
1368
- .map(|metadata| metadata.file_type),
1369
- Ok(FileType::File),
1370
- "a directory moved through Overlay::rename over one a read-only Layer holds must be \
1371
- marked opaque in the writable Layer"
2121
+ overlay.vfs_lstat("dir").map(|stat| stat.mtime),
2122
+ Ok(before),
2123
+ "a lower file copied up through Overlay::open into a directory the upper holds must \
2124
+ leave that directory's modified time as it was"
2125
+ );
2126
+ }
2127
+
2128
+ /// An Overlay over an empty lower Layer under the Tmpfs `upper`, and
2129
+ /// that same Tmpfs mounted on its own, each reached through the VFS.
2130
+ fn beside_its_upper(upper: Tmpfs) -> (crate::vfs::Path, crate::vfs::Path) {
2131
+ let upper = Filesystem::new(upper).expect("the instance must stand");
2132
+ let overlay = Overlay::new(
2133
+ vec![Filesystem::new(Tmpfs::new()).expect("the instance must stand")],
2134
+ Some(upper.clone()),
2135
+ )
2136
+ .expect("an upper over a lower Layer must make a view");
2137
+ let root = |filesystem| {
2138
+ let mount =
2139
+ crate::mount::Mount::new("/data", filesystem, crate::mount::Access::ReadWrite)
2140
+ .expect("/data is a guest path");
2141
+ crate::vfs::Path::root(mount.mnt())
2142
+ };
2143
+ (
2144
+ root(Filesystem::new(overlay).expect("the instance must stand")),
2145
+ root(upper),
2146
+ )
2147
+ }
2148
+
2149
+ // The move holds the directory it leaves and the one above it, and the
2150
+ // removal holds the same two, so only taking the one above first in
2151
+ // both keeps them from waiting on each other; unordered, they wait
2152
+ // within a few moves.
2153
+ // @behavior FS-131
2154
+ #[test]
2155
+ fn an_overlay_and_a_mount_of_its_upper_never_wait_on_each_other() {
2156
+ let (overlay, upper) = beside_its_upper(
2157
+ [("upper/a/b/c", "c"), ("upper/a/b/keep", "")]
2158
+ .into_iter()
2159
+ .collect(),
2160
+ );
2161
+ let moved = Arc::new(AtomicBool::new(false));
2162
+ let removing = {
2163
+ let moved = moved.clone();
2164
+ thread::spawn(move || {
2165
+ while !moved.load(Ordering::SeqCst) {
2166
+ let _ = crate::vfs::filename_rmdir(&Arc::default(), &upper, "upper/a/b");
2167
+ }
2168
+ })
2169
+ };
2170
+ let (done, finished) = std::sync::mpsc::channel();
2171
+ thread::spawn(move || {
2172
+ for _ in 0..500 {
2173
+ crate::vfs::filename_renameat2(&Arc::default(), &overlay, "a/b/c", &overlay, "a/c")
2174
+ .expect("the file must move up");
2175
+ crate::vfs::filename_renameat2(&Arc::default(), &overlay, "a/c", &overlay, "a/b/c")
2176
+ .expect("the file must move back");
2177
+ }
2178
+ let _ = done.send(());
2179
+ });
2180
+ let returned = finished
2181
+ .recv_timeout(crate::sched::testing::MAX_WAIT)
2182
+ .is_ok();
2183
+ moved.store(true, Ordering::SeqCst);
2184
+ if returned {
2185
+ crate::sched::testing::join("the removal", removing);
2186
+ }
2187
+ assert!(
2188
+ returned,
2189
+ "vfs::filename_renameat2 of a file up one directory through an Overlay, while vfs::filename_rmdir \
2190
+ removes that directory through a Mount of its upper Tmpfs, must return"
1372
2191
  );
1373
2192
  }
1374
2193
 
1375
- // The writable Layer has room for the copy's entry but for less than
2194
+ // The upper has room for the copy's entry but for less than
1376
2195
  // the lower file's bytes, so the copy fails part way.
1377
2196
  // @behavior FS-046
1378
2197
  #[test]
1379
2198
  fn a_copy_up_that_fails_part_way_leaves_nothing_behind() {
1380
- let upper = Arc::new(Memory::new().with_limit(Some(2)).with_inodes(Some(8)));
2199
+ let upper = Arc::new(Tmpfs::new().with_size(Some(2)).with_nr_inodes(Some(8)));
1381
2200
  let (overlay, _) = overlay_on(upper.clone());
1382
2201
  assert_eq!(
1383
2202
  (
1384
- write(&overlay, "dir/file", b"x"),
1385
- upper.metadata("dir/file"),
2203
+ write_over(&overlay, "dir/file", b"x"),
2204
+ on(&upper).vfs_lstat("upper/dir/file"),
1386
2205
  read(&overlay, "dir/file")
1387
2206
  ),
1388
2207
  (
1389
- Err(FilesystemError::StorageFull),
1390
- Err(FilesystemError::NotFound),
2208
+ Err(Errno::StorageFull),
2209
+ Err(Errno::NotFound),
1391
2210
  b"lower".to_vec()
1392
2211
  ),
1393
2212
  "a write through Overlay::open whose copy up runs out of room must leave no partial \
@@ -1395,375 +2214,962 @@ mod tests {
1395
2214
  );
1396
2215
  }
1397
2216
 
1398
- /// A Memory whose files write at most three bytes per call and, when
1399
- /// `refuses_close`, refuse their close.
1400
- struct Trickles {
1401
- memory: Memory,
1402
- refuses_close: bool,
1403
- }
1404
-
1405
- struct TrickleFile {
1406
- file: Box<dyn File>,
1407
- refuses_close: bool,
2217
+ // The run's deadline has passed before the write asks, so the copy up
2218
+ // stops before its first chunk.
2219
+ // @behavior FS-213
2220
+ #[test]
2221
+ fn a_copy_up_past_its_runs_deadline_answers_eintr() {
2222
+ let upper = Arc::new(Tmpfs::new());
2223
+ let (overlay, _) = overlay_on(upper.clone());
2224
+ let written = crate::sched::run_task(Some(std::time::Instant::now()), || {
2225
+ write_over(&overlay, "dir/file", b"x")
2226
+ });
2227
+ assert_eq!(
2228
+ (
2229
+ written,
2230
+ on(&upper).vfs_lstat("upper/dir/file"),
2231
+ read(&overlay, "dir/file")
2232
+ ),
2233
+ (
2234
+ Err(Errno::Interrupted),
2235
+ Err(Errno::NotFound),
2236
+ b"lower".to_vec()
2237
+ ),
2238
+ "a write through Overlay::open whose run's deadline passed must answer EINTR before \
2239
+ copying, and leave the lower file showing"
2240
+ );
1408
2241
  }
1409
2242
 
1410
- impl File for TrickleFile {
1411
- fn read_at(&mut self, buf: &mut [u8], offset: u64) -> Result<usize, FilesystemError> {
1412
- self.file.read_at(buf, offset)
1413
- }
1414
-
1415
- fn write_at(&mut self, buf: &[u8], offset: u64) -> Result<usize, FilesystemError> {
1416
- self.file.write_at(&buf[..buf.len().min(3)], offset)
1417
- }
2243
+ /// A Tmpfs reporting `file` two bytes long, though it holds more.
2244
+ struct ReportsTwoBytes;
1418
2245
 
1419
- fn append(&mut self, buf: &[u8]) -> Result<(u64, usize), FilesystemError> {
1420
- self.file.append(&buf[..buf.len().min(3)])
2246
+ impl Hook for ReportsTwoBytes {
2247
+ fn getattr(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Kstat, Errno> {
2248
+ let mut stat = inner.getattr(dentry)?;
2249
+ if dentry.name() == "file" {
2250
+ stat.size = 2;
2251
+ }
2252
+ Ok(stat)
1421
2253
  }
2254
+ }
1422
2255
 
1423
- fn metadata(&self) -> Result<Metadata, FilesystemError> {
1424
- self.file.metadata()
1425
- }
2256
+ // The lower file reads past the size its stat reported, as one growing
2257
+ // while it is copied does.
2258
+ // @behavior FS-214
2259
+ #[test]
2260
+ fn a_copy_up_takes_the_size_the_lower_file_reported() {
2261
+ let tmpfs: Tmpfs = [("file", "lower")].into_iter().collect();
2262
+ let lower = Wrap::new(Arc::new(tmpfs), Arc::new(ReportsTwoBytes));
2263
+ let upper = Arc::new(Tmpfs::new());
2264
+ let overlay = at(over(Arc::new(lower), upper.clone()));
2265
+ write_over(&overlay, "file", b"L").expect("the copy up and the write must land");
2266
+ assert_eq!(
2267
+ read(&on(&upper), "upper/file"),
2268
+ b"Lo".to_vec(),
2269
+ "a lower file copied up through Overlay::open must bring the bytes its stat reported, \
2270
+ not all it reads"
2271
+ );
2272
+ }
1426
2273
 
1427
- fn set_len(&mut self, len: u64) -> Result<(), FilesystemError> {
1428
- self.file.set_len(len)
1429
- }
2274
+ /// A Tmpfs answering a stat of `dir` at any depth with an I/O failure,
2275
+ /// though it opens `dir` as any other directory.
2276
+ struct StatsNoDir;
1430
2277
 
1431
- fn close(self: Box<Self>) -> Result<(), FilesystemError> {
1432
- if self.refuses_close {
1433
- return Err(FilesystemError::PermissionDenied);
2278
+ impl Hook for StatsNoDir {
2279
+ fn getattr(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Kstat, Errno> {
2280
+ if dentry.name() == "dir" {
2281
+ return Err(Errno::Other("dir has no stat".to_string()));
1434
2282
  }
1435
- self.file.close()
2283
+ inner.getattr(dentry)
1436
2284
  }
1437
2285
  }
1438
2286
 
1439
- impl Filesystem for Trickles {
1440
- holds_no_links!();
1441
- never_repeats_identities!();
1442
- is_shared!();
1443
- matches_names_exactly!();
2287
+ /// A Tmpfs whose `file` is gone after its first lookup, as a host
2288
+ /// directory another process changes mid-call.
2289
+ #[derive(Default)]
2290
+ struct Vanishes {
2291
+ seen: AtomicBool,
2292
+ }
1444
2293
 
1445
- fn open(
1446
- &self,
1447
- path: &str,
1448
- options: &OpenOptions,
1449
- ) -> Result<Box<dyn File>, FilesystemError> {
1450
- Ok(Box::new(TrickleFile {
1451
- file: self.memory.open(path, options)?,
1452
- refuses_close: self.refuses_close,
1453
- }))
2294
+ impl Hook for Vanishes {
2295
+ fn getattr(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Kstat, Errno> {
2296
+ if dentry.name() == "file" && self.seen.swap(true, Ordering::SeqCst) {
2297
+ return Err(Errno::NotFound);
2298
+ }
2299
+ inner.getattr(dentry)
1454
2300
  }
2301
+ }
1455
2302
 
1456
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1457
- self.memory.metadata(path)
1458
- }
2303
+ /// A Tmpfs storing names in lower case and reaching each by any
2304
+ /// case, as a host that folds case does, answering each call by the
2305
+ /// folded path from its root.
2306
+ #[derive(Clone)]
2307
+ struct FoldsCase {
2308
+ root: KernPath,
2309
+ }
1459
2310
 
1460
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1461
- self.memory.read_dir(path)
2311
+ impl FoldsCase {
2312
+ fn new(tmpfs: Tmpfs) -> Self {
2313
+ Self { root: at(tmpfs) }
1462
2314
  }
2315
+ }
1463
2316
 
1464
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1465
- self.memory.create_dir(path)
1466
- }
2317
+ /// The path `dentry` stands at beneath the root, folded.
2318
+ fn folded_path_of(dentry: &Dentry) -> String {
2319
+ dentry.path_raw()[1..].to_lowercase()
2320
+ }
1467
2321
 
1468
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1469
- self.memory.remove_dir(path)
1470
- }
2322
+ /// A directory of a `FoldsCase`, open.
2323
+ struct FoldedDir(KernPath);
1471
2324
 
1472
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1473
- self.memory.remove_file(path)
2325
+ impl FileOperations for FoldedDir {
2326
+ fn iterate_shared(
2327
+ &mut self,
2328
+ dentry: &Dentry,
2329
+ ctx: &mut DirContext<'_>,
2330
+ ) -> Result<(), Errno> {
2331
+ let entries = match folded_path_of(dentry).as_str() {
2332
+ "" => self.0.iterate_dir(),
2333
+ at => self.0.open_dir(at)?.iterate_dir(),
2334
+ }?;
2335
+ crate::filesystem::Rdir::default().iterate_shared(dentry, ctx, || Ok(entries))
1474
2336
  }
2337
+ }
1475
2338
 
1476
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1477
- self.memory.rename(from, to, rename)
2339
+ impl FileSystemType for FoldsCase {
2340
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
2341
+ sb.d_make_root(Inode::new(&Kstat::new(FileType::Dir, 0), self));
2342
+ Ok(())
1478
2343
  }
1479
2344
  }
1480
2345
 
1481
- /// A Memory refusing to move or remove a directory.
1482
- struct HoldsDirectories(Memory);
1483
-
1484
- impl Filesystem for HoldsDirectories {
1485
- holds_no_links!();
1486
- never_repeats_identities!();
1487
- is_shared!();
1488
- matches_names_exactly!();
1489
-
1490
- fn open(
1491
- &self,
1492
- path: &str,
1493
- options: &OpenOptions,
1494
- ) -> Result<Box<dyn File>, FilesystemError> {
1495
- self.0.open(path, options)
2346
+ impl InodeOperations for FoldsCase {
2347
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
2348
+ self.root.vfs_lstat(&folded_path_of(dentry))
1496
2349
  }
1497
2350
 
1498
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1499
- self.0.metadata(path)
2351
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
2352
+ let name = dentry.name();
2353
+ let lower = name.to_lowercase();
2354
+ match self.root.vfs_lstat(&folded_path_of(dentry)) {
2355
+ Ok(found) if lower != name => Ok(Lookup::Spelled {
2356
+ name: lower,
2357
+ inode: Inode::new(&found, Arc::new(self.clone())),
2358
+ }),
2359
+ Ok(found) => Ok(Lookup::Found(Inode::new(&found, Arc::new(self.clone())))),
2360
+ Err(Errno::NotFound) => Ok(Lookup::Absent),
2361
+ Err(err) => Err(err),
2362
+ }
1500
2363
  }
1501
2364
 
1502
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1503
- self.0.read_dir(path)
2365
+ fn open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
2366
+ if dentry.file_type() == Ok(FileType::Dir) {
2367
+ return Ok(Box::new(FoldedDir(self.root.clone())));
2368
+ }
2369
+ self.root.open(&folded_path_of(dentry), how)
1504
2370
  }
1505
2371
 
1506
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1507
- self.0.create_dir(path)
2372
+ fn atomic_open(&self, dentry: &Dentry, how: &OpenHow) -> Result<Finish, Errno> {
2373
+ if dentry.in_lookup() {
2374
+ let found = self.lookup(dentry)?;
2375
+ if !how.create || !matches!(found, Lookup::Absent) {
2376
+ return Ok(Finish::Lookup(found));
2377
+ }
2378
+ }
2379
+ if !how.create {
2380
+ return Ok(Finish::NoOpen { created: false });
2381
+ }
2382
+ let file = self.root.create(&folded_path_of(dentry), how)?;
2383
+ Ok(Finish::Open {
2384
+ file,
2385
+ created: true,
2386
+ })
1508
2387
  }
1509
2388
 
1510
- fn remove_dir(&self, _path: &str) -> Result<(), FilesystemError> {
1511
- Err(FilesystemError::PermissionDenied)
2389
+ fn mkdir(&self, dentry: &Dentry) -> Result<(), Errno> {
2390
+ self.root.vfs_mkdir(&folded_path_of(dentry))
1512
2391
  }
1513
2392
 
1514
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1515
- self.0.remove_file(path)
2393
+ fn rmdir(&self, dentry: &Dentry) -> Result<(), Errno> {
2394
+ self.root.vfs_rmdir(&folded_path_of(dentry))
1516
2395
  }
1517
2396
 
1518
- fn rename(&self, _from: &str, _to: &str, _rename: Rename) -> Result<(), FilesystemError> {
1519
- Err(FilesystemError::PermissionDenied)
2397
+ fn unlink(&self, dentry: &Dentry) -> Result<(), Errno> {
2398
+ self.root.vfs_unlink(&folded_path_of(dentry))
1520
2399
  }
1521
- }
1522
2400
 
1523
- /// A Memory refusing to remove a whiteout.
1524
- struct KeepsWhiteouts(Memory);
1525
-
1526
- impl Filesystem for KeepsWhiteouts {
1527
- holds_no_links!();
1528
- never_repeats_identities!();
1529
- is_shared!();
1530
- matches_names_exactly!();
1531
-
1532
- fn open(
2401
+ fn rename(
1533
2402
  &self,
1534
- path: &str,
1535
- options: &OpenOptions,
1536
- ) -> Result<Box<dyn File>, FilesystemError> {
1537
- self.0.open(path, options)
1538
- }
1539
-
1540
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1541
- self.0.metadata(path)
1542
- }
1543
-
1544
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1545
- self.0.read_dir(path)
1546
- }
1547
-
1548
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1549
- self.0.create_dir(path)
2403
+ old: &Dentry,
2404
+ _new_dir: &dyn InodeOperations,
2405
+ new: &Dentry,
2406
+ _flags: Option<RenameFlag>,
2407
+ ) -> Result<(), Errno> {
2408
+ self.root
2409
+ .rename(&folded_path_of(old), &self.root, &folded_path_of(new))
1550
2410
  }
2411
+ }
1551
2412
 
1552
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1553
- self.0.remove_dir(path)
1554
- }
2413
+ /// What `path` names through `fs`, or why it names nothing.
2414
+ fn kind(fs: &KernPath, path: &str) -> Result<FileType, Errno> {
2415
+ fs.vfs_lstat(path).map(|metadata| metadata.file_type)
2416
+ }
1555
2417
 
1556
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1557
- match path.rsplit('/').next() {
1558
- Some(name) if name.starts_with(".wh.") => Err(FilesystemError::PermissionDenied),
1559
- _ => self.0.remove_file(path),
1560
- }
1561
- }
2418
+ // The inner directory is opened too, so only directories held as the
2419
+ // Layers' directories themselves, not reached again by their path,
2420
+ // take it along.
2421
+ // @behavior FS-110
2422
+ #[test]
2423
+ fn a_directory_opened_from_an_overlay_follows_it_when_it_moves() {
2424
+ let upper = Arc::new(Tmpfs::new());
2425
+ let overlay = at(over(Arc::new(Tmpfs::new()), upper.clone()));
2426
+ overlay.vfs_mkdir("dir").expect("dir must be made");
2427
+ overlay.vfs_mkdir("dir/inner").expect("inner must be made");
2428
+ let dir = overlay.open_dir("dir").expect("dir must open");
2429
+ let inner = overlay.open_dir("dir/inner").expect("inner must open");
2430
+ overlay
2431
+ .rename("dir", &overlay, "moved")
2432
+ .expect("the directory must move");
2433
+ overwrite(&dir, "a", b"x");
2434
+ overwrite(&inner, "b", b"x");
2435
+ assert_eq!(
2436
+ (
2437
+ kind(&overlay, "moved/a"),
2438
+ kind(&overlay, "moved/inner/b"),
2439
+ kind(&overlay, "dir")
2440
+ ),
2441
+ (
2442
+ Ok(FileType::RegFile),
2443
+ Ok(FileType::RegFile),
2444
+ Err(Errno::NotFound)
2445
+ ),
2446
+ "files made through directories Overlay::open_dir opened before Overlay::rename moved \
2447
+ the outer one must stand beneath its new path"
2448
+ );
2449
+ }
1562
2450
 
1563
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1564
- self.0.rename(from, to, rename)
1565
- }
2451
+ // @behavior FS-111
2452
+ #[test]
2453
+ fn an_overlay_directory_removed_while_opened_makes_nothing_more() {
2454
+ let overlay = at(over(Arc::new(Tmpfs::new()), Arc::new(Tmpfs::new())));
2455
+ overlay.vfs_mkdir("dir").expect("dir must be made");
2456
+ let dir = overlay.open_dir("dir").expect("dir must open");
2457
+ overlay.vfs_rmdir("dir").expect("dir must remove");
2458
+ overlay.vfs_mkdir("dir").expect("another dir must be made");
2459
+ assert_eq!(
2460
+ (
2461
+ write(&dir, "made", b"x"),
2462
+ dir.iterate_dir().map(|entries| entries.len()),
2463
+ names(&overlay, "dir").len()
2464
+ ),
2465
+ (Err(Errno::NotFound), Ok(0), 0),
2466
+ "a directory Overlay::open_dir opened, once vfs_rmdir removed it and another \
2467
+ was made in its place, must make nothing, list nothing, and leave the new one empty"
2468
+ );
1566
2469
  }
1567
2470
 
1568
- /// A Memory answering a lookup of any marker name with an I/O failure.
1569
- struct ReadsNoMarker(Memory);
2471
+ // A change made to a Layer outside its Overlay is the host's, so the
2472
+ // opened directory keeps the Layer's directory it holds, as a
2473
+ // descriptor keeps its directory, rather than reach the one made in
2474
+ // its place.
2475
+ // @behavior FS-112
2476
+ #[test]
2477
+ fn an_overlay_directory_keeps_its_layers_directory_through_a_change_outside_it() {
2478
+ let upper = tmpfs_with("upper/dir/file", "x");
2479
+ let overlay = at(over(Arc::new(Tmpfs::new()), upper.clone()));
2480
+ let dir = overlay.open_dir("dir").expect("dir must open");
2481
+ let outside = on(&upper);
2482
+ outside
2483
+ .rename("upper/dir", &outside, "upper/moved")
2484
+ .expect("the Layer must move it");
2485
+ outside
2486
+ .vfs_mkdir("upper/dir")
2487
+ .expect("the Layer must make another");
2488
+ overwrite(&outside, "upper/dir/file", b"other");
2489
+ assert_eq!(
2490
+ read(&dir, "file"),
2491
+ b"x".to_vec(),
2492
+ "a read through a directory Overlay::open_dir opened, once its Layer moved it away \
2493
+ and made another in its place outside the Overlay, must read the directory it \
2494
+ opened"
2495
+ );
2496
+ }
1570
2497
 
1571
- impl Filesystem for ReadsNoMarker {
1572
- holds_no_links!();
1573
- never_repeats_identities!();
1574
- is_shared!();
1575
- matches_names_exactly!();
2498
+ /// A lower Layer running what it holds right after its first open, while a
2499
+ /// file of it is being opened through the view.
2500
+ #[derive(Default)]
2501
+ struct RunsAfterOpen(Mutex<Option<Box<dyn FnOnce() + Send>>>);
1576
2502
 
2503
+ impl Hook for RunsAfterOpen {
1577
2504
  fn open(
1578
2505
  &self,
1579
- path: &str,
1580
- options: &OpenOptions,
1581
- ) -> Result<Box<dyn File>, FilesystemError> {
1582
- self.0.open(path, options)
1583
- }
1584
-
1585
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1586
- if path
1587
- .rsplit('/')
1588
- .next()
1589
- .is_some_and(|name| name.starts_with(".wh."))
1590
- {
1591
- return Err(FilesystemError::Other(
1592
- "the marker cannot be read".to_string(),
1593
- ));
2506
+ inner: &dyn InodeOperations,
2507
+ dentry: &Dentry,
2508
+ how: &OpenHow,
2509
+ ) -> Result<Box<dyn FileOperations>, Errno> {
2510
+ let opened = inner.open(dentry, how);
2511
+ let run = self.0.lock().expect("never poisoned").take();
2512
+ if let Some(run) = run {
2513
+ crate::sched::testing::join("the writer", thread::spawn(run));
1594
2514
  }
1595
- self.0.metadata(path)
2515
+ opened
1596
2516
  }
2517
+ }
1597
2518
 
1598
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1599
- self.0.read_dir(path)
1600
- }
2519
+ // The copy up lands between the lower open and whatever the file does to
2520
+ // learn of one, so only a file asking where the data is at each read sees
2521
+ // it. A count taken after the open would say no reader was there to tell.
2522
+ // @behavior FS-157
2523
+ #[test]
2524
+ fn a_file_opened_as_a_copy_up_lands_reads_the_copy() {
2525
+ let hook = Arc::new(RunsAfterOpen::default());
2526
+ let lower = Wrap::new(tmpfs_with("note", "lower"), hook.clone());
2527
+ let overlay = at(over(Arc::new(lower), Arc::new(Tmpfs::new())));
2528
+ *hook.0.lock().expect("never poisoned") = Some({
2529
+ let writer = overlay.clone();
2530
+ Box::new(move || overwrite(&writer, "note", b"upper"))
2531
+ });
2532
+ assert_eq!(
2533
+ read(&overlay, "note"),
2534
+ b"upper".to_vec(),
2535
+ "a read through a file of a lower Layer opened while a write copied it up must read \
2536
+ the copy"
2537
+ );
2538
+ }
1601
2539
 
1602
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1603
- self.0.create_dir(path)
1604
- }
2540
+ // A descriptor held across the removal still names the lower file, while
2541
+ // what stands at its name now is another entry, so only a copy up refusing
2542
+ // a name taken keeps the lower Layer from being asked.
2543
+ // @behavior FS-158
2544
+ #[test]
2545
+ fn a_time_set_on_a_file_whose_name_was_taken_leaves_its_lower_layer() {
2546
+ use crate::mount::{Access, Mount};
2547
+ use crate::vfs::{self, OpenHow, Path};
2548
+ let asked = Arc::new(AtomicUsize::new(0));
2549
+ let overlay = Overlay::new(
2550
+ vec![Filesystem::new(KeepsTimes(asked.clone())).expect("the instance must stand")],
2551
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2552
+ )
2553
+ .expect("the Overlay must stack");
2554
+ let mount = Mount::new(
2555
+ "/data",
2556
+ Filesystem::new(overlay).expect("the instance must stand"),
2557
+ Access::ReadWrite,
2558
+ )
2559
+ .expect("/data is a guest path");
2560
+ let root = Path::root(mount.mnt());
2561
+ let cred = Arc::default();
2562
+ let (read, create) = (
2563
+ OpenHow {
2564
+ read: true,
2565
+ ..OpenHow::default()
2566
+ },
2567
+ OpenHow {
2568
+ write: true,
2569
+ create: true,
2570
+ ..OpenHow::default()
2571
+ },
2572
+ );
2573
+ let held = vfs::kern_path::filp_open(&cred, &root, "file", &read)
2574
+ .unwrap_or_else(|_| panic!("the file must open"));
2575
+ vfs::filename_unlinkat(&cred, &root, "file").expect("the file must be removed");
2576
+ drop(vfs::kern_path::filp_open(&cred, &root, "file", &create));
2577
+ let answer = vfs::do_utimes_fd(
2578
+ &cred,
2579
+ held.path(),
2580
+ &Iattr::for_times(None, Some(crate::vfs::SetTime::Now)),
2581
+ );
2582
+ assert_eq!(
2583
+ (answer, asked.load(Ordering::SeqCst)),
2584
+ (Err(Errno::AlreadyExists), 0),
2585
+ "vfs::do_utimes_fd on a held lower file whose name another entry took must answer \
2586
+ EEXIST and leave the lower Layer unasked"
2587
+ );
2588
+ }
1605
2589
 
1606
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1607
- self.0.remove_dir(path)
1608
- }
2590
+ // The held file's directory was removed and made again, and the upper
2591
+ // directory it knows of is the removed one, so nothing lands in the new one.
2592
+ // @behavior FS-179
2593
+ #[test]
2594
+ fn a_held_file_of_a_directory_made_again_stays_out_of_it() {
2595
+ use crate::mount::{Access, Mount};
2596
+ use crate::vfs::{self, OpenHow, Path};
2597
+ let lower: Tmpfs = [("d/f", "removed")].into_iter().collect();
2598
+ let overlay = Overlay::new(
2599
+ vec![Filesystem::new(lower).expect("the instance must stand")],
2600
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2601
+ )
2602
+ .expect("the Overlay must stack");
2603
+ let mount = Mount::new(
2604
+ "/data",
2605
+ Filesystem::new(overlay).expect("the instance must stand"),
2606
+ Access::ReadWrite,
2607
+ )
2608
+ .expect("/data is a guest path");
2609
+ let root = Path::root(mount.mnt());
2610
+ let cred = Arc::default();
2611
+ let read = OpenHow {
2612
+ read: true,
2613
+ ..OpenHow::default()
2614
+ };
2615
+ let held = vfs::kern_path::filp_open(&cred, &root, "d/f", &read)
2616
+ .unwrap_or_else(|_| panic!("the file must open"));
2617
+ vfs::filename_unlinkat(&cred, &root, "d/f").expect("the file must be removed");
2618
+ vfs::filename_rmdir(&cred, &root, "d").expect("the directory must be removed");
2619
+ vfs::filename_mkdirat(&cred, &root, "d").expect("the directory must be made again");
2620
+ let answer = vfs::do_utimes_fd(
2621
+ &cred,
2622
+ held.path(),
2623
+ &Iattr::for_times(None, Some(crate::vfs::SetTime::Now)),
2624
+ );
2625
+ assert_eq!(
2626
+ (
2627
+ answer,
2628
+ vfs::vfs_fstatat(&cred, &root, "d/f", false).map(|_| ())
2629
+ ),
2630
+ (Err(Errno::NotFound), Err(Errno::NotFound)),
2631
+ "vfs::do_utimes_fd on a held lower file whose directory was removed and made again \
2632
+ must answer ENOENT and leave the file out of the view"
2633
+ );
2634
+ }
1609
2635
 
1610
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1611
- self.0.remove_file(path)
1612
- }
2636
+ /// Slows the first ask about the directory `e` once armed, so a second copy
2637
+ /// up of it finds the first under way.
2638
+ struct SlowsDirectory(AtomicBool);
1613
2639
 
1614
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1615
- self.0.rename(from, to, rename)
2640
+ impl Hook for SlowsDirectory {
2641
+ fn getattr(&self, inner: &dyn InodeOperations, dentry: &Dentry) -> Result<Kstat, Errno> {
2642
+ if dentry.name() == "e" && self.0.swap(false, Ordering::SeqCst) {
2643
+ thread::sleep(Duration::from_millis(100));
2644
+ }
2645
+ inner.getattr(dentry)
1616
2646
  }
1617
2647
  }
1618
2648
 
1619
- /// A Memory whose `file` is gone after its first lookup, as a host
1620
- /// directory another process changes mid-call.
1621
- struct Vanishes {
1622
- memory: Memory,
1623
- seen: AtomicBool,
2649
+ // The second copy up decided the directory was not up yet, and waited for the
2650
+ // first. Without asking again under the lock, it would find the first's copy
2651
+ // standing at the name and refuse.
2652
+ // @behavior FS-181
2653
+ #[test]
2654
+ fn a_directory_two_files_copy_up_at_once_takes_both() {
2655
+ use crate::mount::{Access, Mount};
2656
+ use crate::vfs::{self, OpenHow, Path};
2657
+ let lower: Tmpfs = [("d/e/f", "1"), ("d/e/g", "2")].into_iter().collect();
2658
+ let hook = Arc::new(SlowsDirectory(AtomicBool::new(false)));
2659
+ let overlay = Overlay::new(
2660
+ vec![Filesystem::new(Wrap::new(Arc::new(lower), hook.clone()))
2661
+ .expect("the instance must stand")],
2662
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2663
+ )
2664
+ .expect("the Overlay must stack");
2665
+ let mount = Mount::new(
2666
+ "/data",
2667
+ Filesystem::new(overlay).expect("the instance must stand"),
2668
+ Access::ReadWrite,
2669
+ )
2670
+ .expect("/data is a guest path");
2671
+ let root = Path::root(mount.mnt());
2672
+ let cred = Arc::default();
2673
+ let write = OpenHow {
2674
+ write: true,
2675
+ ..OpenHow::default()
2676
+ };
2677
+ for name in ["d/e/f", "d/e/g"] {
2678
+ vfs::vfs_fstatat(&cred, &root, name, false).expect("the file stands");
2679
+ }
2680
+ hook.0.store(true, Ordering::SeqCst);
2681
+ let opened = thread::scope(|scope| {
2682
+ let (first, second) = (
2683
+ scope.spawn(|| vfs::kern_path::filp_open(&cred, &root, "d/e/f", &write).map(drop)),
2684
+ scope.spawn(|| vfs::kern_path::filp_open(&cred, &root, "d/e/g", &write).map(drop)),
2685
+ );
2686
+ (
2687
+ crate::sched::testing::join_scoped("the first open", first),
2688
+ crate::sched::testing::join_scoped("the second open", second),
2689
+ )
2690
+ });
2691
+ assert_eq!(
2692
+ opened,
2693
+ (Ok(()), Ok(())),
2694
+ "vfs::do_file_open to write two files of one lower directory at once must copy the \
2695
+ directory up once and open both"
2696
+ );
1624
2697
  }
1625
2698
 
1626
- impl Filesystem for Vanishes {
1627
- holds_no_links!();
1628
- never_repeats_identities!();
1629
- is_shared!();
1630
- matches_names_exactly!();
2699
+ mod stress {
2700
+ use super::*;
2701
+ use crate::mount::{Access, Mount};
2702
+ use crate::vfs::{self, OpenHow, Path};
1631
2703
 
1632
- fn open(
1633
- &self,
1634
- path: &str,
1635
- options: &OpenOptions,
1636
- ) -> Result<Box<dyn File>, FilesystemError> {
1637
- self.memory.open(path, options)
2704
+ /// What a removal and an open to write answer racing over one lower file,
2705
+ /// with what the descriptor the open made reports of itself.
2706
+ fn race_removal_with_a_write() -> (Result<(), Errno>, Option<Result<FileType, Errno>>) {
2707
+ let lower: Tmpfs = [("d/f", "lower")].into_iter().collect();
2708
+ let overlay = Overlay::new(
2709
+ vec![Filesystem::new(lower).expect("the instance must stand")],
2710
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2711
+ )
2712
+ .expect("the Overlay must stack");
2713
+ let mount = Mount::new(
2714
+ "/data",
2715
+ Filesystem::new(overlay).expect("the instance must stand"),
2716
+ Access::ReadWrite,
2717
+ )
2718
+ .expect("/data is a guest path");
2719
+ let root = Path::root(mount.mnt());
2720
+ let cred = Arc::default();
2721
+ let write = OpenHow {
2722
+ write: true,
2723
+ ..OpenHow::default()
2724
+ };
2725
+ let ready = std::sync::atomic::AtomicBool::new(false);
2726
+ std::thread::scope(|scope| {
2727
+ let opening = scope.spawn(|| {
2728
+ crate::sched::testing::wait_until("the removal starting", || {
2729
+ ready.load(Ordering::SeqCst)
2730
+ });
2731
+ vfs::kern_path::filp_open(&cred, &root, "d/f", &write)
2732
+ .ok()
2733
+ .map(|file| file.getattr().map(|metadata| metadata.file_type))
2734
+ });
2735
+ ready.store(true, Ordering::SeqCst);
2736
+ let removed = crate::sched::testing::within_max_wait(|| {
2737
+ vfs::filename_unlinkat(&cred, &root, "d/f")
2738
+ });
2739
+ (
2740
+ removed,
2741
+ crate::sched::testing::join_scoped("the open", opening),
2742
+ )
2743
+ })
2744
+ }
2745
+
2746
+ // The make holds only the directory it makes in, so only the removal
2747
+ // holding that directory too, and removing it only once empty, keeps
2748
+ // what the make made from going with it. The two land in the same
2749
+ // instant only a few times in this many tries.
2750
+ // @behavior FS-132
2751
+ #[test]
2752
+ #[ignore = "a stress witness; run by rake crates:stress"]
2753
+ fn a_removal_through_an_overlay_waits_for_a_change_in_that_directory() {
2754
+ let (overlay, upper) = beside_its_upper([("upper/a/.keep", "")].into_iter().collect());
2755
+ let stop = Arc::new(AtomicBool::new(false));
2756
+ let churning = {
2757
+ let stop = stop.clone();
2758
+ thread::spawn(move || {
2759
+ while !stop.load(Ordering::SeqCst) {
2760
+ let _ = vfs::filename_mkdirat(&Arc::default(), &overlay, "a/b");
2761
+ let _ = vfs::filename_rmdir(&Arc::default(), &overlay, "a/b");
2762
+ }
2763
+ })
2764
+ };
2765
+ let mut lost = 0;
2766
+ for _ in 0..100_000 {
2767
+ if vfs::filename_mkdirat(&Arc::default(), &upper, "upper/a/b/made").is_ok() {
2768
+ match vfs::vfs_fstatat(&Arc::default(), &upper, "upper/a/b/made", false) {
2769
+ Ok(_) => {
2770
+ let _ = vfs::filename_rmdir(&Arc::default(), &upper, "upper/a/b/made");
2771
+ }
2772
+ Err(_) => lost += 1,
2773
+ }
2774
+ }
2775
+ }
2776
+ stop.store(true, Ordering::SeqCst);
2777
+ churning.join().expect("the Overlay's calls must not panic");
2778
+ assert_eq!(
2779
+ lost, 0,
2780
+ "vfs::filename_mkdirat in a directory through a Mount of an Overlay's upper \
2781
+ Tmpfs, while vfs::filename_rmdir removes that directory through the Overlay, \
2782
+ must leave every directory it made standing"
2783
+ );
1638
2784
  }
1639
2785
 
1640
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1641
- if path == "file" && self.seen.swap(true, Ordering::SeqCst) {
1642
- return Err(FilesystemError::NotFound);
2786
+ // A removal deciding how to hide the name before the copy up landed asked
2787
+ // the rename to find nothing there.
2788
+ // @behavior FS-182
2789
+ #[test]
2790
+ #[ignore = "a stress witness; run by rake crates:stress"]
2791
+ fn a_file_removed_as_it_is_copied_up_goes() {
2792
+ for _ in 0..50_000 {
2793
+ let (removed, _) = race_removal_with_a_write();
2794
+ assert_eq!(
2795
+ removed,
2796
+ Ok(()),
2797
+ "vfs::filename_unlinkat of a file another Thread opens to write through an \
2798
+ Overlay must remove it"
2799
+ );
1643
2800
  }
1644
- self.memory.metadata(path)
1645
2801
  }
1646
2802
 
1647
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1648
- self.memory.read_dir(path)
2803
+ // A copy up reading its name back after its lock went found the whiteout
2804
+ // the removal left there.
2805
+ // @behavior FS-180
2806
+ #[test]
2807
+ #[ignore = "a stress witness; run by rake crates:stress"]
2808
+ fn a_file_copied_up_as_its_name_is_removed_stays_a_file() {
2809
+ for _ in 0..50_000 {
2810
+ let (_, opened) = race_removal_with_a_write();
2811
+ if let Some(kind) = opened {
2812
+ assert_eq!(
2813
+ kind,
2814
+ Ok(FileType::RegFile),
2815
+ "File::getattr of a file opened to write through an Overlay as it is \
2816
+ removed must report a file"
2817
+ );
2818
+ }
2819
+ }
1649
2820
  }
2821
+ }
1650
2822
 
1651
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1652
- self.memory.create_dir(path)
1653
- }
2823
+ /// A lower Layer whose one entry, `pipe`, is a FIFO, counting each open.
2824
+ struct HoldsFifo(Arc<AtomicUsize>);
1654
2825
 
1655
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1656
- self.memory.remove_dir(path)
2826
+ impl FileSystemType for HoldsFifo {
2827
+ fn fill_super(self: Arc<Self>, sb: &mut Filesystem) -> Result<(), Errno> {
2828
+ sb.d_make_root(Inode::new(&Kstat::new(FileType::Dir, 0), self));
2829
+ Ok(())
1657
2830
  }
2831
+ }
1658
2832
 
1659
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1660
- self.memory.remove_file(path)
2833
+ impl InodeOperations for HoldsFifo {
2834
+ fn getattr(&self, dentry: &Dentry) -> Result<Kstat, Errno> {
2835
+ Ok(match dentry.name().as_str() {
2836
+ "pipe" => Kstat::new(FileType::Fifo, 0).with_identity(1, 2),
2837
+ _ => Kstat::new(FileType::Dir, 0).with_identity(1, 1),
2838
+ })
1661
2839
  }
1662
2840
 
1663
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1664
- self.memory.rename(from, to, rename)
2841
+ fn lookup(&self, dentry: &Dentry) -> Result<Lookup, Errno> {
2842
+ Ok(match dentry.name().as_str() {
2843
+ "pipe" => Lookup::Found(Inode::new(
2844
+ &Kstat::new(FileType::Fifo, 0).with_identity(1, 2),
2845
+ Arc::new(Self(self.0.clone())),
2846
+ )),
2847
+ _ => Lookup::Absent,
2848
+ })
1665
2849
  }
1666
- }
1667
-
1668
- /// A Memory storing names in lower case and reaching each by any
1669
- /// case, as a host that folds case does.
1670
- struct FoldsCase(Memory);
1671
2850
 
1672
- impl Filesystem for FoldsCase {
1673
- holds_no_links!();
1674
- never_repeats_identities!();
1675
- is_shared!();
1676
-
1677
- fn open(
1678
- &self,
1679
- path: &str,
1680
- options: &OpenOptions,
1681
- ) -> Result<Box<dyn File>, FilesystemError> {
1682
- self.0.open(&path.to_lowercase(), options)
2851
+ fn open(&self, _dentry: &Dentry, _how: &OpenHow) -> Result<Box<dyn FileOperations>, Errno> {
2852
+ self.0.fetch_add(1, Ordering::SeqCst);
2853
+ Err(Errno::Interrupted)
1683
2854
  }
2855
+ }
1684
2856
 
1685
- fn metadata(&self, path: &str) -> Result<Metadata, FilesystemError> {
1686
- self.0.metadata(&path.to_lowercase())
1687
- }
2857
+ // A special file answers a time without any open having been asked, as
2858
+ // an open of one could wait for a peer past the invocation's timeout.
2859
+ // @behavior FS-162
2860
+ #[test]
2861
+ fn a_time_set_on_a_special_file_below_an_overlay_opens_nothing() {
2862
+ use crate::mount::{Access, Mount};
2863
+ use crate::vfs::{self, Path};
2864
+ let opened = Arc::new(AtomicUsize::new(0));
2865
+ let overlay = Overlay::new(
2866
+ vec![Filesystem::new(HoldsFifo(opened.clone())).expect("the instance must stand")],
2867
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2868
+ )
2869
+ .expect("the Overlay must stack");
2870
+ let mount = Mount::new(
2871
+ "/data",
2872
+ Filesystem::new(overlay).expect("the instance must stand"),
2873
+ Access::ReadWrite,
2874
+ )
2875
+ .expect("/data is a guest path");
2876
+ let answer = vfs::do_utimes_path(
2877
+ &Arc::default(),
2878
+ &Path::root(mount.mnt()),
2879
+ "pipe",
2880
+ false,
2881
+ &Iattr::for_times(None, Some(crate::vfs::SetTime::Now)),
2882
+ );
2883
+ assert_eq!(
2884
+ (answer, opened.load(Ordering::SeqCst)),
2885
+ (Err(Errno::PermissionDenied), 0),
2886
+ "vfs::do_utimes_pathon a FIFO a lower Layer holds through an Overlay must answer EACCES \
2887
+ and open nothing"
2888
+ );
2889
+ }
1688
2890
 
1689
- fn stored_path(&self, path: &str) -> Result<String, FilesystemError> {
1690
- Ok(path.to_lowercase())
1691
- }
2891
+ // An earlier Overlay's upper, stacked as a lower Layer of another, holds a
2892
+ // whiteout in a directory only that Layer shows, so only a walk reading
2893
+ // such a directory for marks finds nothing there.
2894
+ // @behavior FS-159
2895
+ #[test]
2896
+ fn a_whiteout_in_a_directory_one_layer_shows_names_nothing() {
2897
+ let lower: Tmpfs = [("file", "x")].into_iter().collect();
2898
+ let first_upper = Filesystem::new(Tmpfs::new()).expect("the instance must stand");
2899
+ let first = kern_path(Arc::new(
2900
+ Overlay::new(
2901
+ vec![Filesystem::new(lower).expect("the instance must stand")],
2902
+ Some(first_upper.clone()),
2903
+ )
2904
+ .expect("the Overlay must stack"),
2905
+ ));
2906
+ first.vfs_unlink("file").expect("the file must be removed");
2907
+ let second = at(Overlay::new(
2908
+ vec![first_upper],
2909
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2910
+ )
2911
+ .expect("the Overlay must stack"));
2912
+ assert_eq!(
2913
+ second.vfs_lstat("upper/file").err(),
2914
+ Some(Errno::NotFound),
2915
+ "a stat through an Overlay of a whiteout in a directory one Layer shows must answer \
2916
+ ENOENT, as the listing shows nothing there"
2917
+ );
2918
+ }
1692
2919
 
1693
- fn read_dir(&self, path: &str) -> Result<Vec<DirEntry>, FilesystemError> {
1694
- self.0.read_dir(&path.to_lowercase())
1695
- }
2920
+ // A lower directory moved onto a full one answers why it cannot move, so
2921
+ // only asking that first keeps what stands at the target from answering.
2922
+ // @behavior FS-160
2923
+ #[test]
2924
+ fn a_lower_directory_answers_that_it_cannot_move_before_its_target_is_read() {
2925
+ let lower: Tmpfs = [("dir/file", "x"), ("full/file", "x")]
2926
+ .into_iter()
2927
+ .collect();
2928
+ let overlay = at(over(Arc::new(lower), Arc::new(Tmpfs::new())));
2929
+ assert_eq!(
2930
+ overlay.rename("dir", &overlay, "full"),
2931
+ Err(Errno::CrossesDevices),
2932
+ "a rename through an Overlay of a lower Layer's directory onto one holding entries \
2933
+ must answer EXDEV, as ovl_rename_start asks whether it can move first"
2934
+ );
2935
+ }
1696
2936
 
1697
- fn create_dir(&self, path: &str) -> Result<(), FilesystemError> {
1698
- self.0.create_dir(&path.to_lowercase())
1699
- }
2937
+ // The lower file is far bigger than the upper holds, so only a copy up
2938
+ // leaving its bytes behind can land.
2939
+ // @behavior FS-155
2940
+ #[test]
2941
+ fn a_truncating_open_copies_up_none_of_the_bytes() {
2942
+ use crate::mount::{Access, Mount};
2943
+ use crate::vfs::{self, OpenHow, Path};
2944
+ let lower: Tmpfs = [("file", vec![b'x'; 1 << 20])].into_iter().collect();
2945
+ let upper = Tmpfs::new().with_size(Some(4096)).with_nr_inodes(None);
2946
+ let overlay = Overlay::new(
2947
+ vec![Filesystem::new(lower).expect("the instance must stand")],
2948
+ Some(Filesystem::new(upper).expect("the instance must stand")),
2949
+ )
2950
+ .expect("the Overlay must stack");
2951
+ let mount = Mount::new(
2952
+ "/data",
2953
+ Filesystem::new(overlay).expect("the instance must stand"),
2954
+ Access::ReadWrite,
2955
+ )
2956
+ .expect("/data is a guest path");
2957
+ let root = Path::root(mount.mnt());
2958
+ let cred = Arc::default();
2959
+ let how = OpenHow {
2960
+ read: true,
2961
+ write: true,
2962
+ truncate: true,
2963
+ ..OpenHow::default()
2964
+ };
2965
+ let opened = vfs::kern_path::filp_open(&cred, &root, "file", &how);
2966
+ assert!(
2967
+ opened.is_ok_and(|mut file| file.read(&mut [0; 8]) == Ok(0)),
2968
+ "vfs::do_file_open with O_TRUNC of a lower file past what the upper holds must land \
2969
+ on an empty file"
2970
+ );
2971
+ }
1700
2972
 
1701
- fn remove_dir(&self, path: &str) -> Result<(), FilesystemError> {
1702
- self.0.remove_dir(&path.to_lowercase())
1703
- }
2973
+ // Only the directory the view holds open keeps its Layer's host directory
2974
+ // through walks past a Bind's bound, so only that reaches it once the host
2975
+ // moved it.
2976
+ // @behavior FS-152
2977
+ #[cfg(unix)]
2978
+ #[test]
2979
+ fn an_overlay_directory_held_open_keeps_its_bind_layers_directory_past_the_bound() {
2980
+ use crate::mount::{Access, Mount};
2981
+ use crate::vfs::{self, OpenHow, Path};
2982
+ let host = std::env::temp_dir().join(format!("kobako-overlay-held-{}", std::process::id()));
2983
+ let _ = std::fs::remove_dir_all(&host);
2984
+ let deep = host.join(vec!["d"; 100].join("/"));
2985
+ std::fs::create_dir_all(&deep).expect("the host tree must be made");
2986
+ std::fs::create_dir_all(host.join("held")).expect("the host tree must be made");
2987
+ std::fs::write(host.join("held/f"), "x").expect("the host file must be written");
2988
+ let lower = Filesystem::new(
2989
+ crate::filesystem::Bind::new(&host).expect("the host directory must open"),
2990
+ )
2991
+ .expect("the instance must stand");
2992
+ let overlay = Overlay::new(
2993
+ vec![lower],
2994
+ Some(Filesystem::new(Tmpfs::new()).expect("the instance must stand")),
2995
+ )
2996
+ .expect("the Overlay must stack");
2997
+ let mount = Mount::new(
2998
+ "/data",
2999
+ Filesystem::new(overlay).expect("the instance must stand"),
3000
+ Access::Read,
3001
+ )
3002
+ .expect("/data is a guest path");
3003
+ let root = Path::root(mount.mnt());
3004
+ let cred = Arc::default();
3005
+ let directory = OpenHow {
3006
+ read: true,
3007
+ directory: true,
3008
+ ..OpenHow::default()
3009
+ };
3010
+ let Ok(held) = vfs::kern_path::filp_open(&cred, &root, "held", &directory) else {
3011
+ panic!("the directory must open");
3012
+ };
3013
+ vfs::vfs_fstatat(&cred, &root, &vec!["d"; 100].join("/"), false)
3014
+ .unwrap_or_else(|_| panic!("the deep directory must stand"));
3015
+ std::fs::rename(host.join("held"), host.join("moved")).expect("the host must move it");
3016
+ let reached = vfs::vfs_fstatat(&cred, held.path(), "f", false);
3017
+ let _ = std::fs::remove_dir_all(&host);
3018
+ assert!(
3019
+ reached.is_ok(),
3020
+ "vfs::vfs_fstatat through an Overlay directory held open over a Bind Layer, once a \
3021
+ walk passed the bound and the host moved it, must still reach the directory it opened"
3022
+ );
3023
+ }
1704
3024
 
1705
- fn remove_file(&self, path: &str) -> Result<(), FilesystemError> {
1706
- self.0.remove_file(&path.to_lowercase())
1707
- }
3025
+ // Only the lower Layer holds `dir` when both handles open it, so the
3026
+ // second sees the file only if the copy up through the first reaches
3027
+ // it too.
3028
+ // @behavior FS-119
3029
+ #[test]
3030
+ fn a_copy_up_through_one_overlay_directory_is_seen_through_another() {
3031
+ let lower: Arc<dyn FileSystemType> = tmpfs_with("dir/a.txt", "a");
3032
+ let overlay = at(over(lower, Arc::new(Tmpfs::new())));
3033
+ let first = overlay.open_dir("dir").expect("dir must open");
3034
+ let second = overlay.open_dir("dir").expect("dir must open again");
3035
+ write(&first, "b.txt", b"b").expect("the write must copy dir up");
3036
+ assert_eq!(
3037
+ read(&second, "b.txt"),
3038
+ b"b".to_vec(),
3039
+ "a read through one directory Overlay::open_dir opened, of a file written through \
3040
+ another opened before the write copied it up, must read the file"
3041
+ );
3042
+ }
1708
3043
 
1709
- fn rename(&self, from: &str, to: &str, rename: Rename) -> Result<(), FilesystemError> {
1710
- self.0
1711
- .rename(&from.to_lowercase(), &to.to_lowercase(), rename)
1712
- }
3044
+ // The lower Layer holds no `dir`, so reaching it again by the path it
3045
+ // was opened at would miss where it moved.
3046
+ // @behavior FS-120
3047
+ #[test]
3048
+ fn a_write_through_a_moved_overlay_directory_lands_where_it_went() {
3049
+ let upper = tmpfs_with("upper/dir/a.txt", "a");
3050
+ let overlay = at(over(Arc::new(Tmpfs::new()), upper.clone()));
3051
+ let dir = overlay.open_dir("dir").expect("dir must open");
3052
+ overlay
3053
+ .rename("dir", &overlay, "moved")
3054
+ .expect("the directory must move");
3055
+ assert_eq!(
3056
+ (
3057
+ write(&dir, "b.txt", b"b"),
3058
+ read(&on(&upper), "upper/moved/b.txt")
3059
+ ),
3060
+ (Ok(()), b"b".to_vec()),
3061
+ "a write through a directory Overlay::open_dir opened, once Overlay::rename moved it \
3062
+ over a lower Layer, must land where it moved"
3063
+ );
1713
3064
  }
1714
3065
 
1715
3066
  // @behavior FS-083
1716
3067
  #[test]
1717
3068
  fn an_overlay_spells_a_path_as_the_layer_showing_it_stores_it() {
1718
- let overlay = Overlay::new()
1719
- .layer(Arc::new(Memory::new()), Access::ReadWrite)
1720
- .layer(
1721
- Arc::new(FoldsCase([("private/secret", "x")].into_iter().collect())),
1722
- Access::Read,
1723
- );
3069
+ let overlay = at(over(
3070
+ Arc::new(FoldsCase::new(
3071
+ [("private/secret", "x")].into_iter().collect(),
3072
+ )),
3073
+ Arc::new(Tmpfs::new()),
3074
+ ));
3075
+ let private = overlay
3076
+ .open_dir("PRIVATE")
3077
+ .expect("the directory must open in any case");
1724
3078
  assert_eq!(
1725
3079
  (
1726
- overlay.stored_path("PRIVATE/SECRET"),
1727
- overlay.stored_path("PRIVATE/New")
3080
+ overlay.lookup("PRIVATE"),
3081
+ private.lookup("SECRET"),
3082
+ private.lookup("New")
1728
3083
  ),
1729
3084
  (
1730
- Ok("private/secret".to_string()),
1731
- Ok("private/New".to_string())
3085
+ Ok("private".to_string()),
3086
+ Ok("secret".to_string()),
3087
+ Ok("New".to_string())
1732
3088
  ),
1733
- "a path asked of Overlay::stored_path in another case, shown by a Layer folding case, \
1734
- must come back as that Layer stores each name, a new name kept as given"
3089
+ "a name asked of Overlay::lookup in another case, shown by a Layer folding case, \
3090
+ must come back as that Layer stores it, a new name kept as given"
1735
3091
  );
1736
3092
  }
1737
3093
 
1738
- // A whiteout the Layer cannot read would otherwise count as absent and
1739
- // let the lower file show.
1740
- // @behavior FS-079
3094
+ // A directory only one Layer shows has nothing to merge or hide, so the
3095
+ // walk keeps what that Layer's lookup recorded, as overlayfs leaves it
3096
+ // unmerged and reads `d_is_dir` rather than ask for a stat.
3097
+ // @behavior FS-122
1741
3098
  #[test]
1742
- fn a_layer_that_cannot_read_its_markers_fails_the_lookup() {
1743
- let top: Memory = [(".wh.file", "")].into_iter().collect();
1744
- let overlay = Overlay::new()
1745
- .layer(Arc::new(ReadsNoMarker(top)), Access::Read)
1746
- .layer(memory_with("file", "hidden"), Access::Read);
1747
- assert!(
1748
- matches!(overlay.metadata("file"), Err(FilesystemError::Other(_))),
1749
- "a file looked up through Overlay::metadata, beneath a Layer that cannot read the \
1750
- whiteout over it, must fail the lookup rather than show the file"
3099
+ fn a_directory_one_layer_shows_is_walked_without_its_stat() {
3100
+ let only: Arc<dyn FileSystemType> = tmpfs_with("top/dir/file", "only");
3101
+ let overlay = at(over(
3102
+ Arc::new(Wrap::new(only, Arc::new(StatsNoDir))),
3103
+ Arc::new(Tmpfs::new()),
3104
+ ));
3105
+ assert_eq!(
3106
+ read(&overlay, "top/dir/file"),
3107
+ b"only",
3108
+ "a file read through Overlay::open beneath a directory only the lower Layer shows, \
3109
+ that Layer answering no stat of the directory, must read its content"
3110
+ );
3111
+ }
3112
+
3113
+ /// Refuses every open, as a Layer whose directory cannot open does.
3114
+ struct RefusesOpen;
3115
+
3116
+ impl Hook for RefusesOpen {
3117
+ fn open(
3118
+ &self,
3119
+ _inner: &dyn InodeOperations,
3120
+ _dentry: &Dentry,
3121
+ _how: &OpenHow,
3122
+ ) -> Result<Box<dyn FileOperations>, Errno> {
3123
+ Err(Errno::PermissionDenied)
3124
+ }
3125
+ }
3126
+
3127
+ // A host removing a Bind's directory cannot witness this, as the fid the
3128
+ // lookup took still opens it, so a Layer refuses instead.
3129
+ // @behavior FS-166
3130
+ #[test]
3131
+ fn a_directory_a_layer_cannot_open_answers_why() {
3132
+ use crate::mount::{Access, Mount};
3133
+ use crate::vfs::{self, OpenHow};
3134
+ let lower: Arc<dyn FileSystemType> = tmpfs_with("top/file", "lower");
3135
+ let overlay = over(
3136
+ Arc::new(Wrap::new(lower, Arc::new(RefusesOpen))),
3137
+ Arc::new(Tmpfs::new()),
3138
+ );
3139
+ let mount = Mount::new(
3140
+ "/data",
3141
+ Filesystem::new(overlay).expect("the instance must stand"),
3142
+ Access::Read,
3143
+ )
3144
+ .expect("/data is a guest path");
3145
+ let directory = OpenHow {
3146
+ read: true,
3147
+ directory: true,
3148
+ ..OpenHow::default()
3149
+ };
3150
+ let answer = vfs::kern_path::filp_open(
3151
+ &Arc::default(),
3152
+ &vfs::Path::root(mount.mnt()),
3153
+ "top",
3154
+ &directory,
3155
+ );
3156
+ assert_eq!(
3157
+ answer.err(),
3158
+ Some(Errno::PermissionDenied),
3159
+ "vfs::do_file_open of an Overlay's directory whose Layer refuses its open must answer \
3160
+ what the Layer answered"
1751
3161
  );
1752
3162
  }
1753
3163
 
1754
3164
  // @behavior FS-080
1755
3165
  #[test]
1756
3166
  fn a_file_gone_during_a_rename_answers_not_found() {
1757
- let lower = Vanishes {
1758
- memory: [("file", "lower")].into_iter().collect(),
1759
- seen: AtomicBool::new(false),
1760
- };
1761
- let overlay = Overlay::new()
1762
- .layer(Arc::new(Memory::new()), Access::ReadWrite)
1763
- .layer(Arc::new(lower), Access::Read);
3167
+ let tmpfs: Tmpfs = [("file", "lower")].into_iter().collect();
3168
+ let lower = Wrap::new(Arc::new(tmpfs), Arc::new(Vanishes::default()));
3169
+ let overlay = at(over(Arc::new(lower), Arc::new(Tmpfs::new())));
1764
3170
  assert_eq!(
1765
- overlay.rename("file", "moved", Rename::Any),
1766
- Err(FilesystemError::NotFound),
3171
+ overlay.rename("file", &overlay, "moved"),
3172
+ Err(Errno::NotFound),
1767
3173
  "a file renamed through Overlay::rename that its Layer loses during the call must \
1768
3174
  answer not found"
1769
3175
  );
@@ -1774,148 +3180,134 @@ mod tests {
1774
3180
  // @behavior FS-078
1775
3181
  #[test]
1776
3182
  fn a_directory_over_a_lower_file_on_its_way_reads_as_a_directory() {
1777
- let overlay = Overlay::new()
1778
- .layer(memory_with("dir/sub/file", "upper"), Access::ReadWrite)
1779
- .layer(memory_with("dir", "lower"), Access::Read);
3183
+ let overlay = at(over(
3184
+ tmpfs_with("dir", "lower"),
3185
+ tmpfs_with("upper/dir/sub/file", "upper"),
3186
+ ));
1780
3187
  assert_eq!(
1781
3188
  (
1782
- overlay.metadata("dir/sub").map(|metadata| metadata.file_type),
3189
+ overlay
3190
+ .vfs_lstat("dir/sub")
3191
+ .map(|metadata| metadata.file_type),
1783
3192
  read(&overlay, "dir/sub/file")
1784
3193
  ),
1785
- (Ok(FileType::Directory), b"upper".to_vec()),
1786
- "a directory looked up through Overlay::metadata above a lower Layer holding a file on \
3194
+ (Ok(FileType::Dir), b"upper".to_vec()),
3195
+ "a directory looked up through vfs_lstat above a lower Layer holding a file on \
1787
3196
  its path must read as a directory, as its files open"
1788
3197
  );
1789
3198
  }
1790
3199
 
1791
- // The writable Layer refuses each change only after the Overlay has
1792
- // cleared the whiteout from `dir`, so only putting it back keeps the
1793
- // read-only Layer's `dir/file` hidden.
1794
- // @behavior FS-063
3200
+ // @behavior FS-101
1795
3201
  #[test]
1796
- fn a_refused_change_leaves_what_a_whiteout_hid_hidden() {
1797
- let (overlay, _) = overlay_on(Arc::new(HoldsDirectories(Memory::new())));
1798
- overlay
1799
- .remove_file("dir/file")
1800
- .expect("the file must be removed");
1801
- overlay
1802
- .create_dir("new")
1803
- .expect("the directory must be made");
1804
- let refused = (
1805
- overlay.rename("new", "dir", Rename::Directory),
1806
- overlay.remove_dir("dir"),
1807
- );
3202
+ fn a_file_opened_to_read_before_a_copy_up_reads_the_copy() {
3203
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::default()));
3204
+ let mut reader = open_to_read(&overlay, "dir/file");
3205
+ overwrite(&overlay, "dir/file", b"upper");
1808
3206
  assert_eq!(
1809
- (refused, overlay.metadata("dir/file").err()),
1810
- (
1811
- (
1812
- Err(FilesystemError::PermissionDenied),
1813
- Err(FilesystemError::PermissionDenied)
1814
- ),
1815
- Some(FilesystemError::NotFound)
1816
- ),
1817
- "a rename onto and a removal of a directory whose writable copy holds only a whiteout, \
1818
- refused by the Layer through an Overlay, must leave the whited-out file hidden"
3207
+ read_from(reader.as_mut()),
3208
+ b"upper".to_vec(),
3209
+ "a file Overlay::open handed out to read before another open copied it up must \
3210
+ read what the copy holds"
1819
3211
  );
1820
3212
  }
1821
3213
 
1822
- fn trickles(refuses_close: bool) -> Arc<Trickles> {
1823
- Arc::new(Trickles {
1824
- memory: Memory::new(),
1825
- refuses_close,
1826
- })
1827
- }
1828
-
1829
- // @behavior FS-054
3214
+ // @behavior FS-102
1830
3215
  #[test]
1831
- fn a_copy_up_through_a_layer_writing_in_parts_copies_the_whole_file() {
1832
- let upper = trickles(false);
1833
- let (overlay, _) = overlay_on(upper.clone());
3216
+ fn a_file_opened_to_read_before_a_rename_reads_the_moved_copy() {
3217
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::default()));
3218
+ let mut reader = open_to_read(&overlay, "dir/file");
1834
3219
  overlay
1835
- .open(
1836
- "dir/file",
1837
- &OpenOptions {
1838
- write: true,
1839
- ..OpenOptions::default()
1840
- },
1841
- )
1842
- .expect("the open must copy the lower file up");
3220
+ .rename("dir/file", &overlay, "dir/moved")
3221
+ .expect("the rename must land");
3222
+ overwrite(&overlay, "dir/moved", b"moved");
1843
3223
  assert_eq!(
1844
- read(&upper.memory, "dir/file"),
1845
- b"lower".to_vec(),
1846
- "a write open through Overlay::open must copy the whole lower file up into a Layer \
1847
- whose writes land a few bytes at a time"
3224
+ read_from(reader.as_mut()),
3225
+ b"moved".to_vec(),
3226
+ "a file Overlay::open handed out to read before Overlay::rename moved it must read \
3227
+ what the moved copy holds"
1848
3228
  );
1849
3229
  }
1850
3230
 
1851
- // @behavior FS-055
3231
+ // @behavior FS-103
1852
3232
  #[test]
1853
- fn a_copy_up_whose_close_a_layer_refuses_leaves_nothing_behind() {
1854
- let upper = trickles(true);
1855
- let (overlay, _) = overlay_on(upper.clone());
3233
+ fn a_file_open_to_read_keeps_what_it_held_once_removed() {
3234
+ let (overlay, _) = overlay_on(Arc::new(Tmpfs::default()));
3235
+ let mut reader = open_to_read(&overlay, "dir/file");
3236
+ overwrite(&overlay, "dir/file", b"upper");
3237
+ overlay
3238
+ .vfs_unlink("dir/file")
3239
+ .expect("the removal must land");
3240
+ overwrite(&overlay, "dir/file", b"fresh");
3241
+ overlay
3242
+ .rename("dir/file", &overlay, "dir/moved")
3243
+ .expect("the rename must land");
1856
3244
  assert_eq!(
1857
- (
1858
- write(&overlay, "dir/file", b"x"),
1859
- upper.metadata("dir/file"),
1860
- read(&overlay, "dir/file")
1861
- ),
1862
- (
1863
- Err(FilesystemError::PermissionDenied),
1864
- Err(FilesystemError::NotFound),
1865
- b"lower".to_vec()
1866
- ),
1867
- "a write through Overlay::open whose copy up the writable Layer refuses to close must \
1868
- leave no copy hiding the lower file"
3245
+ read_from(reader.as_mut()),
3246
+ b"upper".to_vec(),
3247
+ "a file Overlay::open handed out to read must keep reading what it held once \
3248
+ vfs_unlink took it away, whatever later stands at its path"
1869
3249
  );
1870
3250
  }
1871
3251
 
1872
- /// Counts each wait its Overlay's lock makes through it.
1873
- struct CountsWaits(AtomicUsize);
3252
+ /// A Tmpfs whose first open sleeps a while, flagging that it began.
3253
+ #[derive(Default)]
3254
+ struct SleepsOnOpen {
3255
+ opening: AtomicBool,
3256
+ }
1874
3257
 
1875
- impl Blocking for CountsWaits {
1876
- fn wait(&self, wait: &mut dyn FnMut()) {
1877
- self.0.fetch_add(1, Ordering::SeqCst);
1878
- wait();
3258
+ impl Hook for SleepsOnOpen {
3259
+ fn open(
3260
+ &self,
3261
+ inner: &dyn InodeOperations,
3262
+ dentry: &Dentry,
3263
+ how: &OpenHow,
3264
+ ) -> Result<Box<dyn FileOperations>, Errno> {
3265
+ if !self.opening.swap(true, Ordering::SeqCst) {
3266
+ thread::sleep(Duration::from_millis(100));
3267
+ }
3268
+ inner.open(dentry, how)
1879
3269
  }
1880
3270
  }
1881
3271
 
3272
+ // The first copy up holds the file's lock while its lower open sleeps,
3273
+ // so the second, of the same file, finds the lock held and waits.
1882
3274
  // @behavior FS-039
1883
3275
  #[test]
1884
- fn a_contended_overlay_waits_through_its_blocking() {
1885
- let counts = Arc::new(CountsWaits(AtomicUsize::new(0)));
1886
- let overlay = Overlay::new()
1887
- .layer(memory_with("note", "x"), Access::Read)
1888
- .with_blocking(counts.clone());
1889
- let held = overlay.lock.hold().expect("the lock must be free");
1890
- let other = overlay.clone();
1891
- let waiter = thread::spawn(move || other.metadata("note").map(|m| m.file_type));
1892
- while counts.0.load(Ordering::SeqCst) == 0 {
1893
- thread::sleep(Duration::from_millis(1));
1894
- }
1895
- drop(held);
3276
+ fn a_contended_copy_up_waits_through_the_registered_blocking() {
3277
+ let counts = crate::sched::testing::count_waits();
3278
+ let sleeps = Arc::new(SleepsOnOpen::default());
3279
+ let lower = Wrap::new(tmpfs_with("note", "lower"), sleeps.clone());
3280
+ let overlay = over(Arc::new(lower), Arc::new(Tmpfs::new()));
3281
+ let first = at(overlay);
3282
+ let second = first.clone();
3283
+ let copying = thread::spawn(move || write_over(&first, "note", b"first"));
3284
+ crate::sched::testing::wait_until("the first copy up opening its lower file", || {
3285
+ sleeps.opening.load(Ordering::SeqCst)
3286
+ });
3287
+ let waited =
3288
+ crate::sched::testing::within_max_wait(|| write_over(&second, "note", b"later"));
1896
3289
  assert_eq!(
1897
3290
  (
1898
- waiter.join().expect("the waiter must not panic"),
1899
- counts.0.load(Ordering::SeqCst)
3291
+ crate::sched::testing::join("the first copy up", copying),
3292
+ waited,
3293
+ counts.load(Ordering::SeqCst) > 0
1900
3294
  ),
1901
- (Ok(FileType::File), 1),
1902
- "a call through an Overlay whose lock another thread holds must wait through the \
1903
- Blocking given by Overlay::with_blocking, then answer"
3295
+ (Ok(()), Ok(()), true),
3296
+ "a write through an Overlay copying up a file another thread is copying up must wait \
3297
+ through the Blocking given to sched::register_blocking, then land"
1904
3298
  );
1905
3299
  }
1906
3300
 
1907
- // Copying up makes the directory in the writable Layer, whose own
1908
- // identity differs, so only reporting the lower Layer's keeps it.
3301
+ // Copying up makes the directory in the upper, whose own identity
3302
+ // differs, so only reporting the lower Layer's keeps it.
1909
3303
  // @behavior FS-072
1910
3304
  #[test]
1911
3305
  fn an_overlay_keeps_a_directorys_identity_when_a_write_copies_it_up() {
1912
- let lower: Arc<dyn Filesystem> =
1913
- Arc::new([("dir/a.txt", "a")].into_iter().collect::<Memory>());
1914
- let overlay = Overlay::new()
1915
- .layer(Arc::new(Memory::new()), Access::ReadWrite)
1916
- .layer(lower, Access::Read);
1917
- let identity = |overlay: &Overlay| {
1918
- let metadata = overlay.metadata("dir").expect("the directory must stand");
3306
+ let lower: Arc<dyn FileSystemType> =
3307
+ Arc::new([("dir/a.txt", "a")].into_iter().collect::<Tmpfs>());
3308
+ let overlay = at(over(lower, Arc::new(Tmpfs::new())));
3309
+ let identity = |overlay: &KernPath| {
3310
+ let metadata = overlay.vfs_lstat("dir").expect("the directory must stand");
1919
3311
  (metadata.dev, metadata.ino)
1920
3312
  };
1921
3313
  let before = identity(&overlay);
@@ -1923,33 +3315,114 @@ mod tests {
1923
3315
  assert_eq!(
1924
3316
  (identity(&overlay) == before, before.1 != 0),
1925
3317
  (true, true),
1926
- "a directory of a read-only Layer copied up by a write through an Overlay's open must \
1927
- keep the identity Overlay::metadata reported before"
3318
+ "a directory of a lower Layer copied up by a write through an Overlay's open must \
3319
+ keep the identity vfs_lstat reported before"
3320
+ );
3321
+ }
3322
+
3323
+ // The upper Layer's directory changes after the lower one is made, so
3324
+ // the two report different times and only the upper's matches.
3325
+ // @behavior FS-117
3326
+ #[test]
3327
+ fn an_overlay_reports_a_merged_directory_as_overlayfs_does() {
3328
+ let lower: Arc<Tmpfs> = Arc::new([("dir/a.txt", "a")].into_iter().collect());
3329
+ let upper: Arc<Tmpfs> = Arc::new(Tmpfs::new());
3330
+ let overlay = at(over(lower.clone(), upper.clone()));
3331
+ std::thread::sleep(std::time::Duration::from_millis(10));
3332
+ write(&overlay, "dir/b.txt", b"b").expect("the upper must take a write");
3333
+ let merged = overlay.vfs_lstat("dir").expect("the directory must stand");
3334
+ let modified = |layer: &Arc<Tmpfs>, path: &str| {
3335
+ on(layer).vfs_lstat(path).expect("a Layer holds it").mtime
3336
+ };
3337
+ assert_eq!(
3338
+ (
3339
+ merged.nlink,
3340
+ merged.mtime == modified(&upper, "upper/dir"),
3341
+ merged.mtime == modified(&lower, "dir"),
3342
+ ),
3343
+ (1, true, false),
3344
+ "Overlay::getattr of a directory two Layers hold, written last in the upper, must \
3345
+ count one name and report the upper Layer's times"
1928
3346
  );
1929
3347
  }
1930
3348
 
1931
3349
  // @behavior FS-073
1932
3350
  #[test]
1933
3351
  fn an_overlay_names_a_directory_alike_whether_a_link_at_its_end_is_followed() {
1934
- let layer = |name: &str| -> Arc<dyn Filesystem> {
1935
- Arc::new(
1936
- [(format!("dir/{name}"), "x")]
1937
- .into_iter()
1938
- .collect::<Memory>(),
1939
- )
1940
- };
1941
- let overlay = Overlay::new()
1942
- .layer(layer("upper"), Access::ReadWrite)
1943
- .layer(layer("lower"), Access::Read);
1944
- let identity = |metadata: Result<Metadata, FilesystemError>| {
3352
+ let overlay = at(over(
3353
+ tmpfs_with("dir/lower", "x"),
3354
+ tmpfs_with("upper/dir/upper", "x"),
3355
+ ));
3356
+ let identity = |metadata: Result<Kstat, Errno>| {
1945
3357
  let metadata = metadata.expect("the directory must stand");
1946
3358
  (metadata.dev, metadata.ino)
1947
3359
  };
1948
3360
  assert_eq!(
1949
- identity(overlay.symlink_metadata("dir")),
1950
- identity(overlay.metadata("dir")),
1951
- "a directory two Layers hold, looked up through Overlay::symlink_metadata, must \
1952
- report the identity Overlay::metadata does"
3361
+ identity(overlay.vfs_lstat("dir")),
3362
+ identity(overlay.vfs_lstat("dir")),
3363
+ "a directory two Layers hold, looked up through vfs_lstat, must \
3364
+ report the identity vfs_lstat does"
1953
3365
  );
1954
3366
  }
3367
+
3368
+ /// A Layer whose `permission` refuses `mask` of what stands at `name`.
3369
+ struct RefusesOf {
3370
+ name: &'static str,
3371
+ mask: Mask,
3372
+ }
3373
+
3374
+ impl Hook for RefusesOf {
3375
+ fn permission(
3376
+ &self,
3377
+ inner: &dyn InodeOperations,
3378
+ dentry: &Dentry,
3379
+ mask: Mask,
3380
+ ) -> Result<(), Errno> {
3381
+ if dentry.name() == self.name && mask.contains(self.mask) {
3382
+ return Err(Errno::PermissionDenied);
3383
+ }
3384
+ inner.permission(dentry, mask)
3385
+ }
3386
+ }
3387
+
3388
+ type LayerCall = fn(&KernPath) -> Result<(), Errno>;
3389
+
3390
+ // Only a Layer of the Host App's own answers `permission`, so each call is
3391
+ // made over a lower Layer refusing just the one ask that call makes of it.
3392
+ // @behavior FS-206
3393
+ #[test]
3394
+ fn an_overlay_asks_a_layers_permission_where_overlayfs_does() {
3395
+ let calls: [(&str, &str, Mask, LayerCall); 4] = [
3396
+ ("finding a name", "dir", Mask::EXEC, |view| {
3397
+ view.vfs_lstat("dir/file").map(drop)
3398
+ }),
3399
+ ("opening a file", "file", Mask::OPEN, |view| {
3400
+ let read = OpenHow {
3401
+ read: true,
3402
+ ..OpenHow::default()
3403
+ };
3404
+ view.open("dir/file", &read).map(drop)
3405
+ }),
3406
+ ("listing a directory", "dir", Mask::OPEN, |view| {
3407
+ view.open_dir("dir")?.iterate_dir().map(drop)
3408
+ }),
3409
+ ("copying a file up", "file", Mask::OPEN, |view| {
3410
+ write_over(view, "dir/file", b"y")
3411
+ }),
3412
+ ];
3413
+ for (call, name, mask, run) in calls {
3414
+ let lower = Wrap::new(
3415
+ tmpfs_with("dir/file", "x"),
3416
+ Arc::new(RefusesOf { name, mask }),
3417
+ );
3418
+ let view = at(over(Arc::new(lower), Arc::new(Tmpfs::new())));
3419
+ assert_eq!(
3420
+ run(&view),
3421
+ Err(Errno::PermissionDenied),
3422
+ "{call} through an Overlay over a Layer whose permission refuses {mask:?} of \
3423
+ `{name}` must answer that refusal, as overlayfs asks inode_permission of the \
3424
+ real inode"
3425
+ );
3426
+ }
3427
+ }
1955
3428
  }