kobako 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/Cargo.lock +868 -447
  6. data/README.md +43 -4
  7. data/ROADMAP.md +1 -2
  8. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  9. data/crates/kobako-runtime/Cargo.toml +58 -11
  10. data/crates/kobako-runtime/README.md +7 -4
  11. data/crates/kobako-runtime/src/cred.rs +136 -0
  12. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  13. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  14. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  15. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  16. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  17. data/crates/kobako-runtime/src/errno.rs +391 -0
  18. data/crates/kobako-runtime/src/error.rs +31 -10
  19. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  21. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +101 -29
  22. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  23. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +52 -34
  24. data/crates/kobako-runtime/src/filesystem/bind.rs +812 -447
  25. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  26. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +11 -16
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  31. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +120 -37
  32. data/crates/kobako-runtime/src/filesystem/overlay.rs +578 -388
  33. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  34. data/crates/kobako-runtime/src/filesystem/rdir.rs +14 -50
  35. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  38. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  39. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  40. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +219 -173
  41. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  42. data/crates/kobako-runtime/src/filesystem.rs +8 -3
  43. data/crates/kobako-runtime/src/fork.rs +319 -0
  44. data/crates/kobako-runtime/src/grant.rs +3 -0
  45. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  46. data/crates/kobako-runtime/src/lib.rs +18 -7
  47. data/crates/kobako-runtime/src/limits.rs +171 -0
  48. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  49. data/crates/kobako-runtime/src/locking.rs +518 -113
  50. data/crates/kobako-runtime/src/memcg.rs +306 -0
  51. data/crates/kobako-runtime/src/mount.rs +37 -9
  52. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  53. data/crates/kobako-runtime/src/net/connections.rs +219 -0
  54. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  55. data/crates/kobako-runtime/src/net/egress.rs +180 -0
  56. data/crates/kobako-runtime/src/net/family.rs +181 -0
  57. data/crates/kobako-runtime/src/net/http.rs +3165 -0
  58. data/crates/kobako-runtime/src/net/lookup.rs +385 -0
  59. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  60. data/crates/kobako-runtime/src/net/namespace.rs +1368 -0
  61. data/crates/kobako-runtime/src/net/reactor.rs +626 -0
  62. data/crates/kobako-runtime/src/net/resolv/darwin.rs +280 -0
  63. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +519 -0
  64. data/crates/kobako-runtime/src/net/resolv/stub.rs +542 -0
  65. data/crates/kobako-runtime/src/net/resolv/windows.rs +218 -0
  66. data/crates/kobako-runtime/src/net/resolv.rs +251 -0
  67. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  68. data/crates/kobako-runtime/src/net/socket.rs +869 -0
  69. data/crates/kobako-runtime/src/net/task.rs +223 -0
  70. data/crates/kobako-runtime/src/net/tcp.rs +1840 -0
  71. data/crates/kobako-runtime/src/net/tls.rs +120 -0
  72. data/crates/kobako-runtime/src/net/transport.rs +304 -0
  73. data/crates/kobako-runtime/src/net/udp.rs +1105 -0
  74. data/crates/kobako-runtime/src/net.rs +45 -0
  75. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  76. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  77. data/crates/kobako-runtime/src/network.rs +551 -0
  78. data/crates/kobako-runtime/src/policy.rs +16 -0
  79. data/crates/kobako-runtime/src/profile.rs +29 -144
  80. data/crates/kobako-runtime/src/runtime.rs +3 -5
  81. data/crates/kobako-runtime/src/sched.rs +338 -51
  82. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  83. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  84. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  85. data/crates/kobako-runtime/src/security.rs +125 -209
  86. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  87. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  88. data/crates/kobako-runtime/src/vfs/dentry.rs +210 -117
  89. data/crates/kobako-runtime/src/vfs/file.rs +243 -248
  90. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  91. data/crates/kobako-runtime/src/vfs/kern_path.rs +62 -53
  92. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  93. data/crates/kobako-runtime/src/vfs/namei.rs +1162 -818
  94. data/crates/kobako-runtime/src/vfs/namespace.rs +245 -0
  95. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  96. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  97. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  98. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  99. data/crates/kobako-runtime/src/vfs/stat.rs +248 -23
  100. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  101. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  102. data/crates/kobako-runtime/src/vfs.rs +10 -6
  103. data/crates/kobako-runtime/src/wait.rs +381 -0
  104. data/crates/kobako-transport/CHANGELOG.md +38 -0
  105. data/crates/kobako-transport/Cargo.toml +1 -1
  106. data/crates/kobako-transport/README.md +3 -4
  107. data/crates/kobako-transport/src/abi.rs +78 -72
  108. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  109. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  110. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  111. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  112. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  113. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  114. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  116. data/crates/kobako-transport/src/envelope.rs +13 -8
  117. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  118. data/crates/kobako-wasmtime/Cargo.toml +47 -7
  119. data/crates/kobako-wasmtime/README.md +4 -3
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +18 -37
  123. data/crates/kobako-wasmtime/src/ambient.rs +43 -19
  124. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  125. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  126. data/crates/kobako-wasmtime/src/cache.rs +106 -113
  127. data/crates/kobako-wasmtime/src/config.rs +52 -68
  128. data/crates/kobako-wasmtime/src/driver.rs +80 -82
  129. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  130. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  131. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  132. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  133. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  134. data/crates/kobako-wasmtime/src/invocation.rs +91 -15
  135. data/crates/kobako-wasmtime/src/lib.rs +7 -3
  136. data/crates/kobako-wasmtime/src/limiter.rs +130 -12
  137. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +305 -0
  138. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +9 -20
  139. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  140. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  141. data/crates/kobako-wasmtime/src/preview1/fd.rs +347 -312
  142. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  143. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  144. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +335 -388
  145. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  146. data/crates/kobako-wasmtime/src/preview1/poll.rs +255 -125
  147. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  148. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  149. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  150. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  151. data/crates/kobako-wasmtime/src/preview1.rs +131 -51
  152. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  153. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  154. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  155. data/crates/kobako-wasmtime/src/preview2/host.rs +4319 -0
  156. data/crates/kobako-wasmtime/src/preview2/http.rs +1587 -0
  157. data/crates/kobako-wasmtime/src/preview2/io.rs +328 -0
  158. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  159. data/crates/kobako-wasmtime/src/preview2/table.rs +257 -0
  160. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  161. data/crates/kobako-wasmtime/src/trap.rs +88 -28
  162. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  163. data/crates/kobako-wasmtime/src/wasi.rs +291 -81
  164. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  165. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  166. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  167. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  168. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  169. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  170. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  171. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  172. data/data/kobako.wasm +0 -0
  173. data/ext/kobako/Cargo.toml +6 -2
  174. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  175. data/ext/kobako/src/escape.rs +404 -0
  176. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +34 -32
  177. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +158 -170
  178. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +71 -23
  179. data/ext/kobako/src/fork.rs +72 -0
  180. data/ext/kobako/src/gvl.rs +729 -0
  181. data/ext/kobako/src/handoff.rs +490 -0
  182. data/ext/kobako/src/lib.rs +74 -3
  183. data/ext/kobako/src/network/mock.rs +187 -0
  184. data/ext/kobako/src/network.rs +593 -0
  185. data/ext/kobako/src/pinned_value.rs +44 -0
  186. data/ext/kobako/src/runtime/bridge.rs +58 -50
  187. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  188. data/ext/kobako/src/runtime.rs +272 -163
  189. data/ext/kobako/src/wire.rs +42 -0
  190. data/lib/kobako/catalog/extensions.rb +14 -2
  191. data/lib/kobako/catalog/flags.rb +3 -5
  192. data/lib/kobako/catalog/grants.rb +5 -4
  193. data/lib/kobako/catalog/handles.rb +14 -32
  194. data/lib/kobako/catalog/mount.rb +11 -3
  195. data/lib/kobako/catalog/network.rb +35 -0
  196. data/lib/kobako/catalog/replacements.rb +28 -0
  197. data/lib/kobako/catalog/services.rb +5 -19
  198. data/lib/kobako/catalog/snippets.rb +3 -18
  199. data/lib/kobako/catalog.rb +3 -0
  200. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  201. data/lib/kobako/codec/decoder.rb +5 -5
  202. data/lib/kobako/codec/ext_types.rb +3 -3
  203. data/lib/kobako/codec/handle_walk.rb +3 -43
  204. data/lib/kobako/codec/state.rb +2 -18
  205. data/lib/kobako/codec/value_budget.rb +133 -41
  206. data/lib/kobako/codec.rb +6 -7
  207. data/lib/kobako/context.rb +24 -11
  208. data/lib/kobako/errors.rb +18 -18
  209. data/lib/kobako/extension.rb +3 -2
  210. data/lib/kobako/filesystem.rb +10 -3
  211. data/lib/kobako/fork.rb +42 -0
  212. data/lib/kobako/handle.rb +2 -3
  213. data/lib/kobako/names.rb +28 -0
  214. data/lib/kobako/network.rb +210 -0
  215. data/lib/kobako/outcome.rb +7 -7
  216. data/lib/kobako/runtime.rb +3 -2
  217. data/lib/kobako/sandbox.rb +73 -35
  218. data/lib/kobako/sandbox_options.rb +42 -109
  219. data/lib/kobako/transport/argument_wrap.rb +64 -0
  220. data/lib/kobako/transport/block_failure.rb +1 -1
  221. data/lib/kobako/transport/dispatcher.rb +6 -6
  222. data/lib/kobako/transport/exposure.rb +26 -15
  223. data/lib/kobako/transport/reflection.rb +21 -4
  224. data/lib/kobako/transport/run.rb +8 -23
  225. data/lib/kobako/transport/yielder.rb +2 -9
  226. data/lib/kobako/transport.rb +1 -0
  227. data/lib/kobako/usage.rb +4 -2
  228. data/lib/kobako/version.rb +1 -1
  229. data/lib/kobako.rb +8 -4
  230. data/release-please-config.json +15 -0
  231. data/sig/kobako/catalog/extensions.rbs +2 -0
  232. data/sig/kobako/catalog/grants.rbs +7 -4
  233. data/sig/kobako/catalog/handles.rbs +2 -2
  234. data/sig/kobako/catalog/mount.rbs +3 -1
  235. data/sig/kobako/catalog/network.rbs +20 -0
  236. data/sig/kobako/catalog/replacements.rbs +14 -0
  237. data/sig/kobako/catalog/services.rbs +0 -4
  238. data/sig/kobako/catalog/snippets.rbs +0 -2
  239. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  240. data/sig/kobako/codec/handle_walk.rbs +0 -6
  241. data/sig/kobako/codec/state.rbs +0 -4
  242. data/sig/kobako/codec/value_budget.rbs +48 -5
  243. data/sig/kobako/codec.rbs +2 -2
  244. data/sig/kobako/context.rbs +3 -1
  245. data/sig/kobako/errors.rbs +4 -7
  246. data/sig/kobako/filesystem.rbs +21 -3
  247. data/sig/kobako/fork.rbs +17 -0
  248. data/sig/kobako/network.rbs +115 -0
  249. data/sig/kobako/outcome.rbs +1 -1
  250. data/sig/kobako/runtime.rbs +32 -3
  251. data/sig/kobako/sandbox.rbs +10 -2
  252. data/sig/kobako/sandbox_options.rbs +29 -40
  253. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  254. data/sig/kobako/transport/error.rbs +1 -1
  255. data/sig/kobako/transport/exposure.rbs +2 -4
  256. data/sig/kobako/transport/reflection.rbs +10 -0
  257. data/sig/kobako/transport/run.rbs +0 -2
  258. data/sig/kobako/transport/yielder.rbs +0 -3
  259. data/sig/kobako/transport.rbs +1 -1
  260. data/sig/kobako.rbs +13 -0
  261. metadata +97 -37
  262. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  263. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  264. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  265. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  266. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  267. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  268. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  269. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  270. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  271. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  272. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  273. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  274. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  275. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  276. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  277. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  278. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  279. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  280. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  281. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  282. data/ext/kobako/src/runtime/escape.rs +0 -67
  283. data/ext/kobako/src/runtime/gvl.rs +0 -147
  284. data/ext/kobako/src/runtime/pinned_value.rs +0 -31
  285. data/lib/kobako/constant_name.rb +0 -8
  286. data/lib/kobako/pool.rb +0 -140
  287. data/sig/kobako/constant_name.rbs +0 -3
  288. data/sig/kobako/pool.rbs +0 -42
