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
@@ -4,38 +4,250 @@
4
4
  //! here instead of answering the guest with it, the invocation ends at its next
5
5
  //! host call, and the run raises it again once control is back in Ruby.
6
6
  //!
7
- //! The slot is per thread, as each invocation runs on its caller's
8
- //! thread. A nested invocation takes what its own run held before the
9
- //! outer callback sees it, so the outer one holds it next. What a run held
10
- //! belongs to it alone: one ending by a panic drops it, and a thread outside
11
- //! any run holds nothing, since no run would raise it again.
7
+ //! The slot is the run's, kept for the Fiber that started it, since a run's
8
+ //! callbacks come back on that Fiber whatever native thread it is on, and
9
+ //! another Fiber's run on the same Thread is a run of its own. A nested
10
+ //! invocation takes what its own run held before the outer callback sees it,
11
+ //! so the outer one holds it next. What a run held belongs to it alone: one
12
+ //! ending by a panic drops it, and a Fiber outside any run holds nothing,
13
+ //! since no run would raise it again.
12
14
 
13
- use std::cell::{Cell, RefCell};
15
+ use std::collections::HashMap;
16
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
17
+ use std::sync::{Arc, Mutex, PoisonError};
14
18
 
19
+ use kobako_runtime::fork::ProcessLocal;
20
+ use kobako_runtime::sched::Current;
21
+ use kobako_runtime::wait::{do_poll, poll_wait, PollTable, WaitQueueHead};
15
22
  use magnus::value::BoxValue;
16
23
  use magnus::{Error as MagnusError, Ruby, Value};
17
24
 
