kobako 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +125 -0
  5. data/Cargo.lock +457 -494
  6. data/README.md +2 -3
  7. data/ROADMAP.md +0 -1
  8. data/crates/kobako-runtime/CHANGELOG.md +90 -0
  9. data/crates/kobako-runtime/Cargo.toml +14 -15
  10. data/crates/kobako-runtime/README.md +1 -1
  11. data/crates/kobako-runtime/src/cred.rs +32 -20
  12. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  13. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
  14. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  15. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
  16. data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
  17. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
  18. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
  19. data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
  20. data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
  21. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  22. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
  23. data/crates/kobako-runtime/src/filesystem.rs +2 -0
  24. data/crates/kobako-runtime/src/fork.rs +239 -16
  25. data/crates/kobako-runtime/src/limits.rs +17 -41
  26. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  27. data/crates/kobako-runtime/src/locking.rs +508 -113
  28. data/crates/kobako-runtime/src/memcg.rs +83 -160
  29. data/crates/kobako-runtime/src/mount.rs +0 -30
  30. data/crates/kobako-runtime/src/net/connections.rs +53 -13
  31. data/crates/kobako-runtime/src/net/egress.rs +44 -24
  32. data/crates/kobako-runtime/src/net/http.rs +888 -456
  33. data/crates/kobako-runtime/src/net/lookup.rs +150 -50
  34. data/crates/kobako-runtime/src/net/namespace.rs +97 -95
  35. data/crates/kobako-runtime/src/net/reactor.rs +298 -203
  36. data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
  37. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
  38. data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
  39. data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
  40. data/crates/kobako-runtime/src/net/resolv.rs +39 -15
  41. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  42. data/crates/kobako-runtime/src/net/socket.rs +51 -52
  43. data/crates/kobako-runtime/src/net/task.rs +223 -0
  44. data/crates/kobako-runtime/src/net/tcp.rs +410 -158
  45. data/crates/kobako-runtime/src/net/tls.rs +65 -3
  46. data/crates/kobako-runtime/src/net/transport.rs +72 -47
  47. data/crates/kobako-runtime/src/net/udp.rs +231 -129
  48. data/crates/kobako-runtime/src/net.rs +3 -0
  49. data/crates/kobako-runtime/src/sched.rs +244 -58
  50. data/crates/kobako-runtime/src/security.rs +27 -16
  51. data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
  52. data/crates/kobako-runtime/src/vfs/file.rs +52 -53
  53. data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
  54. data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
  55. data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
  56. data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
  57. data/crates/kobako-runtime/src/vfs.rs +1 -0
  58. data/crates/kobako-runtime/src/wait.rs +75 -50
  59. data/crates/kobako-transport/CHANGELOG.md +7 -0
  60. data/crates/kobako-transport/Cargo.toml +1 -1
  61. data/crates/kobako-transport/README.md +1 -1
  62. data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
  63. data/crates/kobako-wasmtime/Cargo.toml +27 -6
  64. data/crates/kobako-wasmtime/README.md +3 -3
  65. data/crates/kobako-wasmtime/src/abi.rs +2 -1
  66. data/crates/kobako-wasmtime/src/ambient.rs +11 -2
  67. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  68. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  69. data/crates/kobako-wasmtime/src/cache.rs +88 -103
  70. data/crates/kobako-wasmtime/src/driver.rs +40 -27
  71. data/crates/kobako-wasmtime/src/invocation.rs +21 -7
  72. data/crates/kobako-wasmtime/src/lib.rs +2 -0
  73. data/crates/kobako-wasmtime/src/limiter.rs +78 -25
  74. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
  75. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
  76. data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
  77. data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
  78. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
  79. data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
  80. data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
  81. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  82. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  83. data/crates/kobako-wasmtime/src/preview1.rs +85 -9
  84. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
  85. data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
  86. data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
  87. data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
  88. data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
  89. data/crates/kobako-wasmtime/src/trap.rs +68 -23
  90. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  91. data/crates/kobako-wasmtime/src/wasi.rs +91 -10
  92. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  93. data/data/kobako.wasm +0 -0
  94. data/ext/kobako/Cargo.toml +6 -2
  95. data/ext/kobako/src/escape.rs +332 -26
  96. data/ext/kobako/src/filesystem/grants.rs +5 -7
  97. data/ext/kobako/src/filesystem/ruby.rs +10 -3
  98. data/ext/kobako/src/filesystem.rs +47 -8
  99. data/ext/kobako/src/fork.rs +72 -0
  100. data/ext/kobako/src/gvl.rs +499 -76
  101. data/ext/kobako/src/handoff.rs +490 -0
  102. data/ext/kobako/src/lib.rs +10 -0
  103. data/ext/kobako/src/network.rs +5 -3
  104. data/ext/kobako/src/pinned_value.rs +28 -15
  105. data/ext/kobako/src/runtime/bridge.rs +32 -25
  106. data/ext/kobako/src/runtime.rs +74 -43
  107. data/lib/kobako/catalog/handles.rb +9 -5
  108. data/lib/kobako/codec/decoder.rb +1 -1
  109. data/lib/kobako/codec/state.rb +2 -18
  110. data/lib/kobako/codec/value_budget.rb +4 -4
  111. data/lib/kobako/codec.rb +5 -6
  112. data/lib/kobako/errors.rb +4 -7
  113. data/lib/kobako/filesystem.rb +1 -1
  114. data/lib/kobako/fork.rb +42 -0
  115. data/lib/kobako/handle.rb +1 -2
  116. data/lib/kobako/sandbox.rb +17 -36
  117. data/lib/kobako/sandbox_options.rb +7 -9
  118. data/lib/kobako/usage.rb +4 -2
  119. data/lib/kobako/version.rb +1 -1
  120. data/lib/kobako.rb +2 -2
  121. data/sig/kobako/catalog/handles.rbs +2 -0
  122. data/sig/kobako/codec/state.rbs +0 -4
  123. data/sig/kobako/codec/value_budget.rbs +1 -1
  124. data/sig/kobako/codec.rbs +2 -2
  125. data/sig/kobako/errors.rbs +0 -3
  126. data/sig/kobako/fork.rbs +17 -0
  127. data/sig/kobako/runtime.rbs +2 -2
  128. data/sig/kobako/sandbox.rbs +3 -12
  129. data/sig/kobako/sandbox_options.rbs +0 -2
  130. metadata +15 -4
  131. data/lib/kobako/pool.rb +0 -162
  132. data/sig/core/thread.rbs +0 -6
  133. data/sig/kobako/pool.rbs +0 -46