@@ -0,0 +1,729 @@
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.
4
+ //!
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
+ //!
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.
20
+
21
+ use std::cell::Cell;
22
+ use std::ffi::CString;
23
+ use std::os::raw::{c_char, c_int, c_long, c_void};
24
+ use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
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
+
30
+ use kobako_runtime::sched::{run_interruptible, Blocking, Current, Task};
31
+
32
+ use magnus::block::Proc;
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};
38
+
39
+ use super::errors;
40
+ use super::escape;
41
+ use super::fork;
42
+ use super::handoff::{self, Message};
43
+
44
+ thread_local! {
45
+ // True while this thread sits inside a region whose GVL we released and
46
+ // have not yet re-acquired. Drives `reenter`'s one-shot re-acquire.
47
+ static GVL_RELEASED: Cell<bool> = const { Cell::new(false) };
48
+ }
49
+
50
+ fn region<F, R>(release: bool, f: F) -> R
51
+ where
52
+ F: FnOnce() -> R,
53
+ {
54
+ if !release {
55
+ return f();
56
+ }
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.
62
+ let task = Task::current();
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
+ };
74
+ run_interruptible(|| {
75
+ loop {
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
79
+ // inside it does, as a signal pending when a Linux task sleeps
80
+ // wakes the sleep.
81
+ if escape::pending() {
82
+ task.interrupt();
83
+ } else if interrupt_pending() {
84
+ task.signal();
85
+ }
86
+ // SAFETY: `func` and `data` come from `call_via`, which keeps the
87
+ // closure alive across the call; `task` outlives it on this frame,
88
+ // and Ruby calls `signal_task` with it only while the region runs.
89
+ unsafe {
90
+ rb_sys::rb_thread_call_without_gvl2(
91
+ Some(func),
92
+ data,
93
+ Some(signal_task),
94
+ task_ptr,
95
+ )
96
+ }
97
+ });
98
+ match ran {
99
+ Ok(value) => return value,
100
+ // A run holds the interrupt and raises it once back in Ruby.
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();
106
+ }
107
+ // Outside a run nothing would raise a held interrupt, so it
108
+ // stays with Ruby, which raises it as this call returns; the
109
+ // wait runs with the GVL kept and ends at once, interrupted.
110
+ Err(_) => {
111
+ task.interrupt();
112
+ return current.carry(take());
113
+ }
114
+ }
115
+ }
116
+ })
117
+ }
118
+
119
+ /// Whether Ruby holds an interrupt or a signal for this thread, deferred or
120
+ /// not, asked without running it.
121
+ fn interrupt_pending() -> bool {
122
+ // SAFETY: `rb_thread_interrupted` only reads the current thread's flags,
123
+ // which Ruby allows even without the GVL.
124
+ unsafe { rb_sys::rb_thread_interrupted(rb_sys::rb_thread_current()) != 0 }
125
+ }
126
+
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) {
131
+ // SAFETY: `region` passes its own `Task`, alive for the whole region
132
+ // Ruby calls this from.
133
+ let task = unsafe { &*task.cast::<Task>() };
134
+ task.signal();
135
+ }
136
+
137
+ /// Whether this thread holds the GVL: outside any released region, or
138
+ /// inside a dispatch that re-acquired it.
139
+ fn holds() -> bool {
140
+ !GVL_RELEASED.with(|g| g.get())
141
+ }
142
+
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
145
+ /// the GVL and finish, and other Threads run while the guest sleeps.
146
+ pub(crate) struct GvlFreeWait;
147
+
148
+ impl Blocking for GvlFreeWait {
149
+ fn wait(&self, wait: &mut dyn FnMut()) {
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())
190
+ }
191
+ }
192
+
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>
206
+ where
207
+ F: FnOnce() -> R,
208
+ {
209
+ if handoff::on_guest() {
210
+ return handoff::on_caller(|| reenter(f)).flatten();
211
+ }
212
+ if holds() {
213
+ return Some(keeping_held_jump(f));
214
+ }
215
+ let _guard = ReleasedGuard::set(false);
216
+ // Ruby checks for interrupts as it gives the GVL back on the way out, and
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.
220
+ let run_callback = |f: F| {
221
+ let ruby = Ruby::get().expect("a thread back in Ruby holds the GVL");
222
+ let (value, raised) = keeping_held_jump(|| handle_interrupt(&ruby, "immediate", f));
223
+ if let Err(error) = raised {
224
+ escape::keep(error);
225
+ }
226
+ value.expect("a callback run under handle_interrupt returns")
227
+ };
228
+ // SAFETY: `func` and `data` come from `call_via`, which keeps the
229
+ // closure alive across the call, and this thread is a Ruby thread
230
+ // inside a region that released the GVL, as the call requires.
231
+ let ran = call_via(
232
+ || run_callback(f),
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"),
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
+ })
277
+ .ok()
278
+ .expect("rb_ensure always runs its ensure function")
279
+ }
280
+
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);
302
+ run.finish()?;
303
+ Ok(ran)
304
+ }
305
+
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>(
312
+ ruby: &Ruby,
313
+ release: bool,
314
+ waiting: &Arc<AtomicUsize>,
315
+ state: &Arc<escape::RunState>,
316
+ f: impl FnOnce() -> R + Send + 'static,
317
+ ) -> Result<R, MagnusError> {
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
+ }
612
+ }
613
+ }
614
+
615
+ thread_local! {
616
+ // The body the block `handle_interrupt` yields to runs, kept here as a
617
+ // block takes no closure.
618
+ static BODY: Cell<Option<*mut (dyn FnMut() + 'static)>> = const { Cell::new(None) };
619
+ }
620
+
621
+ /// `Thread.handle_interrupt(Object => timing) { f }`: what `f` returned, if it
622
+ /// ran to its end, and what the call raised, as one deferred interrupt comes
623
+ /// as the mask is lifted.
624
+ fn handle_interrupt<R>(
625
+ ruby: &Ruby,
626
+ timing: &str,
627
+ f: impl FnOnce() -> R,
628
+ ) -> (Option<R>, Result<(), MagnusError>) {
629
+ /// The body of the call around this one, put back on drop.
630
+ struct OuterBody(Option<*mut (dyn FnMut() + 'static)>);
631
+
632
+ impl Drop for OuterBody {
633
+ fn drop(&mut self) {
634
+ BODY.with(|body| body.set(self.0));
635
+ }
636
+ }
637
+
638
+ fn run_body(ruby: &Ruby, _args: &[Value], _block: Option<Proc>) -> Value {
639
+ if let Some(body) = BODY.with(Cell::get) {
640
+ // SAFETY: `handle_interrupt` set it for the length of this call,
641
+ // which yields to this block at most once, on this thread.
642
+ unsafe { (*body)() };
643
+ }
644
+ ruby.qnil().as_value()
645
+ }
646
+
647
+ let mut f = Some(f);
648
+ let mut value = None;
649
+ let mut body = || value = f.take().map(|f| f());
650
+ let body: &mut dyn FnMut() = &mut body;
651
+ // SAFETY: only the lifetime is erased; `OuterBody` takes the pointer back
652
+ // before `body` goes out of scope, and nothing else keeps it.
653
+ let body: *mut (dyn FnMut() + 'static) = unsafe { std::mem::transmute(body) };
654
+ let outer = OuterBody(BODY.with(|current| current.replace(Some(body))));
655
+ let mask = ruby.hash_new();
656
+ let raised = mask
657
+ .aset(ruby.class_object(), ruby.to_symbol(timing))
658
+ .and_then(|()| {
659
+ ruby.class_thread()
660
+ .funcall_with_block::<_, _, Value>(
661
+ "handle_interrupt",
662
+ (mask,),
663
+ ruby.proc_new(run_body),
664
+ )
665
+ .map(|_| ())
666
+ });
667
+ drop(outer);
668
+ (value, raised)
669
+ }
670
+
671
+ /// Restores `GVL_RELEASED` to its prior value on drop, so an unwinding panic
672
+ /// through a released region cannot leave the flag stuck.
673
+ struct ReleasedGuard {
674
+ prev: bool,
675
+ }
676
+
677
+ impl ReleasedGuard {
678
+ fn set(value: bool) -> Self {
679
+ Self {
680
+ prev: GVL_RELEASED.with(|g| g.replace(value)),
681
+ }
682
+ }
683
+ }
684
+
685
+ impl Drop for ReleasedGuard {
686
+ fn drop(&mut self) {
687
+ GVL_RELEASED.with(|g| g.set(self.prev));
688
+ }
689
+ }
690
+
691
+ struct GvlCtx<F, R> {
692
+ f: Option<F>,
693
+ result: Option<std::thread::Result<R>>,
694
+ }
695
+
696
+ /// Runs the closure under `catch_unwind`, so a panic is captured here rather
697
+ /// than unwinding across the C frame.
698
+ unsafe extern "C" fn trampoline<F, R>(data: *mut c_void) -> *mut c_void
699
+ where
700
+ F: FnOnce() -> R,
701
+ {
702
+ // SAFETY: `call_via` passes its own `GvlCtx<F, R>`, borrowed by nothing
703
+ // else for the length of the call.
704
+ let ctx = unsafe { &mut *data.cast::<GvlCtx<F, R>>() };
705
+ let f = ctx.f.take().expect("gvl trampoline runs its closure once");
706
+ ctx.result = Some(catch_unwind(AssertUnwindSafe(f)));
707
+ ptr::null_mut()
708
+ }
709
+
710
+ /// Run `f` through `invoke`, or hand it back when Ruby ran nothing because an
711
+ /// interrupt is pending, as `rb_thread_call_without_gvl2` does.
712
+ fn call_via<F, R>(
713
+ f: F,
714
+ mut invoke: impl FnMut(unsafe extern "C" fn(*mut c_void) -> *mut c_void, *mut c_void) -> *mut c_void,
715
+ ) -> Result<R, F>
716
+ where
717
+ F: FnOnce() -> R,
718
+ {
719
+ let mut ctx = GvlCtx::<F, R> {
720
+ f: Some(f),
721
+ result: None,
722
+ };
723
+ invoke(trampoline::<F, R>, ptr::addr_of_mut!(ctx).cast::<c_void>());
724
+ match ctx.result.take() {
725
+ Some(Ok(value)) => Ok(value),
726
+ Some(Err(payload)) => resume_unwind(payload),
727
+ None => Err(ctx.f.take().expect("a declined call keeps its closure")),
728
+ }
729
+ }