18
- thread_local! {
19
- static ESCAPE: RefCell<Option<Escape>> = const { RefCell::new(None) };
20
- static RUNS: Cell<usize> = const { Cell::new(0) };
25
+ use super::handoff::{self, Line};
26
+
27
+ /// The runs in progress, each under the Fiber that started it, and the forks
28
+ /// holding new ones back. A forked child starts from none, as the process
29
+ /// made none of its own.
30
+ static RUNS: ProcessLocal<Runs> = ProcessLocal::new();
31
+
32
+ #[derive(Default)]
33
+ struct Runs {
34
+ by_fiber: HashMap<FiberId, Arc<RunState>>,
35
+ /// The guests of runs whose caller was collected, in progress until each
36
+ /// ends. The Fiber's address is free for another run once collected.
37
+ ending: Vec<Arc<Line>>,
38
+ /// The forks under way, each found no run in progress.
39
+ forks: usize,
40
+ /// The outermost runs waiting for the forks under way to return.
41
+ waiting: Vec<(FiberId, Arc<RunState>)>,
42
+ /// Woken as the last fork under way returns.
43
+ opened: Arc<WaitQueueHead>,
44
+ }
45
+
46
+ impl Runs {
47
+ /// Whether a run is in progress, one whose caller was collected included
48
+ /// until its guest ends.
49
+ fn in_progress(&mut self) -> bool {
50
+ self.ending.retain(|line| !line.has_ended());
51
+ !self.by_fiber.is_empty() || !self.ending.is_empty()
52
+ }
53
+ }
54
+
55
+ /// Run `f` on the runs in progress.
56
+ fn with_runs<R>(f: impl FnOnce(&mut Runs) -> R) -> R {
57
+ RUNS.with(|runs| f(runs.get_or_insert_with(Runs::default)))
58
+ }
59
+
60
+ /// Forget the run on `fiber`.
61
+ fn remove(fiber: FiberId) {
62
+ with_runs(|runs| runs.by_fiber.remove(&fiber));
21
63
  }
22
64
 
23
- /// One invocation or compile on this thread, which raises what it held once
65
+ /// Wait, without the GVL, until the last fork under way enters the run on
66
+ /// `fiber`. An interrupt ends the wait, and the run gives back its place,
67
+ /// whether still waiting or entered as the interrupt came.
68
+ fn wait_for_forks(ruby: &Ruby, fiber: FiberId) -> Result<(), MagnusError> {
69
+ let entered = |table: Option<&mut PollTable>| {
70
+ with_runs(|runs| {
71
+ poll_wait(&runs.opened, table);
72
+ runs.by_fiber.contains_key(&fiber).then_some(())
73
+ })
74
+ };
75
+ loop {
76
+ if let Ok(Some(())) = do_poll(|| None, &entered) {
77
+ return Ok(());
78
+ }
79
+ if let Err(interrupt) = ruby.thread_check_ints() {
80
+ with_runs(|runs| {
81
+ runs.waiting.retain(|(waiting, _)| *waiting != fiber);
82
+ runs.by_fiber.remove(&fiber);
83
+ });
84
+ return Err(interrupt);
85
+ }
86
+ }
87
+ }
88
+
89
+ /// Hold new runs back for a fork, unless a run is in progress, which a forked
90
+ /// child would inherit the locks of. Checking and holding back are one step,
91
+ /// so no run starts between them.
92
+ pub(super) fn hold_runs_back() -> bool {
93
+ with_runs(|runs| {
94
+ let held = !runs.in_progress();
95
+ if held {
96
+ runs.forks += 1;
97
+ }
98
+ held
99
+ })
100
+ }
101
+
102
+ /// Let runs in again as a fork that held them back returns. The last one
103
+ /// enters every waiting run in the same step, so no fork closes the gate
104
+ /// before they do. A forked child held none back.
105
+ pub(super) fn let_runs_in() {
106
+ let opened = with_runs(|runs| {
107
+ runs.forks = runs.forks.saturating_sub(1);
108
+ if runs.forks == 0 {
109
+ let waiting = std::mem::take(&mut runs.waiting);
110
+ runs.by_fiber.extend(waiting);
111
+ }
112
+ runs.opened.clone()
113
+ });
114
+ opened.wake_up();
115
+ }
116
+
117
+ /// One outermost run on a Fiber and the runs nested in its callbacks.
118
+ pub(super) struct RunState {
119
+ /// The task every thread carrying the run out shares, so a lock its
120
+ /// guest holds knows a nested run's guest, or a guest of a run another
121
+ /// Fiber of the Thread starts meanwhile, as the same owner.
122
+ task: Current,
123
+ held: Mutex<Option<Escape>>,
124
+ /// Whether `held` holds an error, read by the guest's own thread.
125
+ pending: Arc<AtomicBool>,
126
+ depth: Mutex<usize>,
127
+ /// The line to each guest of the run and its nested runs, innermost last.
128
+ lines: Mutex<Vec<Arc<Line>>>,
129
+ /// The Ruby objects the run's guests reach, one entry for each pin. The
130
+ /// run's caller marks them, so the collector keeps them where they stand
131
+ /// while the caller does, and frees them with a caller that never came back.
132
+ pins: Mutex<Vec<rb_sys::VALUE>>,
133
+ /// The Ruby Thread the run started on, pinned so it stays where it stands.
134
+ thread: rb_sys::VALUE,
135
+ }
136
+
137
+ impl RunState {
138
+ fn is_running(&self) -> bool {
139
+ *lock(&self.depth) > 0
140
+ }
141
+
142
+ /// Keep `value` for the run.
143
+ pub(super) fn pin(&self, value: rb_sys::VALUE) {
144
+ lock(&self.pins).push(value);
145
+ }
146
+
147
+ /// Let go of one pin of `value`.
148
+ pub(super) fn unpin(&self, value: rb_sys::VALUE) {
149
+ let mut pins = lock(&self.pins);
150
+ if let Some(at) = pins.iter().position(|&pinned| pinned == value) {
151
+ pins.swap_remove(at);
152
+ }
153
+ }
154
+
155
+ /// The Ruby objects the run keeps, for its caller to mark.
156
+ pub(super) fn pinned(&self) -> Vec<rb_sys::VALUE> {
157
+ lock(&self.pins).clone()
158
+ }
159
+
160
+ pub(super) fn task(&self) -> &Current {
161
+ &self.task
162
+ }
163
+
164
+ /// Run `serve` with `line` as the run's innermost, so a guest block its
165
+ /// callbacks call finds the guest it belongs to.
166
+ pub(super) fn lending<R>(&self, line: &Arc<Line>, serve: impl FnOnce() -> R) -> R {
167
+ /// Takes the line back however `serve` ends.
168
+ struct Lent<'a>(&'a RunState);
169
+
170
+ impl Drop for Lent<'_> {
171
+ fn drop(&mut self) {
172
+ lock(&self.0.lines).pop();
173
+ }
174
+ }
175
+
176
+ lock(&self.lines).push(line.clone());
177
+ let _lent = Lent(self);
178
+ serve()
179
+ }
180
+
181
+ /// The line to the run's innermost guest.
182
+ pub(super) fn innermost_line(&self) -> Option<Arc<Line>> {
183
+ lock(&self.lines).last().cloned()
184
+ }
185
+
186
+ /// Whether the run holds an error, as its guest's thread asks it.
187
+ pub(super) fn pending_flag(&self) -> Arc<AtomicBool> {
188
+ self.pending.clone()
189
+ }
190
+ }
191
+
192
+ /// One invocation or compile on this Fiber, which raises what it held once
24
193
  /// it is back in Ruby.