@@ -2,58 +2,39 @@
2
2
  //! goes on, as 9p's `fid->rdir` holds what its server sent, so a caller reading in
3
3
  //! small steps costs one listing, not one per step.
4
4
 
5
- use crate::cred::Cred;
6
- use crate::memcg::MemoryCharge;
7
5
  use crate::vfs::{Dentry, DirContext, DirEntry, FileType};
8
6
  use crate::Errno;
9
7
 
10
8
  /// The entries a listing began with, `.` and `..` first, on the open directory
11
- /// until it reaches its end, counted against who holds them.
9
+ /// until it reaches its end.
12
10
  #[derive(Default)]
13
- pub struct Rdir(Option<Listing>);
14
-
15
- struct Listing {
16
- entries: Vec<DirEntry>,
17
- /// Gives the entries' bytes back once the listing goes.
18
- _charge: MemoryCharge,
19
- }
20
-
21
- /// Charge the bytes `entries` hold to `cred` for as long as the listing holds
22
- /// them.
23
- fn charge(cred: &Cred, entries: &[DirEntry]) -> Result<MemoryCharge, Errno> {
24
- let names: usize = entries.iter().map(|entry| entry.name.capacity()).sum();
25
- MemoryCharge::new(cred.memory_budget(), size_of_val(entries) + names)
26
- }
11
+ pub struct Rdir(Option<Vec<DirEntry>>);
27
12
 
