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
@@ -1,38 +1,45 @@
1
- //! Releasing Ruby's GVL for an invocation's guest span so distinct Sandboxes on
2
- //! distinct Threads run their guest code in parallel.
1
+ //! A run of a Sandbox, its guest on a thread of its own while the calling Fiber
2
+ //! serves it, giving up the GVL while the guest runs when the Sandbox asks, and
3
+ //! otherwise each quantum as CRuby's Threads do.
3
4
  //!
4
- //! `region` brackets one invocation's guest span, releasing the GVL when the
5
- //! Sandbox asks for it; `reenter` re-acquires the GVL for a guest→host dispatch
6
- //! callback, which is ordinary Ruby and must hold the lock. A thread-local flag
7
- //! stops a nested dispatch from re-acquiring a second time, and both directions
8
- //! run their closure through a `catch_unwind` trampoline because a panic must
9
- //! never cross the C frame of `rb_thread_call_without_gvl2` /
10
- //! `rb_thread_call_with_gvl` (undefined behaviour). The flag is per-thread,
11
- //! matching the one-thread-one-Sandbox contract, and is restored through a drop
12
- //! guard so an unwinding panic cannot leave it corrupt for the next invocation.
5
+ //! `run` hands the guest to its thread and serves what it asks of Ruby in this
6
+ //! frame, holding the GVL; `reenter` is how the guest's thread asks, and runs
7
+ //! inline where the GVL is already held. Ruby runs only where no guest frame
8
+ //! stands, so a raise, a trap handler, or a Fiber switch in a callback crosses
9
+ //! none, and a callback takes interrupts as the Host App's own mask allows.
10
+ //! What Ruby delivers while the guest runs is held by the run before the next
11
+ //! callback starts, or as its caller gives up its quantum; what raises stops
12
+ //! the guest, and the run raises it once it ends.
13
13
  //!
14
- //! A raise where either direction returns jumps over every Rust frame of the
15
- //! run and what they hold: a lock's guard, this flag. A release uses
16
- //! `rb_thread_call_without_gvl2`, which declines rather than raises, and a run
17
- //! releasing the GVL defers Ruby's interrupts (`defer_interrupts`) outside its
18
- //! callbacks, as `rb_thread_call_with_gvl` checks for one as it gives the GVL
19
- //! back. An interrupt waits for the run to end instead. Two kinds of work on the
20
- //! main thread run whatever the mask says, so one that raises there still
21
- //! jumps: a trap handler, and on Ruby 3.4+ the Thread another Ractor's
22
- //! `require` starts there, which raises when it cannot start. No public Ruby
23
- //! API defers either.
14
+ //! A wait without the GVL uses `rb_thread_call_without_gvl2`, which declines
15
+ //! rather than raises. A thread-local flag says a thread is inside such a wait,
16
+ //! so a signal handled there takes the GVL back once; a Ruby thread may go on
17
+ //! on another native thread once it takes the GVL back, so the flag is set only
18
+ //! inside the wait. Each direction runs its closure through a `catch_unwind`
19
+ //! trampoline, as a panic must never cross a C frame.
24
20
 
25
21
  use std::cell::Cell;
26
- use std::os::raw::c_void;
22
+ use std::ffi::CString;
23
+ use std::os::raw::{c_char, c_int, c_long, c_void};
27
24
  use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
28
25
  use std::ptr;
26
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
27
+ use std::sync::{Arc, Mutex, OnceLock, PoisonError};
28
+ use std::time::Duration;
29
29
 
30
- use kobako_runtime::sched::{run_interruptible, Blocking, Task};
30
+ use kobako_runtime::sched::{run_interruptible, Blocking, Current, Task};
31
31
 
32
32
  use magnus::block::Proc;
33
- use magnus::{prelude::*, Error as MagnusError, Ruby, Value};
33
+ use magnus::gc::Marker;
34
+ use magnus::rb_sys::FromRawValue;
35
+ use magnus::typed_data::DataTypeFunctions;
36
+ use magnus::TypedData;
37
+ use magnus::{prelude::*, Error as MagnusError, RClass, RModule, Ruby, Value};
34
38
 
39
+ use super::errors;
35
40
  use super::escape;