25
194
  pub(super) struct Run {
195
+ fiber: FiberId,
196
+ state: Arc<RunState>,
26
197
  finished: bool,
27
198
  }
28
199
 
29
200
  impl Run {
30
- pub(super) fn enter() -> Self {
31
- RUNS.with(|runs| runs.set(runs.get() + 1));
32
- Self { finished: false }
201
+ /// Enter a run on the calling Fiber: a nested one shares the run its
202
+ /// Fiber is in, an outermost one starts a run of its own. Locks know an
203
+ /// outermost one as the run another Fiber of the Thread has in progress,
204
+ /// as CRuby refuses a Mutex another Fiber of the Thread owns, unless
205
+ /// `scheduler_waits` says a Fiber scheduler takes the run's waits, as
206
+ /// CRuby leaves a Mutex wait to the scheduler.
207
+ ///
208
+ /// An outermost run waits while a fork is under way, counted in
209
+ /// `waiting`, its Sandbox's runs waiting, and raises what interrupts that
210
+ /// wait.
211
+ pub(super) fn enter(
212
+ ruby: &Ruby,
213
+ waiting: &AtomicUsize,
214
+ scheduler_waits: bool,
215
+ ) -> Result<Self, MagnusError> {
216
+ let fiber = fiber_id();
217
+ let state = match with_runs(|runs| runs.by_fiber.get(&fiber).cloned()) {
218
+ Some(state) => state,
219
+ None => {
220
+ let state = start(scheduler_waits);
221
+ let entered = with_runs(|runs| {
222
+ if runs.forks == 0 {
223
+ runs.by_fiber.insert(fiber, state.clone());
224
+ } else {
225
+ runs.waiting.push((fiber, state.clone()));
226
+ }
227
+ runs.forks == 0
228
+ });
229
+ if !entered {
230
+ handoff::count_waiting(waiting, || wait_for_forks(ruby, fiber))?;
231
+ }
232
+ state
233
+ }
234
+ };
235
+ *lock(&state.depth) += 1;
236
+ Ok(Self {
237
+ fiber,
238
+ state,
239
+ finished: false,
240
+ })
241
+ }
242
+
243
+ pub(super) fn state(&self) -> &Arc<RunState> {
244
+ &self.state
33
245
  }
34
246
 
35
247
  /// Raise what this run held.
36
248
  pub(super) fn finish(mut self) -> Result<(), MagnusError> {
37
249
  self.finished = true;
38
- match ESCAPE.with(|held| held.borrow_mut().take()) {
250
+ match take(&self.state) {
39
251
  Some(held) => Err(held.error),
40
252
  None => Ok(()),
41
253
  }
@@ -44,16 +256,98 @@ impl Run {
44
256
 
45
257
  impl Drop for Run {
46
258
  fn drop(&mut self) {
47
- RUNS.with(|runs| runs.set(runs.get() - 1));
48
259
  if !self.finished {
49
- ESCAPE.with(|held| held.borrow_mut().take());
260
+ take(&self.state);
261
+ }
262
+ let mut depth = lock(&self.state.depth);
263
+ *depth -= 1;
264
+ if *depth == 0 {
265
+ drop(depth);
266
+ remove(self.fiber);
50
267
  }
51
268
  }
52
269
  }
53
270
 
54
- /// Whether this thread is inside a run, which holds what reaches it.
271
+ /// Start an outermost run on the calling Fiber. Unless a Fiber scheduler takes
272
+ /// its waits, locks know it as a run another Fiber of the Thread has in
273
+ /// progress: no such run goes on while this Thread waits.
274
+ fn start(scheduler_waits: bool) -> Arc<RunState> {
275
+ // SAFETY: `rb_thread_current` reads the calling thread's own execution
276
+ // context, which a thread holding the GVL may.
277
+ let thread = unsafe { rb_sys::rb_thread_current() };
278
+ let task = (!scheduler_waits)
279
+ .then(|| run_by_thread(thread))
280
+ .flatten()
281
+ .map_or_else(Current::default, |running| {
282
+ Current::with_owner(&running.task)
283
+ });
284
+ Arc::new(RunState {
285
+ task,
286
+ held: Mutex::new(None),
287
+ pending: Arc::default(),
288
+ depth: Mutex::new(0),
289
+ lines: Mutex::new(Vec::new()),
290
+ pins: Mutex::new(vec![thread]),
291
+ thread,
292
+ })
293
+ }
294
+
295
+ /// A run another Fiber has in progress on `thread`.
296
+ fn run_by_thread(thread: rb_sys::VALUE) -> Option<Arc<RunState>> {
297
+ let on_thread: Vec<Arc<RunState>> = with_runs(|runs| {
298
+ runs.by_fiber
299
+ .values()
300
+ .filter(|state| state.thread == thread)
301
+ .cloned()
302
+ .collect()
303
+ });
304
+ on_thread.into_iter().find(|state| state.is_running())
305
+ }
306
+
307
+ /// Move the run `fiber` is in to the guest `line` leads to, as the collector
308
+ /// freed the Fiber while it was suspended in a callback: the run stays in
309
+ /// progress until that guest ends, and the Fiber's address is free for
310
+ /// another run.
311
+ pub(super) fn forget(fiber: FiberId, line: &Arc<Line>) {
312
+ with_runs(|runs| {
313
+ runs.by_fiber.remove(&fiber);
314
+ if !line.has_ended() {
315
+ runs.ending.push(line.clone());
316
+ }
317
+ });
318
+ }
319
+
320
+ /// A Fiber as a run knows it: the Fiber itself, which the run's `RunCaller`
321
+ /// keeps on the Fiber's own stack, so the collector, scanning that stack,
322
+ /// never moves it while the run lasts.
323
+ pub(crate) type FiberId = rb_sys::VALUE;
324
+
325
+ /// The calling Fiber, asked while holding the GVL.
326
+ pub(crate) fn fiber_id() -> FiberId {
327
+ // SAFETY: `rb_fiber_current` reads the calling thread's own execution
328
+ // context, which a thread holding the GVL may.
329
+ unsafe { rb_sys::rb_fiber_current() }
330
+ }
331
+
332
+ /// The run the calling Fiber is in, asked while holding the GVL.
333
+ pub(super) fn current_run() -> Option<Arc<RunState>> {
334
+ let fiber = fiber_id();
335
+ with_runs(|runs| runs.by_fiber.get(&fiber).cloned())
336
+ }
337
+
338
+ /// Whether the calling Fiber is inside a run, which holds what reaches it.
55
339
  pub(super) fn is_in_run() -> bool {
56
- RUNS.with(|runs| runs.get() > 0)
340
+ current_run().is_some()
341
+ }
342
+
343
+ fn take(state: &RunState) -> Option<Escape> {
344
+ let held = lock(&state.held).take();
345
+ state.pending.store(false, Ordering::SeqCst);
346
+ held
347
+ }
348
+
349
+ fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
350
+ mutex.lock().unwrap_or_else(PoisonError::into_inner)
57
351
  }
58
352
 
59
353
  /// The error and, when it carries one, its exception kept rooted while
@@ -63,6 +357,11 @@ struct Escape {
63
357
  _rooted: Option<BoxValue<Value>>,
64
358
  }
65
359
 
360
+ // SAFETY: an `Escape` is made, read, and dropped only on a thread holding the
361
+ // GVL, which is what its Ruby values need; the run's other threads see only the
362
+ // `pending` flag beside it.
363
+ unsafe impl Send for Escape {}
364
+
66
365
  /// Hold `error` unless it is a `StandardError`, which comes back for the
67
366
  /// callback to answer the guest with.
68
367
  pub(super) fn hold(ruby: &Ruby, error: MagnusError) -> Result<(), MagnusError> {
@@ -82,17 +381,24 @@ pub(super) fn hold_interrupts() {
82
381
  }
83
382
  }
84
383
 
85
- /// Keep `error` for the host; the first one kept wins.
384
+ /// Keep `error` for the host; the first one kept wins. Outside any run
385
+ /// nothing would raise it again, so it goes.
86
386
  pub(super) fn keep(error: MagnusError) {
87
- ESCAPE.with(|held| {
88
- held.borrow_mut().get_or_insert_with(|| Escape {
89
- _rooted: error.value().map(BoxValue::new),
90
- error,
91
- });
387
+ let Some(state) = current_run() else {
388
+ return;
389
+ };
390
+ lock(&state.held).get_or_insert_with(|| Escape {
391
+ _rooted: error.value().map(BoxValue::new),
392
+ error,
92
393
  });
394
+ state.pending.store(true, Ordering::SeqCst);
93
395
  }
94
396
 
95
- /// Whether this thread holds an error for the host.
397
+ /// Whether the run holds an error for the host, asked on the run's caller or
398
+ /// on its guest's thread.
96
399
  pub(super) fn pending() -> bool {
97
- ESCAPE.with(|held| held.borrow().is_some())
400
+ match handoff::pending_flag() {
401
+ Some(pending) => pending.load(Ordering::SeqCst),
402
+ None => current_run().is_some_and(|state| state.pending.load(Ordering::SeqCst)),
403
+ }
98
404
  }
@@ -79,29 +79,27 @@ impl Policy<MountRequest<'_>> for RubyPolicy {
79
79
  false
80
80
  })
81
81
  })
82
+ .unwrap_or(false)
82
83
  }
83
84
  }