28
13
  impl Rdir {
29
14
  /// Hand `ctx` the directory from its position. A listing from the start
30
15
  /// reads the directory through `read`, then stats it and what stands above
31
16
  /// it for `.` and `..`, as 9p and FUSE take those from their server and
32
17
  /// `ovl_cache_update` asks `vfs_getattr`; a failure of either answers before
33
- /// any entry. A listing going on reads what that listing began with. Those
34
- /// entries count against the caller from the moment they are read until the
35
- /// listing ends, as `ovl_cache_get` and `v9fs_alloc_rdir_buf` allocate before
36
- /// the first `dir_emit`: past what a security module allows, the listing
37
- /// answers out of memory before it hands any entry.
18
+ /// any entry. A listing going on reads what that listing began with, as
19
+ /// `ovl_cache_get` and `v9fs_alloc_rdir_buf` keep it until the listing ends.
38
20
  pub fn iterate_shared(
39
21
  &mut self,
40
22
  dentry: &Dentry,
41
23
  ctx: &mut DirContext<'_>,
42
24
  read: impl FnOnce() -> Result<Vec<DirEntry>, Errno>,
43
25
  ) -> Result<(), Errno> {
44
- let listing = match self.0.take().filter(|_| ctx.pos() != 0) {
26
+ let entries = match self.0.take().filter(|_| ctx.pos() != 0) {
45
27
  Some(held) => held,
46
28
  None => {
47
29
  let read = read()?;
48
30
  let mut entries = dots(dentry)?;
49
31
  entries.extend(read);
50
32
  entries.shrink_to_fit();
51
- let _charge = charge(ctx.cred(), &entries)?;
52
- Listing { entries, _charge }
33
+ entries
53
34
  }
54
35
  };
55
- if !emit_from(ctx, &listing.entries) {
56
- self.0 = Some(listing);
36
+ if !emit_from(ctx, &entries) {
37
+ self.0 = Some(entries);
57
38
  }
58
39
  Ok(())
59
40
  }
@@ -0,0 +1,31 @@
1
+ //! Host links the Filesystem tests stage beneath a Bind.
2
+
3
+ use std::path::Path;
4
+
5
+ /// Make a host link at `at` leading to `target`, spelled as a unix path.
6
+ /// Windows makes a link to a directory apart from one to a file, so there
7
+ /// the kind follows what `target` names now, a file where nothing stands,
8
+ /// and `target` takes the host's separator.
9
+ pub(crate) fn symlink(target: impl AsRef<Path>, at: impl AsRef<Path>) {
10
+ let (target, at) = (target.as_ref(), at.as_ref());
11
+ #[cfg(unix)]
12
+ let made = std::os::unix::fs::symlink(target, at);
13
+ #[cfg(windows)]
14
+ let made = {
15
+ let target = std::path::PathBuf::from(target.to_string_lossy().replace('/', "\\"));
16
+ let beside = at.parent().unwrap_or(Path::new(""));
17
+ if beside.join(&target).is_dir() {
18
+ std::os::windows::fs::symlink_dir(&target, at)
19
+ } else {
20
+ std::os::windows::fs::symlink_file(&target, at)
21
+ }
22
+ };
23
+ made.unwrap_or_else(|err| {
24
+ panic!(
25
+ "the host must make a link at {} to {}: {err}; a Windows host makes one only \
26
+ in Developer Mode or with the privilege to create symbolic links",
27
+ at.display(),
28
+ target.display()
29
+ )
30
+ });
31
+ }
@@ -470,8 +470,9 @@ const BOGO_DIRENT_SIZE: u64 = 20;
470
470
 
471
471
  impl Tmpfs {
472
472
  /// The most bytes a Tmpfs's files hold unless given a limit of their
473
- /// own: the size Docker gives a `--tmpfs` mount.
474
- pub const DEFAULT_SIZE: usize = 64 * 1024 * 1024;
473
+ /// own: room for a script's scratch files, as most scripts need far
474
+ /// less, while a Host App that needs more says so.
475
+ pub const DEFAULT_SIZE: usize = 4 * 1024 * 1024;
475
476
 
476
477
  pub fn new() -> Self {
477
478
  let space = Space {
@@ -762,6 +763,10 @@ impl FileOperations for TmpfsDir {
762
763
  generic_read_dir()
763
764
  }
764
765
 
766
+ fn has_iterate_shared(&self) -> bool {
767
+ true
768
+ }
769
+
765
770
  /// Reads on from each name's stable position, as `offset_readdir` does, so
766
771
  /// nothing is held between two calls.
767
772
  fn iterate_shared(&mut self, dentry: &Dentry, ctx: &mut DirContext<'_>) -> Result<(), Errno> {
@@ -769,6 +774,7 @@ impl FileOperations for TmpfsDir {
769
774
  return Ok(());
770
775
  }
771
776
  loop {
777
+ crate::sched::stop_if_fatal()?;
772
778
  let found = {
773
779
  let state = self.dir.state();
774
780
  state
@@ -1176,6 +1182,19 @@ mod tests {
1176
1182
  );
1177
1183
  }
1178
1184
 
1185
+ /// Set every time of what stands at `path` to a moment long past, so a
1186
+ /// time a later change sets differs from it whatever the clock's
1187
+ /// resolution.
1188
+ fn set_long_ago(fs: &KernPath, path: &str) {
1189
+ let long_ago = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1);
1190
+ let at = Some(SetTime::At(long_ago));
1191
+ let attr = Iattr {
1192
+ ctime: Some(long_ago),
1193
+ ..Iattr::for_times(at, at)
1194
+ };
1195
+ fs.setattr(path, &attr).expect("the times must be set");
1196
+ }
1197
+
1179
1198
  fn at(tmpfs: Tmpfs) -> KernPath {
1180
1199
  kern_path(Arc::new(tmpfs))
1181
1200
  }
@@ -1360,14 +1379,14 @@ mod tests {
1360
1379
  fn a_tmpfs_holds_its_default_size() {
1361
1380
  let tmpfs = at(Tmpfs::new());
1362
1381
  let _file = writable(&tmpfs, "file");
1363
- let mib_64 = 64 * 1024 * 1024;
1382
+ let mib_4 = 4 * 1024 * 1024;
1364
1383
  assert_eq!(
1365
1384
  (
1366
- tmpfs.truncate("file", mib_64),
1367
- tmpfs.truncate("file", mib_64 + 1)
1385
+ tmpfs.truncate("file", mib_4),
1386
+ tmpfs.truncate("file", mib_4 + 1)
1368
1387
  ),
1369
1388
  (Ok(()), Err(Errno::StorageFull)),
1370
- "a Tmpfs given no limit through Tmpfs::new must hold 64 MiB and refuse a byte more"
1389
+ "a Tmpfs given no limit through Tmpfs::new must hold 4 MiB and refuse a byte more"
1371
1390
  );
1372
1391
  }
1373
1392
 
@@ -1379,7 +1398,7 @@ mod tests {
1379
1398
  assert_eq!(
1380
1399
  tmpfs.truncate("file", Tmpfs::DEFAULT_SIZE as u64 + 1),
1381
1400
  Ok(()),
1382
- "a Tmpfs given no limit through Tmpfs::with_size(None) must grow past 64 MiB"
1401
+ "a Tmpfs given no limit through Tmpfs::with_size(None) must grow past 4 MiB"
1383
1402
  );
1384
1403
  }
1385
1404
 
@@ -1480,6 +1499,21 @@ mod tests {
1480
1499
  );
1481
1500
  }
1482
1501
 
1502
+ // @behavior FS-238
1503
+ #[test]
1504
+ fn a_tmpfs_holds_its_default_entries() {
1505
+ let tmpfs = at(Tmpfs::new());
1506
+ let created: Vec<_> = (0..1025)
1507
+ .map(|index| create(&tmpfs, &format!("{index}")))
1508
+ .collect();
1509
+ assert_eq!(
1510
+ (created[..1024].iter().all(Result::is_ok), &created[1024]),
1511
+ (true, &Err(Errno::StorageFull)),
1512
+ "a Tmpfs given neither a size nor inodes through Tmpfs::new must hold 1024 files \
1513
+ beside its root and refuse the next as out of space"
1514
+ );
1515
+ }
1516
+
1483
1517
  // The second handle opened before the first appended, so only an end
1484
1518
  // read as the append lands puts its bytes after the first's.
1485
1519
  // @behavior FS-036
@@ -1717,14 +1751,14 @@ mod tests {
1717
1751
  }
1718
1752
 
1719
1753
  // The content stands as it was, so only `st_ctime` tells the name moved, as
1720
- // `simple_rename_timestamp` moves it alone. The wait passes the clock's
1721
- // resolution, so the two times cannot pass for one.
1754
+ // `simple_rename_timestamp` moves it alone. The times start long past, so
1755
+ // the two cannot pass for one whatever the clock's resolution.
1722
1756
  // @behavior FS-177
1723
1757
  #[test]
1724
1758
  fn a_moved_file_moves_only_its_changed_time() {
1725
1759
  let tmpfs = at([("file", "x")].into_iter().collect());
1760
+ set_long_ago(&tmpfs, "file");
1726
1761
  let before = tmpfs.vfs_lstat("file").expect("the file must stand");
1727
- std::thread::sleep(std::time::Duration::from_millis(20));
1728
1762
  tmpfs
1729
1763
  .rename("file", &tmpfs, "moved")
1730
1764
  .expect("the move must land");
@@ -1825,8 +1859,8 @@ mod tests {
1825
1859
  );
1826
1860
  }
1827
1861
 
1828
- // The write waits past the clock's resolution, so a time left where
1829
- // the file was made cannot pass for one the write moved.
1862
+ // The file's times are set long past before it is read, so a time left
1863
+ // where it was cannot pass for one the write moved.
1830
1864
  // @behavior FS-115
1831
1865
  #[test]
1832
1866
  fn a_tmpfs_keeps_a_files_times_as_a_tmpfs_mounted_noatime_does() {
@@ -1841,10 +1875,10 @@ mod tests {
1841
1875
  .expect("the file must be made");
1842
1876
  file.write_iter(&mut Kiocb::new(0), b"ab")
1843
1877
  .expect("the file must take a write");
1878
+ set_long_ago(&tmpfs, "file");
1844
1879
  let made = tmpfs.vfs_lstat("file").expect("the file must report");
1845
1880
  file.read_iter(&mut Kiocb::new(0), &mut [0; 1])
1846
1881
  .expect("the file must read");
1847
- std::thread::sleep(std::time::Duration::from_millis(10));
1848
1882
  file.write_iter(&mut Kiocb::new(0), b"c")
1849
1883
  .expect("the file must take a write within its length");
1850
1884
  let written = tmpfs.vfs_lstat("file").expect("the file must stand");
@@ -9,6 +9,8 @@ mod bind;
9
9
  mod overlay;
10
10
  mod pipe;
11
11
  mod rdir;
12
+ #[cfg(test)]
13
+ pub(crate) mod testing;
12
14
  mod tmpfs;
13
15
  #[cfg(test)]
14
16
  pub(crate) mod wrap;
@@ -3,17 +3,33 @@
3
3
  //! process — a count of what its own threads hold, or a thread it started — is
4
4
  //! the parent's alone, so the child starts from none.
5
5
 
6
+ use std::marker::PhantomData;
7
+ use std::ptr;
8
+ use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
6
9
  use std::sync::{Mutex, PoisonError};
7
10
 
8
- /// The process a value was made in, as Linux's `struct pid` names a task: a
9
- /// forked child inherits the value, but not having made it.
10
- #[derive(Clone, Copy, PartialEq, Eq)]
11
- pub(crate) struct Pid(u32);
11
+ /// How many forks this process descends through, as each child counts one
12
+ /// more in the handler `pthread_atfork` runs for it.
13
+ static GENERATION: AtomicU64 = AtomicU64::new(0);
14
+
15
+ /// The process a value was made in, as Linux's `struct pid` names a task
16
+ /// apart from any later one given its number: a forked child inherits the
17
+ /// value, but not having made it, and neither does a descendant that the
18
+ /// number came round to.
19
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
20
+ pub(crate) struct Pid {
21
+ number: u32,
22
+ generation: u64,
23
+ }
12
24
 
13
25
  impl Pid {
14
26
  /// This process.
15
27
  pub(crate) fn current() -> Self {
16
- Self(std::process::id())
28
+ count_forks();
29
+ Self {
30
+ number: std::process::id(),
31
+ generation: GENERATION.load(Ordering::Relaxed),
32
+ }
17
33
  }
18
34
 
19
35
  /// Whether this process is the one named.
@@ -24,40 +40,119 @@ impl Pid {
24
40
  /// Another process than this one, as a forked child sees its parent.
25
41
  #[cfg(test)]
26
42
  pub(crate) fn parent() -> Self {
27
- Self(std::process::id().wrapping_add(1))
43
+ let current = Self::current();
44
+ Self {
45
+ number: current.number.wrapping_add(1),
46
+ ..current
47
+ }
48
+ }
49
+ }
50
+
51
+ /// Count each fork from here on in the child, so a descendant given a dead
52
+ /// ancestor's number still tells itself apart. The handler only adds, which
53
+ /// is all a child may do before it returns from `fork`.
54
+ #[cfg(unix)]
55
+ fn count_forks() {
56
+ static REGISTER: std::sync::Once = std::sync::Once::new();
57
+ extern "C" fn forked() {
58
+ GENERATION.fetch_add(1, Ordering::Relaxed);
28
59
  }
60
+ REGISTER.call_once(|| {
61
+ // SAFETY: `forked` touches one atomic, as a child handler may.
62
+ let err = unsafe { libc::pthread_atfork(None, None, Some(forked)) };
63
+ assert_eq!(err, 0, "pthread_atfork must take the fork handler");
64
+ });
29
65
  }
30
66
 
67
+ /// A process that cannot fork has no child to tell apart.
68
+ #[cfg(not(unix))]
69
+ fn count_forks() {}
70
+
31
71
  /// A value of the process that made it, as `thread_local!` keeps one per
32
72
  /// thread: a forked child, which inherits the memory but none of the parent's
33
73
  /// other threads, sees none until it makes its own.
34
74
  pub struct ProcessLocal<T> {
35
- slot: Mutex<(Option<Pid>, Option<T>)>,
75
+ slot: AtomicPtr<Slot<T>>,
76
+ /// Shared across threads as each slot's lock is.
77
+ _value: PhantomData<Mutex<Option<T>>>,
78
+ }
79
+
80
+ /// One process's value, behind a lock of its own.
81
+ struct Slot<T> {
82
+ owner: Pid,
83
+ value: Mutex<Option<T>>,
36
84
  }
37
85
 
38
86
  impl<T> ProcessLocal<T> {
39
87
  /// None made yet.
40
88
  pub const fn new() -> Self {
41
89
  Self {
42
- slot: Mutex::new((None, None)),
90
+ slot: AtomicPtr::new(ptr::null_mut()),
91
+ _value: PhantomData,
43
92
  }
44
93
  }
45
94
 
46
- /// Run `f` on what this process holds, emptied first when another process
47
- /// made it.
95
+ /// Run `f` on what this process holds, none when another process made
96
+ /// what is held.
48
97
  pub fn with<R>(&self, f: impl FnOnce(&mut Option<T>) -> R) -> R {
49
- let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
50
- if !slot.0.is_some_and(Pid::is_current) {
51
- *slot = (Some(Pid::current()), None);
98
+ let mut value = self
99
+ .own_slot()
100
+ .value
101
+ .lock()
102
+ .unwrap_or_else(PoisonError::into_inner);
103
+ f(&mut value)
104
+ }
105
+
106
+ /// This process's slot, put in place of another process's, which is left
107
+ /// as it was: a thread that never came along may hold its lock, and its
108
+ /// value may close what this process no longer owns, as a kqueue the
109
+ /// fork did not copy.
110
+ fn own_slot(&self) -> &Slot<T> {
111
+ let current = Pid::current();
112
+ let mut held = self.slot.load(Ordering::Acquire);
113
+ loop {
114
+ // SAFETY: a slot in place is freed only as the ProcessLocal drops.
115
+ if let Some(slot) = unsafe { held.as_ref() } {
116
+ if slot.owner == current {
117
+ return slot;
118
+ }
119
+ }
120
+ let fresh = Box::into_raw(Box::new(Slot {
121
+ owner: current,
122
+ value: Mutex::new(None),
123
+ }));
124
+ match self
125
+ .slot
126
+ .compare_exchange(held, fresh, Ordering::AcqRel, Ordering::Acquire)
127
+ {
128
+ // SAFETY: `fresh` is in place, freed only as above.
129
+ Ok(_) => return unsafe { &*fresh },
130
+ Err(now) => {
131
+ // SAFETY: `fresh` never left this thread.
132
+ drop(unsafe { Box::from_raw(fresh) });
133
+ held = now;
134
+ }
135
+ }
52
136
  }
53
- f(&mut slot.1)
54
137
  }
55
138
 
56
139
  /// Stand in for a fork: what is held now was made by another process.
57
140
  #[cfg(test)]
58
141
  pub(crate) fn inherit(&self) {
59
- let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
60
- slot.0 = Some(Pid::parent());
142
+ self.inherit_from(Pid::parent());
143
+ }
144
+
145
+ /// Stand in for a fork from `parent`. The slot this process made is left
146
+ /// in place for any thread still holding it, as a fork leaves the
147
+ /// parent's.
148
+ #[cfg(test)]
149
+ fn inherit_from(&self, parent: Pid) {
150
+ let value = self.with(Option::take);
151
+ let inherited = Box::into_raw(Box::new(Slot {
152
+ owner: parent,
153
+ value: Mutex::new(value),
154
+ }));
155
+ self.slot.store(inherited, Ordering::Release);
61
156
  }
62
157
  }
63
158
 
@@ -67,10 +162,34 @@ impl<T> Default for ProcessLocal<T> {
67
162
  }
68
163
  }
69
164
 
165
+ impl<T> Drop for ProcessLocal<T> {
166
+ fn drop(&mut self) {
167
+ let held = *self.slot.get_mut();
168
+ // SAFETY: a slot in place is freed only here.
169
+ if unsafe { held.as_ref() }.is_some_and(|slot| slot.owner.is_current()) {
170
+ // SAFETY: as above, and nothing borrows `self` any more.
171
+ drop(unsafe { Box::from_raw(held) });
172
+ }
173
+ }
174
+ }
175
+
70
176
  #[cfg(test)]
71
177
  mod tests {
178
+ use std::sync::atomic::AtomicUsize;
179
+ use std::sync::{Arc, Barrier};
180
+ use std::thread;
181
+
72
182
  use super::*;
73
183
 
184
+ /// Counts each drop of itself.
185
+ struct CountsDrops(Arc<AtomicUsize>);
186
+
187
+ impl Drop for CountsDrops {
188
+ fn drop(&mut self) {
189
+ self.0.fetch_add(1, Ordering::SeqCst);
190
+ }
191
+ }
192
+
74
193
  #[test]
75
194
  fn a_value_made_in_another_process_is_not_handed_out() {
76
195
  let local = ProcessLocal::new();
@@ -93,4 +212,108 @@ mod tests {
93
212
  "a ProcessLocal must keep what this process made"
94
213
  );
95
214
  }
215
+
216
+ #[test]
217
+ fn a_value_an_ancestor_under_the_same_number_made_is_not_handed_out() {
218
+ let local = ProcessLocal::new();
219
+ local.with(|held| *held = Some(1));
220
+ let current = Pid::current();
221
+ local.inherit_from(Pid {
222
+ generation: current.generation.wrapping_sub(1),
223
+ ..current
224
+ });
225
+ assert_eq!(
226
+ local.with(|held| *held),
227
+ None,
228
+ "a ProcessLocal must hand none of what an ancestor made to a descendant that its \
229
+ process number came round to"
230
+ );
231
+ }
232
+
233
+ #[test]
234
+ fn a_value_made_in_another_process_is_never_dropped() {
235
+ let drops = Arc::new(AtomicUsize::new(0));
236
+ let local = ProcessLocal::new();
237
+ local.with(|held| *held = Some(CountsDrops(drops.clone())));
238
+ local.inherit();
239
+ local.with(|held| *held = Some(CountsDrops(Arc::new(AtomicUsize::new(0)))));
240
+ drop(local);
241
+ assert_eq!(
242
+ drops.load(Ordering::SeqCst),
243
+ 0,
244
+ "a ProcessLocal must never drop what another process made, which may close what \
245
+ the forked child no longer owns"
246
+ );
247
+ }
248
+
249
+ #[test]
250
+ fn a_value_made_in_this_process_drops_with_it() {
251
+ let drops = Arc::new(AtomicUsize::new(0));
252
+ let local = ProcessLocal::new();
253
+ local.with(|held| *held = Some(CountsDrops(drops.clone())));
254
+ drop(local);
255
+ assert_eq!(
256
+ drops.load(Ordering::SeqCst),
257
+ 1,
258
+ "a ProcessLocal must drop what this process made as it drops"
259
+ );
260
+ }
261
+
262
+ #[test]
263
+ fn threads_replacing_an_inherited_value_at_once_share_one() {
264
+ const THREADS: usize = 8;
265
+ let local = Arc::new(ProcessLocal::<usize>::new());
266
+ local.with(|held| *held = Some(100));
267
+ local.inherit();
268
+ let start = Arc::new(Barrier::new(THREADS));
269
+ let threads: Vec<_> = (0..THREADS)
270
+ .map(|_| {
271
+ let (local, start) = (local.clone(), start.clone());
272
+ thread::spawn(move || {
273
+ start.wait();
274
+ local.with(|held| *held.get_or_insert(0) += 1);
275
+ })
276
+ })
277
+ .collect();
278
+ threads.into_iter().for_each(|t| t.join().unwrap());
279
+ assert_eq!(
280
+ local.with(|held| *held),
281
+ Some(THREADS),
282
+ "threads of a forked child replacing an inherited value at once must all count on \
283
+ the one value this process puts in place"
284
+ );
285
+ }
286
+
287
+ #[cfg(unix)]
288
+ #[test]
289
+ fn a_forked_child_counts_one_generation_more() {
290
+ let parent = Pid::current();
291
+ let mut ends = [0; 2];
292
+ // SAFETY: a pipe into two descriptors this test owns.
293
+ assert_eq!(unsafe { libc::pipe(ends.as_mut_ptr()) }, 0, "a pipe opens");
294
+ // SAFETY: the child only reads an atomic, writes, and exits.
295
+ let child = unsafe { libc::fork() };
296
+ if child == 0 {
297
+ let generation = Pid::current().generation.to_ne_bytes();
298
+ // SAFETY: the child writes its generation and exits at once.
299
+ unsafe {
300
+ libc::write(ends[1], generation.as_ptr().cast(), generation.len());
301
+ libc::_exit(0);
302
+ }
303
+ }
304
+ let mut read = [0u8; 8];
305
+ // SAFETY: reading into a buffer this test owns, then reaping the child.
306
+ unsafe {
307
+ libc::close(ends[1]);
308
+ libc::read(ends[0], read.as_mut_ptr().cast(), read.len());
309
+ libc::close(ends[0]);
310
+ libc::waitpid(child, ptr::null_mut(), 0);
311
+ }
312
+ assert_eq!(
313
+ u64::from_ne_bytes(read),
314
+ parent.generation + 1,
315
+ "a child forked after kobako named its process must count one fork more than its \
316
+ parent, so a descendant given the parent's number tells itself apart"
317
+ );
318
+ }
96
319
  }
@@ -22,29 +22,29 @@ pub struct Limits {
22
22
  pub stdout_limit: Option<usize>,
23
23
  /// Byte cap for guest stderr capture, the same as `stdout_limit`.
24
24
  pub stderr_limit: Option<usize>,
25
- /// Descriptors one invocation may hold open, the standard ones and each
26
- /// outermost Mount's preopen included; an open past it answers `MFILE`.
27
- /// Only the guest's descriptors count, as `RLIMIT_NOFILE` counts a
28
- /// process's: the host descriptors a Filesystem holds behind one are
29
- /// its own, up to two for a file and one for each Layer holding a
30
- /// directory, Directory Layers alone holding any.
25
+ /// Descriptors one invocation may hold open, the standard ones and the
26
+ /// root's preopen included; an open past it answers `MFILE`. Only the
27
+ /// guest's descriptors count, as `RLIMIT_NOFILE` counts a process's: the
28
+ /// host descriptors a Filesystem holds behind one are its own, one for
29
+ /// each Bind Layer holding an Overlay's directory.
31
30
  pub open_file_limit: Option<usize>,
32
31
  /// Connections one invocation holds open at once, each socket, HTTP request,
33
32
  /// and name lookup in flight one; one past it answers `EAGAIN`.
34
33
  pub open_connection_limit: Option<usize>,
35
- /// Connections one invocation makes in all, each socket and HTTP request
36
- /// one, as a budget of subrequests is counted; one past it answers
37
- /// `EAGAIN`.
34
+ /// Connections one invocation makes in all, each lookup, dial, and HTTP
35
+ /// request one, spent before it leaves the host and never given back, as a
36
+ /// budget of subrequests is counted; one past it answers `EAGAIN`.
38
37
  pub connection_limit: Option<usize>,
39
38
  }
40
39
 
41
40
  impl Default for Limits {
42
41
  /// A 60-second deadline, 10 seconds to set the Guest Binary up, 4 MiB of
43
- /// memory growth, sized for a guest whose every value takes 16 bytes,
44
- /// 1 MiB for each output channel, 1024 open files, the soft limit Linux
45
- /// gives a process (`INR_OPEN_CUR`), and 6 open connections and 50 in
46
- /// all, as a Cloudflare Worker may hold 6 waiting and make 50
47
- /// subrequests on its free plan.
42
+ /// memory growth, 1 MiB for each output channel, 16 open files, and 6 open connections
43
+ /// and 50 in all, as a Cloudflare Worker may hold 6 waiting and make 50
44
+ /// subrequests on its free plan. The open files are far below the 1024
45
+ /// Linux gives a process (`INR_OPEN_CUR`), since every invocation shares
46
+ /// one process's descriptors: 16 leaves room for 6 files with every
47
+ /// connection open beside the standard descriptors and the root.
48
48
  fn default() -> Self {
49
49
  Limits {
50
50
  timeout: Some(Duration::from_secs(60)),
@@ -52,24 +52,14 @@ impl Default for Limits {
52
52
  memory_limit: Some(4 << 20),
53
53
  stdout_limit: Some(1 << 20),
54
54
  stderr_limit: Some(1 << 20),
55
- open_file_limit: Some(1024),
55
+ open_file_limit: Some(16),
56
56
  open_connection_limit: Some(6),
57
57
  connection_limit: Some(50),
58
58
  }
59
59
  }
60
60
  }
61
61
 
62
- /// The least guest memory one value occupies, so a guest payload may hold one
63
- /// value for each of these bytes of the memory cap.
64
- const VALUE_BYTES: usize = 16;
65
-
66
62
  impl Limits {
67
- /// The most values a guest payload may make the host build, one for each
68
- /// `VALUE_BYTES` of `memory_limit`; none where memory is not capped.
69
- pub fn value_budget(&self) -> Option<usize> {
70
- self.memory_limit.map(|limit| limit / VALUE_BYTES)
71
- }
72
-
73
63
  /// Each cap, named by the option a Host App sets it with, so every
74
64
  /// frontend reads and writes the caps from this one list.
75
65
  pub fn caps_mut(&mut self) -> [(&'static str, Cap<'_>); 8] {
@@ -143,26 +133,12 @@ mod tests {
143
133
  memory_limit: Some(4 * 1024 * 1024),
144
134
  stdout_limit: Some(1024 * 1024),
145
135
  stderr_limit: Some(1024 * 1024),
146
- open_file_limit: Some(1024),
136
+ open_file_limit: Some(16),
147
137
  open_connection_limit: Some(6),
148
138
  connection_limit: Some(50),
149
139
  },
150
140
  "a Sandbox given no caps must start under a 60 s deadline, 10 s of setup, 4 MiB of \
151
- memory, 1 MiB per output channel, 1024 open files, and 6 open connections of 50"
152
- );
153
- }
154
-
155
- #[test]
156
- fn a_payload_holds_one_value_for_each_sixteen_bytes_of_memory() {
157
- let uncapped = Limits {
158
- memory_limit: None,
159
- ..Limits::default()
160
- };
161
- assert_eq!(
162
- (Limits::default().value_budget(), uncapped.value_budget()),
163
- (Some(4 * 1024 * 1024 / 16), None),
164
- "Limits::value_budget must allow one value for each 16 bytes of memory_limit, and \
165
- none to count where memory is not capped"
141
+ memory, 1 MiB per output channel, 16 open files, and 6 open connections of 50"
166
142
  );
167
143
  }
168
144