41
+ use super::fork;
42
+ use super::handoff::{self, Message};
36
43
 
37
44
  thread_local! {
38
45
  // True while this thread sits inside a region whose GVL we released and
@@ -47,50 +54,62 @@ where
47
54
  if !release {
48
55
  return f();
49
56
  }
50
- // An interrupt the thread receives meanwhile stops each wait the run meets,
51
- // for a lock or a host-side event; the interrupt itself still waits for the
52
- // run to end. One landing before or after the run itself, while the guest
53
- // is set up or torn down, still belongs to this region and goes with it.
57
+ // What Ruby wakes the thread for meanwhile signals each wait the run meets,
58
+ // for a lock or a host-side event, which hands it to `GvlFreeWait`; what it
59
+ // raises waits for the run to end. One landing before or after the run
60
+ // itself, while the guest is set up or torn down, still belongs to this
61
+ // region and goes with it.
54
62
  let task = Task::current();
55
63
  let task_ptr = ptr::addr_of!(task).cast_mut().cast::<c_void>();
64
+ // A Ruby thread may go on on another native thread once it takes the GVL
65
+ // back, so what this thread-local state says holds only while `f` runs,
66
+ // on the thread running it.
67
+ let current = Current::get();
68
+ let f = Cell::new(Some(f));
69
+ let take = || f.take().expect("a region runs its closure once");
70
+ let mut released = || {
71
+ let _released = ReleasedGuard::set(true);
72
+ current.carry(take())
73
+ };
56
74
  run_interruptible(|| {
57
- let mut f = f;
58
75
  loop {
59
- let released = ReleasedGuard::set(true);
60
- let ran = call_via(f, |func, data| {
61
- // An interrupt that came before the region, which Ruby declines
62
- // to start under or the run's mask defers, stops the waits as one
76
+ let ran = call_via(&mut released, |func, data| {
77
+ // What came before the region, which Ruby declines to start
78
+ // under or the run's mask defers, reaches the waits as one
63
79
  // inside it does, as a signal pending when a Linux task sleeps
64
- // ends the sleep.
65
- if escape::pending() || interrupt_pending() {
80
+ // wakes the sleep.
81
+ if escape::pending() {
66
82
  task.interrupt();
83
+ } else if interrupt_pending() {
84
+ task.signal();
67
85
  }
68
86
  // SAFETY: `func` and `data` come from `call_via`, which keeps the
69
87
  // closure alive across the call; `task` outlives it on this frame,
70
- // and Ruby calls `interrupt_task` with it only while the region runs.
88
+ // and Ruby calls `signal_task` with it only while the region runs.
71
89
  unsafe {
72
90
  rb_sys::rb_thread_call_without_gvl2(
73
91
  Some(func),
74
92
  data,
75
- Some(interrupt_task),
93
+ Some(signal_task),
76
94
  task_ptr,
77
95
  )
78
96
  }
79
97
  });
80
- drop(released);
81
98
  match ran {
82
99
  Ok(value) => return value,
83
100
  // A run holds the interrupt and raises it once back in Ruby.
84
- Err(declined) if escape::is_in_run() => {
85
- escape::hold_interrupts();
86
- f = declined;
101
+ // One its mask defers stays queued, so the waits are signalled
102
+ // to take it as a callback would.
103
+ Err(_) if escape::is_in_run() => {
104
+ keeping_held_jump(escape::hold_interrupts);
105
+ task.signal();
87
106
  }
88
107
  // Outside a run nothing would raise a held interrupt, so it
89
108
  // stays with Ruby, which raises it as this call returns; the
90
109
  // wait runs with the GVL kept and ends at once, interrupted.
91
- Err(declined) => {
110
+ Err(_) => {
92
111
  task.interrupt();
93
- return declined();
112
+ return current.carry(take());
94
113
  }
95
114
  }
96
115
  }
@@ -105,13 +124,14 @@ fn interrupt_pending() -> bool {
105
124
  unsafe { rb_sys::rb_thread_interrupted(rb_sys::rb_thread_current()) != 0 }
106
125
  }
107
126
 
108
- /// Have the thread's run stop waiting for locks, called by Ruby without the GVL
109
- /// as the region's unblocking function.
110
- unsafe extern "C" fn interrupt_task(task: *mut c_void) {
127
+ /// Signal the thread's run, called by Ruby without the GVL as the region's
128
+ /// unblocking function, whenever it wakes the thread: for an exception, a
129
+ /// trap, or `Thread#wakeup`, which only the GVL tells apart.
130
+ unsafe extern "C" fn signal_task(task: *mut c_void) {
111
131
  // SAFETY: `region` passes its own `Task`, alive for the whole region
112
132
  // Ruby calls this from.
113
133
  let task = unsafe { &*task.cast::<Task>() };
114
- task.interrupt();
134
+ task.signal();
115
135
  }
116
136
 
117
137
  /// Whether this thread holds the GVL: outside any released region, or
@@ -120,33 +140,86 @@ fn holds() -> bool {
120
140
  !GVL_RELEASED.with(|g| g.get())
121
141
  }
122
142
 
123
- /// A thread waits for a lock or a host-side event without the GVL, so a
124
- /// holder asking a Filesystem written in Ruby, or a mount's block, can take
143
+ /// A thread waits for a lock or a host-side event without the GVL, so an
144
+ /// owner asking a Filesystem written in Ruby, or a mount's block, can take
125
145
  /// the GVL and finish, and other Threads run while the guest sleeps.
126
146
  pub(crate) struct GvlFreeWait;
127
147
 
128
148
  impl Blocking for GvlFreeWait {
129
149
  fn wait(&self, wait: &mut dyn FnMut()) {
130
- region(holds(), wait);
150
+ if handoff::on_guest() {
151
+ return handoff::wait_releasing(wait);
152
+ }
153
+ if !(holds() && escape::is_in_run()) {
154
+ return region(holds(), wait);
155
+ }
156
+ // A run keeping the GVL defers interrupts across its wait, so taking
157
+ // the GVL back to handle a signal never raises where it gives the GVL
158
+ // up again.
159
+ let ruby = Ruby::get().expect("a Thread keeping the GVL holds it");
160
+ let (_, raised) = handle_interrupt(&ruby, "never", || region(true, wait));
161
+ if let Err(error) = raised {
162
+ escape::keep(error);
163
+ }
164
+ }
165
+
166
+ /// Take what Ruby woke the thread for, as a callback takes it; one that
167
+ /// raises ends the run's waits, and the run raises it once it ends.
168
+ /// Outside a run nothing would raise it, so it stays with Ruby and ends the
169
+ /// wait at once.
170
+ fn handle_signal(&self) {
171
+ if handoff::on_guest() {
172
+ handoff::on_caller(|| self.handle_signal());
173
+ return;
174
+ }
175
+ if escape::is_in_run() {
176
+ reenter(escape::hold_interrupts);
177
+ }
178
+ if !escape::is_in_run() || escape::pending() {
179
+ Task::current().interrupt();
180
+ }
181
+ }
182
+
183
+ /// The run of the calling Fiber, asked only while the GVL is held, as a
184
+ /// Fiber may resume on another native thread once it gave the GVL up.
185
+ fn current(&self) -> Option<Current> {
186
+ if !holds_gvl() {
187
+ return None;
188
+ }
189
+ escape::current_run().map(|run| run.task().clone())
131
190
  }
132
191
  }
133
192
 
134
- /// Runs inline when the GVL is already held — hold mode, or a nested
135
- /// dispatch whose outer frame re-acquired it.
136
- pub(crate) fn reenter<F, R>(f: F) -> R
193
+ /// Whether the calling thread holds the GVL: a Ruby thread outside any region
194
+ /// of this module, where alone a Ruby thread gives it up.
195
+ pub(crate) fn holds_gvl() -> bool {
196
+ // SAFETY: `ruby_native_thread_p` only asks whether the calling thread is
197
+ // Ruby's, on any thread.
198
+ !handoff::on_guest() && unsafe { rb_sys::ruby_native_thread_p() } != 0 && holds()
199
+ }
200
+
201
+ /// Run `f`, which calls Ruby, holding the GVL: on the run's caller when a
202
+ /// guest's thread asks, inline when the GVL is already held. `None` when the
203
+ /// run's caller is gone, as a Fiber left suspended in a callback and collected
204
+ /// is, so nothing of Ruby is reached.
205
+ pub(crate) fn reenter<F, R>(f: F) -> Option<R>
137
206
  where
138
207
  F: FnOnce() -> R,
139
208
  {
209
+ if handoff::on_guest() {
210
+ return handoff::on_caller(|| reenter(f)).flatten();
211
+ }
140
212
  if holds() {
141
- return f();
213
+ return Some(keeping_held_jump(f));
142
214
  }
143
215
  let _guard = ReleasedGuard::set(false);
144
216
  // Ruby checks for interrupts as it gives the GVL back on the way out, and
145
- // raising there would jump over every Rust frame of the run. The run masks
146
- // them (`defer_interrupts`), so the callback alone takes them as they come.
217
+ // raising there would jump over every Rust frame of the run. A wait inside
218
+ // a run masks them (`GvlFreeWait`), so the callback alone takes them as
219
+ // they come.
147
220
  let run_callback = |f: F| {
148
221
  let ruby = Ruby::get().expect("a thread back in Ruby holds the GVL");
149
- let (value, raised) = handle_interrupt(&ruby, "immediate", f);
222
+ let (value, raised) = keeping_held_jump(|| handle_interrupt(&ruby, "immediate", f));
150
223
  if let Err(error) = raised {
151
224
  escape::keep(error);
152
225
  }
@@ -155,38 +228,388 @@ where
155
228
  // SAFETY: `func` and `data` come from `call_via`, which keeps the
156
229
  // closure alive across the call, and this thread is a Ruby thread
157
230
  // inside a region that released the GVL, as the call requires.
158
- call_via(
231
+ let ran = call_via(
159
232
  || run_callback(f),
160
233
  |func, data| unsafe { rb_sys::rb_thread_call_with_gvl(Some(func), data) },
234
+ );
235
+ Some(
236
+ ran.ok()
237
+ .expect("rb_thread_call_with_gvl always runs its function"),
161
238
  )
239
+ }
240
+
241
+ /// Run `f`, which calls Ruby, so a `throw` the run holds keeps its target.
242
+ /// CRuby keeps where a `throw` goes on the Fiber rather than in anything
243
+ /// `escape` can hold, and a `catch` completing inside `f` clears it;
244
+ /// `rb_ensure` puts it back after running its ensure function, which is `f`.
245
+ fn keeping_held_jump<F, R>(f: F) -> R
246
+ where
247
+ F: FnOnce() -> R,
248
+ {
249
+ /// The body `rb_ensure` runs before `f`, which does nothing.
250
+ unsafe extern "C" fn nothing(_: rb_sys::VALUE) -> rb_sys::VALUE {
251
+ rb_sys::Qnil as rb_sys::VALUE
252
+ }
253
+
254
+ /// `trampoline`, taking its `GvlCtx` as the `VALUE` `rb_ensure` passes.
255
+ unsafe extern "C" fn ensure<F, R>(data: rb_sys::VALUE) -> rb_sys::VALUE
256
+ where
257
+ F: FnOnce() -> R,
258
+ {
259
+ // SAFETY: `data` is the `GvlCtx<F, R>` `call_via` handed over.
260
+ unsafe { trampoline::<F, R>(data as *mut c_void) as rb_sys::VALUE }
261
+ }
262
+
263
+ if !escape::pending() {
264
+ return f();
265
+ }
266
+ // SAFETY: `data` comes from `call_via`, which keeps the closure alive
267
+ // across the call; `ensure` runs it once, under `catch_unwind`.
268
+ call_via(f, |_, data| unsafe {
269
+ rb_sys::rb_ensure(
270
+ Some(nothing),
271
+ rb_sys::Qnil as rb_sys::VALUE,
272
+ Some(ensure::<F, R>),
273
+ data as rb_sys::VALUE,
274
+ );
275
+ ptr::null_mut()
276
+ })
162
277
  .ok()
163
- .expect("rb_thread_call_with_gvl always runs its function")
278
+ .expect("rb_ensure always runs its ensure function")
164
279
  }
165
280
 
166
- /// Run `f` as one run of a Sandbox: giving up the GVL when `release` says so,
167
- /// with Ruby's interrupts deferred until it is back in Ruby, and one the run
168
- /// kept raised once it ends.
169
- pub(crate) fn run<R>(ruby: &Ruby, release: bool, f: impl FnOnce() -> R) -> Result<R, MagnusError> {
170
- let run = escape::Run::enter();
171
- let ran = defer_interrupts(ruby, release, || region(release, f));
281
+ /// Run `f` as one run of a Sandbox on a guest's thread, serving what it asks of
282
+ /// Ruby here, giving up the GVL while it runs when `release` says so, and
283
+ /// raising what the run kept once it ends. Each wait the run makes is counted
284
+ /// on `waiting` while it waits.
285
+ ///
286
+ /// `setup` builds what the guest runs inside the run, so each Ruby object it
287
+ /// pins is kept for the run.
288
+ pub(crate) fn run<R, F>(
289
+ ruby: &Ruby,
290
+ release: bool,
291
+ waiting: &Arc<AtomicUsize>,
292
+ setup: impl FnOnce() -> Result<F, MagnusError>,
293
+ ) -> Result<R, MagnusError>
294
+ where
295
+ R: Send + 'static,
296
+ F: FnOnce() -> R + Send + 'static,
297
+ {
298
+ let run = escape::Run::enter(ruby, waiting, release && scheduler_takes_waits(ruby))?;
299
+ let f = setup()?;
300
+ let ran = serve(ruby, release, waiting, run.state(), f)?;
301
+ fork::tell_pitchfork_past_trust(ruby);
172
302
  run.finish()?;
173
- ran
303
+ Ok(ran)
174
304
  }
175
305
 
176
- /// Run `f` with Ruby's interrupts deferred, when `release` says the run gives
177
- /// up the GVL, until it is back in Ruby, where one comes as the error. A run
178
- /// keeping the GVL meets no interrupt check outside its callbacks.
179
- fn defer_interrupts<R>(
306
+ /// Run `f` on a guest's thread carrying the run's task and serve it until it
307
+ /// ends. Each job it hands over runs here holding the GVL, in this frame, so
308
+ /// what a callback raises or switches to never crosses the guest's frames. A
309
+ /// host with no thread for the guest raises `TrapError`, the guest not
310
+ /// started.
311
+ fn serve<R: Send + 'static>(
180
312
  ruby: &Ruby,
181
313
  release: bool,
182
- f: impl FnOnce() -> R,
314
+ waiting: &Arc<AtomicUsize>,
315
+ state: &Arc<escape::RunState>,
316
+ f: impl FnOnce() -> R + Send + 'static,
183
317
  ) -> Result<R, MagnusError> {
184
- if !release {
185
- return Ok(f());
318
+ let ran = Arc::new(Mutex::new(None));
319
+ let answered = ran.clone();
320
+ let line = handoff::start(
321
+ state.task().clone(),
322
+ !release,
323
+ state.pending_flag(),
324
+ waiting.clone(),
325
+ move || {
326
+ let value = f();
327
+ *answered.lock().unwrap_or_else(PoisonError::into_inner) = Some(value);
328
+ },
329
+ )
330
+ .map_err(|err| errors::trap_err(ruby, format!("can't create Thread: {err}")))?;
331
+ let caller = ruby.obj_wrap(RunCaller {
332
+ line: line.clone(),
333
+ fiber: escape::fiber_id(),
334
+ run: state.clone(),
335
+ served: AtomicBool::new(false),
336
+ });
337
+ let ended = state.lending(&line, || run_interruptible(|| serve_line(&line)));
338
+ caller.served.store(true, Ordering::SeqCst);
339
+ std::hint::black_box(caller);
340
+ if let Some(panic) = ended {
341
+ resume_unwind(panic);
342
+ }
343
+ let value = ran.lock().unwrap_or_else(PoisonError::into_inner).take();
344
+ Ok(value.expect("a run that ended without a panic answered"))
345
+ }
346
+
347
+ /// A run's caller as Ruby's collector sees it. It stands on the caller's stack
348
+ /// while the caller serves the run, so the collector frees it with a Fiber left
349
+ /// suspended in a callback and never resumed, and the guest then goes on
350
+ /// without its caller, every wait of it interrupted. It marks the Ruby objects
351
+ /// the run pinned, so they go with it.
352
+ #[derive(TypedData)]
353
+ #[magnus(class = "Kobako::RunCaller", free_immediately, mark, size)]
354
+ struct RunCaller {
355
+ line: Arc<handoff::Line>,
356
+ fiber: escape::FiberId,
357
+ run: Arc<escape::RunState>,
358
+ served: AtomicBool,
359
+ }
360
+
361
+ impl DataTypeFunctions for RunCaller {
362
+ fn mark(&self, marker: &Marker) {
363
+ for pinned in self.run.pinned() {
364
+ // SAFETY: each is a live object the run pinned, unpinned only once
365
+ // its holder lets it go.
366
+ marker.mark(unsafe { Value::from_raw(pinned) });
367
+ }
368
+ }
369
+ }
370
+
371
+ impl Drop for RunCaller {
372
+ fn drop(&mut self) {
373
+ if !self.served.load(Ordering::SeqCst) {
374
+ self.line.abandon();
375
+ escape::forget(self.fiber, &self.line);
376
+ }
377
+ }
378
+ }
379
+
380
+ /// Defines the class the `#[magnus::wrap]` name resolves to, and looks it up
381
+ /// once, before any object is wrapped. The quantum is read here, as close to
382
+ /// where CRuby reads its own as an extension stands.
383
+ pub(crate) fn register(kobako: RModule) -> Result<(), MagnusError> {
384
+ let ruby = Ruby::get().expect("Ruby thread");
385
+ kobako.define_class("RunCaller", ruby.class_object())?;
386
+ RunCaller::class(&ruby);
387
+ quantum();
388
+ Ok(())
389
+ }
390
+
391
+ /// Run `f` on the guest's own stack, as a guest block a callback calls
392
+ /// re-enters the guest where its frames stand, serving the run meanwhile.
393
+ pub(crate) fn on_guest_stack<R>(line: &handoff::Line, f: impl FnOnce() -> R) -> R {
394
+ line.hand_guest(f, || serve_line(line))
395
+ }
396
+
397
+ /// Serve what the guest hands over until the run ends or what was handed to it
398
+ /// is answered, with the panic it ended by.
399
+ fn serve_line(line: &handoff::Line) -> Option<handoff::Panic> {
400
+ let task = Task::current();
401
+ let release = !line.keeps_gvl();
402
+ let mut gives_up = release;
403
+ loop {
404
+ let message = if gives_up {
405
+ take_released(line, &task)
406
+ } else {
407
+ take_in_turn(line, &task)
408
+ };
409
+ match message {
410
+ Message::Job(job) => {
411
+ // What Ruby delivered while the guest ran is the run's, held
412
+ // before the callback starts, so it never lands in the
413
+ // callback as if the callback raised it.
414
+ keeping_held_jump(escape::hold_interrupts);
415
+ line.answer(job);
416
+ }
417
+ Message::Wait(true) => gives_up = true,
418
+ Message::Wait(false) => {
419
+ gives_up = release;
420
+ line.begin_turn();
421
+ line.resume();
422
+ }
423
+ Message::Answer(panic) | Message::Done(panic) => return panic,
424
+ }
425
+ }
426
+ }
427
+
428
+ /// What the guest hands over next, waited for keeping the GVL for what is left
429
+ /// of the caller's quantum, then giving it up to whichever Thread waits, as
430
+ /// CRuby's timer has a running Thread do. The mailbox is looked at once
431
+ /// before the time is judged, and nothing handed over starts the quantum
432
+ /// again, so a guest that never comes back, or one that never stops asking,
433
+ /// still lets the other Threads run.
434
+ fn take_in_turn(line: &handoff::Line, task: &Task) -> Message {
435
+ loop {
436
+ if let Some(message) = line.take_within(line.turn_left(quantum())) {
437
+ return message;
438
+ }
439
+ yield_turn(task);
440
+ line.begin_turn();
441
+ }
442
+ }
443
+
444
+ /// Hand the GVL to a Thread waiting for it, then take what Ruby delivered, as
445
+ /// `rb_thread_schedule` does, which gives nothing up when no Thread waits. What
446
+ /// that raises is the run's, held, and ends the guest as an interrupt does.
447
+ fn yield_turn(task: &Task) {
448
+ let scheduled = keeping_held_jump(|| {
449
+ magnus::rb_sys::protect(|| {
450
+ // SAFETY: the caller holds the GVL, which `rb_thread_schedule`
451
+ // gives up and takes back; it raises only into this `protect`.
452
+ unsafe { rb_sys::rb_thread_schedule() };
453
+ rb_sys::Qnil as rb_sys::VALUE
454
+ })
455
+ });
456
+ if let Err(raised) = scheduled {
457
+ escape::keep(raised);
458
+ }
459
+ if escape::pending() {
460
+ task.interrupt();
461
+ }
462
+ }
463
+
464
+ /// How long a run's caller keeps the GVL while it waits for its guest: the
465
+ /// quantum CRuby gives each Thread, which Ruby 3.4 and later read from
466
+ /// `RUBY_THREAD_TIMESLICE` as the process starts.
467
+ fn quantum() -> Duration {
468
+ static QUANTUM: OnceLock<Duration> = OnceLock::new();
469
+ *QUANTUM.get_or_init(|| {
470
+ let reads_timeslice = (
471
+ rb_sys::RUBY_API_VERSION_MAJOR,
472
+ rb_sys::RUBY_API_VERSION_MINOR,
473
+ ) >= (3, 4);
474
+ let set = reads_timeslice
475
+ .then(|| std::env::var("RUBY_THREAD_TIMESLICE").ok())
476
+ .flatten()
477
+ .and_then(|value| timeslice_ms(&value));
478
+ Duration::from_millis(set.unwrap_or(DEFAULT_QUANTUM_MS).into())
479
+ })
480
+ }
481
+
482
+ /// CRuby's `thread_default_quantum_ms`.
483
+ const DEFAULT_QUANTUM_MS: u32 = 100;
484
+
485
+ /// The milliseconds `value` names as CRuby reads `RUBY_THREAD_TIMESLICE`:
486
+ /// `strtol` in any base, taken only above zero and within 32 bits.
487
+ fn timeslice_ms(value: &str) -> Option<u32> {
488
+ extern "C" {
489
+ fn strtol(text: *const c_char, end: *mut *mut c_char, base: c_int) -> c_long;
490
+ }
491
+ let text = CString::new(value).ok()?;
492
+ // SAFETY: `text` is a NUL-terminated string alive across the call, and a
493
+ // null `end` asks `strtol` not to say where it stopped.
494
+ let quantum = unsafe { strtol(text.as_ptr(), ptr::null_mut(), 0) };
495
+ u32::try_from(quantum).ok().filter(|&ms| ms > 0)
496
+ }
497
+
498
+ /// `rb_nogvl` declines to run its function while an interrupt is pending,
499
+ /// rather than raising.
500
+ const RB_NOGVL_INTR_FAIL: c_int = 0x1;
501
+
502
+ /// `rb_nogvl` may hand its function to the Fiber scheduler's
503
+ /// `blocking_operation_wait`, which runs it on another thread while the Fiber
504
+ /// waits; a Ruby without the hook ignores it.
505
+ const RB_NOGVL_OFFLOAD_SAFE: c_int = 0x4;
506
+
507
+ /// Whether the calling Fiber's scheduler takes a wait `rb_nogvl` offers with
508
+ /// `RB_NOGVL_OFFLOAD_SAFE`, as Ruby 3.4 and later hand one to a scheduler
509
+ /// that defines `blocking_operation_wait`.
510
+ fn scheduler_takes_waits(ruby: &Ruby) -> bool {
511
+ let offers = (
512
+ rb_sys::RUBY_API_VERSION_MAJOR,
513
+ rb_sys::RUBY_API_VERSION_MINOR,
514
+ ) >= (3, 4);
515
+ offers
516
+ && ruby
517
+ .class_object()
518
+ .const_get::<_, RClass>("Fiber")
519
+ .and_then(|fiber| fiber.funcall::<_, _, Value>("current_scheduler", ()))
520
+ .is_ok_and(|scheduler| {
521
+ !scheduler.is_nil()
522
+ && scheduler
523
+ .respond_to("blocking_operation_wait", true)
524
+ .unwrap_or(false)
525
+ })
526
+ }
527
+
528
+ /// What a wait without the GVL hands Ruby's unblocking function.
529
+ struct Unblock<'a> {
530
+ task: &'a Task,
531
+ line: &'a handoff::Line,
532
+ }
533
+
534
+ /// Signal the run and wake the caller's wait, called by Ruby without the GVL
535
+ /// whenever it wakes the thread, or as a Fiber scheduler cancels the wait.
536
+ unsafe extern "C" fn unblock_wait(data: *mut c_void) {
537
+ // SAFETY: `released_wait` passes its own `Unblock`, alive for the whole
538
+ // wait Ruby calls this from.
539
+ let unblock = unsafe { &*data.cast::<Unblock<'_>>() };
540
+ unblock.task.signal();
541
+ unblock.line.wake_caller();
542
+ }
543
+
544
+ /// What the guest hands over next, waited for without the GVL: within a spin
545
+ /// first, as a callback mostly comes back that soon, then in a wait a Fiber
546
+ /// scheduler may hand to another thread, so the Thread's other Fibers run while
547
+ /// the guest does.
548
+ fn take_released(line: &handoff::Line, task: &Task) -> Message {
549
+ let unblock = Unblock { task, line };
550
+ loop {
551
+ if let Some(message) = released_wait(&unblock, 0, || line.take_spinning()) {
552
+ return message;
553
+ }
554
+ let waited = released_wait(&unblock, RB_NOGVL_OFFLOAD_SAFE, || line.take_until_woken());
555
+ if let Some(message) = waited {
556
+ return message;
557
+ }
558
+ }
559
+ }
560
+
561
+ /// Run `take` once without the GVL. What Ruby woke the thread for, or declined
562
+ /// to wait under, signals each wait the run meets, as a signal pending when a
563
+ /// Linux task sleeps wakes the sleep; what a Fiber scheduler raises where it
564
+ /// takes the wait over is the run's, held and ending its waits.
565
+ fn released_wait(
566
+ unblock: &Unblock<'_>,
567
+ flags: c_int,
568
+ mut take: impl FnMut() -> Option<Message>,
569
+ ) -> Option<Message> {
570
+ let data = ptr::addr_of!(*unblock).cast_mut().cast::<c_void>();
571
+ // A Ruby thread may go on on another native thread once it takes the GVL
572
+ // back, so the thread-local flag holds only while the wait runs.
573
+ let mut released = || {
574
+ let _released = ReleasedGuard::set(true);
575
+ take()
576
+ };
577
+ let mut taken = None;
578
+ let protected = magnus::rb_sys::protect(|| {
579
+ if escape::pending() {
580
+ unblock.task.interrupt();
581
+ } else if interrupt_pending() {
582
+ unblock.task.signal();
583
+ }
584
+ // SAFETY: `func` and `data` come from `call_via`, which keeps the
585
+ // closure alive across the call; `unblock` outlives it, and Ruby calls
586
+ // `unblock_wait` with it only while the wait runs.
587
+ taken = Some(call_via(&mut released, |func, closure| unsafe {
588
+ rb_sys::rb_nogvl(
589
+ Some(func),
590
+ closure,
591
+ Some(unblock_wait),
592
+ data,
593
+ RB_NOGVL_INTR_FAIL | flags,
594
+ )
595
+ }));
596
+ rb_sys::Qnil as rb_sys::VALUE
597
+ });
598
+ match (protected, taken) {
599
+ (Ok(_), Some(Ok(message))) => message,
600
+ // The run holds the interrupt and raises it once it ends, and the
601
+ // waits are signalled to take it as a callback would.
602
+ (Ok(_), _) => {
603
+ keeping_held_jump(escape::hold_interrupts);
604
+ unblock.task.signal();
605
+ None
606
+ }
607
+ (Err(raised), _) => {
608
+ escape::keep(raised);
609
+ unblock.task.interrupt();
610
+ None
611
+ }
186
612
  }
187
- let (value, raised) = handle_interrupt(ruby, "never", f);
188
- raised?;
189
- Ok(value.expect("a run under handle_interrupt returns"))
190
613
  }
191
614
 
192
615
  thread_local! {