84
85
 
85
86
  /// The Grants one invocation carries, from the Sandbox's Mounts as
86
87
  /// `[at, access, filesystem, block]` entries, beside the pins keeping
87
88
  /// each Mount's filesystem and block in place while the guest may reach
88
- /// them; the caller holds both until the invocation returns.
89
- pub(crate) fn to_grants(
90
- ruby: &Ruby,
91
- mounts: RArray,
92
- ) -> Result<(Vec<Grant>, Vec<PinnedValue>), MagnusError> {
89
+ /// them, kept for the run building them.
90
+ pub(crate) fn to_grants(mounts: RArray) -> Result<(Vec<Grant>, Vec<PinnedValue>), MagnusError> {
93
91
  let mut grants = Vec::with_capacity(mounts.len());
94
92
  let mut pins = Vec::with_capacity(mounts.len() * 2);
95
93
  for index in 0..mounts.len() as isize {
96
94
  let entry: RArray = mounts.entry(index)?;
97
95
  let filesystem: Value = entry.entry(2)?;
98
- pins.push(PinnedValue::new(ruby, filesystem));
96
+ pins.push(PinnedValue::new(filesystem));
99
97
  let mount = to_mount(entry.entry(0)?, entry.entry(1)?, filesystem)?;
100
98
  let block: Value = entry.entry(3)?;
101
99
  grants.push(Grant::Mount(if block.is_nil() {
102
100
  mount
103
101
  } else {
104
- pins.push(PinnedValue::new(ruby, block));
102
+ pins.push(PinnedValue::new(block));
105
103
  mount.with_policy(Arc::new(RubyPolicy {
106
104
  block: Opaque::from(block),
107
105
  }))
@@ -146,6 +146,8 @@ fn ask_or<T>(
146
146
  Ok(()) => Errno::Other(String::new()),
147
147
  })
148
148
  })
149
+ // Nothing of the run's caller is left to ask.
150
+ .unwrap_or_else(|| Err(Errno::Other(String::new())))
149
151
  }
150
152
 
151
153
  /// Ask `object` a change, answering nothing more than whether it was made.
@@ -246,7 +248,7 @@ impl RubyFilesystem {
246
248
  let path = path_of(dentry);
247
249
  let file = ask(self.object, "open", Errno::Unsupported, |ruby, fs| {
248
250
  let file: Value = fs.funcall("open", (path, to_flags(ruby, how, create)?))?;
249
- Ok(RubyFile::pin(ruby, file))
251
+ Ok(RubyFile::pin(file))
250
252
  })?;
251
253
  match dentry.inode().map(|inode| inode.identity()) {
252
254
  None => {
@@ -285,6 +287,7 @@ impl RubyFilesystem {
285
287
  names.iter().try_for_each(|name| verify_dirent_name(name))?;
286
288
  let mut entries = Vec::with_capacity(names.len());
287
289
  for name in names {
290
+ kobako_runtime::sched::stop_if_fatal()?;
288
291
  match self.stat(join(&at, &name)) {
289
292
  Ok(stat) => entries
290
293
  .push(DirEntry::new(name, stat.file_type).with_identity(stat.dev, stat.ino)),
@@ -486,6 +489,10 @@ impl FileOperations for RubyDir {
486
489
  generic_read_dir()
487
490
  }
488
491
 
492
+ fn has_iterate_shared(&self) -> bool {
493
+ true
494
+ }
495
+
489
496
  /// What a listing began with stays on the open directory until it ends, so
490
497
  /// a caller reading in small steps asks the object once, as FUSE's readdir
491
498
  /// cache spares asking the server each time.
@@ -562,9 +569,9 @@ impl DentryOperations for RubyFilesystem {
562
569
  }
563
570
 
564
571
  impl RubyFile {
565
- fn pin(ruby: &Ruby, file: Value) -> Self {
572
+ fn pin(file: Value) -> Self {
566
573
  Self {
567
- file: Arc::new(PinnedValue::new(ruby, file)),
574
+ file: Arc::new(PinnedValue::new(file)),
568
575
  closed: false,
569
576
  }
570
577
  }
@@ -10,12 +10,13 @@
10
10
  mod grants;
11
11
  mod ruby;
12
12
 
13
+ use std::io;
13
14
  use std::sync::Arc;
14
15
 
15
16
  use magnus::value::{Opaque, ReprValue};
16
17
  use magnus::{
17
18
  function, gc, prelude::*, scan_args::get_kwargs, scan_args::scan_args, DataTypeFunctions,
18
- Error as MagnusError, RArray, RHash, RModule, RString, Ruby, Symbol, TypedData, Value,
19
+ Error as MagnusError, RArray, RClass, RHash, RModule, RString, Ruby, Symbol, TypedData, Value,
19
20
  };
20
21
 
21
22
  use ruby::RubyFilesystem;
@@ -70,7 +71,7 @@ pub(super) fn register(ruby: &Ruby, kobako: RModule) -> Result<(), MagnusError>
70
71
  Ok(())
71
72
  }
72
73
 
73
- /// `Tmpfs.new(files = {}, size: 64 MiB, nr_inodes:)`: each
74
+ /// `Tmpfs.new(files = {}, size: 4 MiB, nr_inodes:)`: each
74
75
  /// `path => contents` pair becomes a file, its directories created along
75
76
  /// the way. Ruby hands a bare `"path" => contents` over as keywords, so
76
77
  /// every String keyword is a file too. Without `nr_inodes:` the entries
@@ -123,6 +124,39 @@ fn to_instance_error(error: Errno) -> MagnusError {
123
124
  )
124
125
  }
125
126
 
127
+ /// Whether the host refused `err` for want of descriptors, its process's or
128
+ /// its machine's, by the numbers Ruby's `Errno` classes hold for this host.
129
+ fn out_of_descriptors(ruby: &Ruby, err: &io::Error) -> bool {
130
+ let number = |name: &str| -> Option<i32> {
131
+ let errno: RModule = ruby.class_object().const_get("Errno").ok()?;
132
+ let class: RClass = errno.const_get(name).ok()?;
133
+ class.const_get("Errno").ok()
134
+ };
135
+ err.raw_os_error().is_some_and(|code| {
136
+ ["EMFILE", "ENFILE"]
137
+ .iter()
138
+ .any(|name| number(name) == Some(code))
139
+ })
140
+ }
141
+
142
+ /// Why `Bind.new` could not open `path`: the host's own `Errno` when it was out
143
+ /// of descriptors, which is no fault of the argument, and an `ArgumentError`
144
+ /// naming the path otherwise.
145
+ fn refusal(ruby: &Ruby, path: &str, err: &io::Error) -> MagnusError {
146
+ if let Some(code) = err.raw_os_error().filter(|_| out_of_descriptors(ruby, err)) {
147
+ if let Ok(raised) = ruby
148
+ .exception_system_call_error()
149
+ .new_instance((path.to_string(), code))
150
+ {
151
+ return MagnusError::from(raised);
152
+ }
153
+ }
154
+ MagnusError::new(
155
+ ruby.exception_arg_error(),
156
+ format!("cannot open host directory {path}: {err}"),
157
+ )
158
+ }
159
+
126
160
  /// A `size:` or `nr_inodes:` count, or `nil` for none.
127
161
  fn to_count(count: Value) -> Result<Option<usize>, MagnusError> {
128
162
  Option::<usize>::try_convert(count)
@@ -135,12 +169,17 @@ fn bind_new(args: &[Value]) -> Result<BindFs, MagnusError> {
135
169
  let (path,) = args.required;
136
170
  let kwargs = get_kwargs::<_, (), (Option<bool>,), ()>(args.keywords, &[], &["exclusive"])?;
137
171
  let (exclusive,) = kwargs.optional;
138
- let directory = Bind::new(&path).map_err(|err| {
139
- MagnusError::new(
140
- ruby.exception_arg_error(),
141
- format!("cannot open host directory {path}: {err}"),
142
- )
143
- })?;
172
+ // A host out of descriptors may be holding ones the Host App let go
173
+ // without closing, so they are collected once and the open tried again,
174
+ // as `rb_gc_for_fd` has `Dir.new` do.
175
+ let directory = match Bind::new(&path) {
176
+ Err(err) if out_of_descriptors(&ruby, &err) => {
177
+ ruby.gc_start();
178
+ Bind::new(&path)
179
+ }
180
+ opened => opened,
181
+ }
182
+ .map_err(|err| refusal(&ruby, &path, &err))?;
144
183
  Filesystem::new(directory.with_exclusive(exclusive.unwrap_or(false)))
145
184
  .map(BindFs)
146
185
  .map_err(to_instance_error)
@@ -0,0 +1,72 @@
1
+ //! A fork through Ruby, checked before it happens, as `pthread_atfork`'s
2
+ //! prepare handler runs in the forking thread. A forked child inherits the
3
+ //! memory but only the forking thread, so a fork raises while any run is in
4
+ //! progress, whose locks the child would inherit held, and on macOS once the
5
+ //! system verified a certificate, after which a child touching its
6
+ //! certificate services crashes.
7
+
8
+ use std::sync::atomic::{AtomicBool, Ordering};
9
+
10
+ use kobako_runtime::filesystem::Bind;
11
+ use magnus::{function, prelude::*, Error as MagnusError, RModule, Ruby, Value};
12
+
13
+ use super::escape;
14
+
15
+ pub(crate) fn register(kobako: RModule) -> Result<(), MagnusError> {
16
+ let fork = kobako.define_module("Fork")?;
17
+ fork.define_singleton_method("prepare", function!(prepare, 0))?;
18
+ fork.define_singleton_method("release", function!(escape::let_runs_in, 0))?;
19
+ Ok(())
20
+ }
21
+
22
+ /// Hold new runs back until `release`, raising `RuntimeError` for a fork that
23
+ /// cannot go on: the permanent refusal first, so no one retries it. Once held
24
+ /// back, nothing walks a Bind, so the directories Binds keep are let go and
25
+ /// the child inherits none of them.
26
+ fn prepare() -> Result<(), MagnusError> {
27
+ let ruby = Ruby::get().expect("a fork's prepare runs on a Ruby thread");
28
+ refuse_past_trust(&ruby)?;
29
+ if !escape::hold_runs_back() {
30
+ return Err(MagnusError::new(
31
+ ruby.exception_runtime_error(),
32
+ "cannot fork while a Sandbox run is in progress, as the child would inherit \
33
+ the locks it holds; fork again once no run is in progress",
34
+ ));
35
+ }
36
+ Bind::drop_kept_directories();
37
+ Ok(())
38
+ }
39
+
40
+ /// Tell Pitchfork, once, that this process forks no more once the system
41
+ /// verified a certificate, so it forks from another worker rather than meet
42
+ /// the refusal. The guest's thread that verified holds no
43
+ /// GVL, so the run tells it as it ends.
44
+ pub(crate) fn tell_pitchfork_past_trust(ruby: &Ruby) {
45
+ static TOLD: AtomicBool = AtomicBool::new(false);
46
+ if kobako_runtime::net::first_trusted_host().is_none() || TOLD.load(Ordering::Relaxed) {
47
+ return;
48
+ }
49
+ let info = ruby
50
+ .class_object()
51
+ .const_get::<_, RModule>("Pitchfork")
52
+ .and_then(|pitchfork| pitchfork.const_get::<_, Value>("Info"));
53
+ if let Ok(info) = info {
54
+ TOLD.store(true, Ordering::Relaxed);
55
+ let _: Result<Value, _> = info.funcall("no_longer_fork_safe!", ());
56
+ }
57
+ }
58
+
59
+ /// Raise for a fork on macOS once the system verified a certificate.
60
+ fn refuse_past_trust(ruby: &Ruby) -> Result<(), MagnusError> {
61
+ match kobako_runtime::net::first_trusted_host() {
62
+ Some(host) => Err(MagnusError::new(
63
+ ruby.exception_runtime_error(),
64
+ format!(
65
+ "cannot fork after a guest's HTTPS to {host} had macOS verify a certificate: \
66
+ a child touching the system's certificate services crashes; fork before any \
67
+ guest makes an HTTPS request"
68
+ ),
69
+ )),
70
+ None => Ok(()),
71
+ }
72
+ }