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.
- checksums.yaml +4 -4
- data/.githooks/linux-tests.sh +29 -0
- data/.release-please-manifest.json +1 -1
- data/CHANGELOG.md +125 -0
- data/Cargo.lock +457 -494
- data/README.md +2 -3
- data/ROADMAP.md +0 -1
- data/crates/kobako-runtime/CHANGELOG.md +90 -0
- data/crates/kobako-runtime/Cargo.toml +14 -15
- data/crates/kobako-runtime/README.md +1 -1
- data/crates/kobako-runtime/src/cred.rs +32 -20
- data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
- data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +56 -22
- data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
- data/crates/kobako-runtime/src/filesystem/bind/walk.rs +33 -14
- data/crates/kobako-runtime/src/filesystem/bind.rs +393 -220
- data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +2 -0
- data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +9 -10
- data/crates/kobako-runtime/src/filesystem/overlay.rs +277 -46
- data/crates/kobako-runtime/src/filesystem/rdir.rs +8 -27
- data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
- data/crates/kobako-runtime/src/filesystem/tmpfs.rs +47 -13
- data/crates/kobako-runtime/src/filesystem.rs +2 -0
- data/crates/kobako-runtime/src/fork.rs +239 -16
- data/crates/kobako-runtime/src/limits.rs +17 -41
- data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
- data/crates/kobako-runtime/src/locking.rs +508 -113
- data/crates/kobako-runtime/src/memcg.rs +83 -160
- data/crates/kobako-runtime/src/mount.rs +0 -30
- data/crates/kobako-runtime/src/net/connections.rs +53 -13
- data/crates/kobako-runtime/src/net/egress.rs +44 -24
- data/crates/kobako-runtime/src/net/http.rs +888 -456
- data/crates/kobako-runtime/src/net/lookup.rs +150 -50
- data/crates/kobako-runtime/src/net/namespace.rs +97 -95
- data/crates/kobako-runtime/src/net/reactor.rs +298 -203
- data/crates/kobako-runtime/src/net/resolv/darwin.rs +8 -3
- data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +50 -0
- data/crates/kobako-runtime/src/net/resolv/stub.rs +29 -23
- data/crates/kobako-runtime/src/net/resolv/windows.rs +14 -44
- data/crates/kobako-runtime/src/net/resolv.rs +39 -15
- data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
- data/crates/kobako-runtime/src/net/socket.rs +51 -52
- data/crates/kobako-runtime/src/net/task.rs +223 -0
- data/crates/kobako-runtime/src/net/tcp.rs +410 -158
- data/crates/kobako-runtime/src/net/tls.rs +65 -3
- data/crates/kobako-runtime/src/net/transport.rs +72 -47
- data/crates/kobako-runtime/src/net/udp.rs +231 -129
- data/crates/kobako-runtime/src/net.rs +3 -0
- data/crates/kobako-runtime/src/sched.rs +244 -58
- data/crates/kobako-runtime/src/security.rs +27 -16
- data/crates/kobako-runtime/src/vfs/dentry.rs +80 -41
- data/crates/kobako-runtime/src/vfs/file.rs +52 -53
- data/crates/kobako-runtime/src/vfs/kern_path.rs +24 -11
- data/crates/kobako-runtime/src/vfs/namei.rs +399 -184
- data/crates/kobako-runtime/src/vfs/namespace.rs +123 -40
- data/crates/kobako-runtime/src/vfs/stat.rs +105 -16
- data/crates/kobako-runtime/src/vfs.rs +1 -0
- data/crates/kobako-runtime/src/wait.rs +75 -50
- data/crates/kobako-transport/CHANGELOG.md +7 -0
- data/crates/kobako-transport/Cargo.toml +1 -1
- data/crates/kobako-transport/README.md +1 -1
- data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
- data/crates/kobako-wasmtime/Cargo.toml +27 -6
- data/crates/kobako-wasmtime/README.md +3 -3
- data/crates/kobako-wasmtime/src/abi.rs +2 -1
- data/crates/kobako-wasmtime/src/ambient.rs +11 -2
- data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
- data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
- data/crates/kobako-wasmtime/src/cache.rs +88 -103
- data/crates/kobako-wasmtime/src/driver.rs +40 -27
- data/crates/kobako-wasmtime/src/invocation.rs +21 -7
- data/crates/kobako-wasmtime/src/lib.rs +2 -0
- data/crates/kobako-wasmtime/src/limiter.rs +78 -25
- data/crates/kobako-wasmtime/src/preview1/descriptors.rs +13 -17
- data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +4 -5
- data/crates/kobako-wasmtime/src/preview1/differential.rs +1 -1
- data/crates/kobako-wasmtime/src/preview1/fd.rs +23 -19
- data/crates/kobako-wasmtime/src/preview1/mount_view.rs +130 -197
- data/crates/kobako-wasmtime/src/preview1/path.rs +3 -3
- data/crates/kobako-wasmtime/src/preview1/poll.rs +28 -22
- data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
- data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
- data/crates/kobako-wasmtime/src/preview1.rs +85 -9
- data/crates/kobako-wasmtime/src/preview2/filesystem.rs +2 -2
- data/crates/kobako-wasmtime/src/preview2/host.rs +609 -249
- data/crates/kobako-wasmtime/src/preview2/http.rs +299 -215
- data/crates/kobako-wasmtime/src/preview2/io.rs +17 -4
- data/crates/kobako-wasmtime/src/preview2/table.rs +24 -72
- data/crates/kobako-wasmtime/src/trap.rs +68 -23
- data/crates/kobako-wasmtime/src/waits.rs +59 -0
- data/crates/kobako-wasmtime/src/wasi.rs +91 -10
- data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
- data/data/kobako.wasm +0 -0
- data/ext/kobako/Cargo.toml +6 -2
- data/ext/kobako/src/escape.rs +332 -26
- data/ext/kobako/src/filesystem/grants.rs +5 -7
- data/ext/kobako/src/filesystem/ruby.rs +10 -3
- data/ext/kobako/src/filesystem.rs +47 -8
- data/ext/kobako/src/fork.rs +72 -0
- data/ext/kobako/src/gvl.rs +499 -76
- data/ext/kobako/src/handoff.rs +490 -0
- data/ext/kobako/src/lib.rs +10 -0
- data/ext/kobako/src/network.rs +5 -3
- data/ext/kobako/src/pinned_value.rs +28 -15
- data/ext/kobako/src/runtime/bridge.rs +32 -25
- data/ext/kobako/src/runtime.rs +74 -43
- data/lib/kobako/catalog/handles.rb +9 -5
- data/lib/kobako/codec/decoder.rb +1 -1
- data/lib/kobako/codec/state.rb +2 -18
- data/lib/kobako/codec/value_budget.rb +4 -4
- data/lib/kobako/codec.rb +5 -6
- data/lib/kobako/errors.rb +4 -7
- data/lib/kobako/filesystem.rb +1 -1
- data/lib/kobako/fork.rb +42 -0
- data/lib/kobako/handle.rb +1 -2
- data/lib/kobako/sandbox.rb +17 -36
- data/lib/kobako/sandbox_options.rb +7 -9
- data/lib/kobako/usage.rb +4 -2
- data/lib/kobako/version.rb +1 -1
- data/lib/kobako.rb +2 -2
- data/sig/kobako/catalog/handles.rbs +2 -0
- data/sig/kobako/codec/state.rbs +0 -4
- data/sig/kobako/codec/value_budget.rbs +1 -1
- data/sig/kobako/codec.rbs +2 -2
- data/sig/kobako/errors.rbs +0 -3
- data/sig/kobako/fork.rbs +17 -0
- data/sig/kobako/runtime.rbs +2 -2
- data/sig/kobako/sandbox.rbs +3 -12
- data/sig/kobako/sandbox_options.rbs +0 -2
- metadata +15 -4
- data/lib/kobako/pool.rb +0 -162
- data/sig/core/thread.rbs +0 -6
- data/sig/kobako/pool.rbs +0 -46
|
@@ -18,14 +18,25 @@
|
|
|
18
18
|
//! wait on each other. Two concurrent misses on one path both compile,
|
|
19
19
|
//! and the later insert wins with an equivalent Module.
|
|
20
20
|
|
|
21
|
+
#[cfg(unix)]
|
|
22
|
+
mod unix;
|
|
23
|
+
#[cfg(windows)]
|
|
24
|
+
mod windows;
|
|
25
|
+
|
|
21
26
|
use std::collections::HashMap;
|
|
27
|
+
use std::ffi::OsStr;
|
|
22
28
|
use std::fmt::Write as _;
|
|
23
29
|
use std::fs;
|
|
24
30
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
|
25
31
|
use std::path::{Path, PathBuf};
|
|
26
32
|
use std::sync::{Mutex, OnceLock};
|
|
27
33
|
use std::thread;
|
|
28
|
-
use std::time::Duration;
|
|
34
|
+
use std::time::{Duration, SystemTime};
|
|
35
|
+
|
|
36
|
+
#[cfg(unix)]
|
|
37
|
+
use unix::PrivateDir;
|
|
38
|
+
#[cfg(windows)]
|
|
39
|
+
use windows::PrivateDir;
|
|
29
40
|
|
|
30
41
|
use sha2::{Digest, Sha256};
|
|
31
42
|
use wasmtime::{Config as WtConfig, Engine as WtEngine, Module as WtModule};
|
|
@@ -51,22 +62,33 @@ const EPOCH_TICK: Duration = Duration::from_millis(10);
|
|
|
51
62
|
/// one ticker thread per process.
|
|
52
63
|
pub(crate) fn load_engine() -> Result<&'static WtEngine, SetupError> {
|
|
53
64
|
if let Some(engine) = SHARED_ENGINE.get() {
|
|
54
|
-
spawn_epoch_ticker(engine)
|
|
65
|
+
spawn_epoch_ticker(engine)?;
|
|
55
66
|
return Ok(engine);
|
|
56
67
|
}
|
|
57
68
|
let mut config = WtConfig::new();
|
|
58
69
|
config.wasm_exceptions(true);
|
|
59
70
|
config.epoch_interruption(true);
|
|
71
|
+
catch_traps(&mut config);
|
|
60
72
|
let engine =
|
|
61
73
|
WtEngine::new(&config).map_err(|e| SetupError::Dead(format!("engine init: {e}")))?;
|
|
62
74
|
let engine = SHARED_ENGINE.get_or_init(|| engine);
|
|
63
|
-
spawn_epoch_ticker(engine)
|
|
75
|
+
spawn_epoch_ticker(engine)?;
|
|
64
76
|
Ok(engine)
|
|
65
77
|
}
|
|
66
78
|
|
|
79
|
+
/// macOS hands a guest's faults to wasmtime over a Mach port by default,
|
|
80
|
+
/// which no forked child can use; POSIX signals carry across a fork. The
|
|
81
|
+
/// choice belongs to the whole process, so every Engine in it must make the
|
|
82
|
+
/// same one, or wasmtime panics creating the one that differs.
|
|
83
|
+
fn catch_traps(config: &mut WtConfig) {
|
|
84
|
+
config.macos_use_mach_ports(!cfg!(feature = "posix-signals-on-macos"));
|
|
85
|
+
}
|
|
86
|
+
|
|
67
87
|
/// The ticker is the process's own: a forked child, which inherits the Engine
|
|
68
|
-
/// but no thread, starts one of its own, or no deadline would fire in it.
|
|
69
|
-
|
|
88
|
+
/// but no thread, starts one of its own, or no deadline would fire in it. A
|
|
89
|
+
/// host with no thread to start for it fails the caller, and the next caller
|
|
90
|
+
/// starts it again.
|
|
91
|
+
fn spawn_epoch_ticker(engine: &WtEngine) -> Result<(), SetupError> {
|
|
70
92
|
static TICKER: ProcessLocal<()> = ProcessLocal::new();
|
|
71
93
|
TICKER.with(|ticker| {
|
|
72
94
|
if ticker.is_none() {
|
|
@@ -77,10 +99,11 @@ fn spawn_epoch_ticker(engine: &WtEngine) {
|
|
|
77
99
|
thread::sleep(EPOCH_TICK);
|
|
78
100
|
engine.increment_epoch();
|
|
79
101
|
})
|
|
80
|
-
.
|
|
102
|
+
.map_err(|err| SetupError::Dead(format!("can't create Thread: {err}")))?;
|
|
81
103
|
*ticker = Some(());
|
|
82
104
|
}
|
|
83
|
-
|
|
105
|
+
Ok(())
|
|
106
|
+
})
|
|
84
107
|
}
|
|
85
108
|
|
|
86
109
|
/// A missing file answers `SetupError::GuestBinaryNotFound`, the common state of
|
|
@@ -133,7 +156,6 @@ pub(crate) fn load_module(path: &Path) -> Result<WtModule, SetupError> {
|
|
|
133
156
|
/// Retention window for unused cache entries. A hit refreshes the
|
|
134
157
|
/// artifact's mtime, so only entries no process has loaded for the
|
|
135
158
|
/// whole window are removed by `prune_stale`.
|
|
136
|
-
#[cfg(unix)]
|
|
137
159
|
const ARTIFACT_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
|
|
138
160
|
|
|
139
161
|
/// Content addressing makes a rebuilt Guest Binary a new entry rather than
|
|
@@ -145,7 +167,7 @@ const ARTIFACT_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
|
|
|
145
167
|
fn artifact_path(engine: &WtEngine, wasm_bytes: &[u8]) -> Option<PathBuf> {
|
|
146
168
|
let base = std::env::var_os("XDG_CACHE_HOME")
|
|
147
169
|
.map(PathBuf::from)
|
|
148
|
-
.or_else(
|
|
170
|
+
.or_else(cache_home)?;
|
|
149
171
|
let digest = Sha256::digest(wasm_bytes);
|
|
150
172
|
let mut name = String::with_capacity(96);
|
|
151
173
|
for byte in digest {
|
|
@@ -155,6 +177,19 @@ fn artifact_path(engine: &WtEngine, wasm_bytes: &[u8]) -> Option<PathBuf> {
|
|
|
155
177
|
Some(base.join("kobako").join(name))
|
|
156
178
|
}
|
|
157
179
|
|
|
180
|
+
/// Where the platform keeps a user's caches when `XDG_CACHE_HOME` names
|
|
181
|
+
/// none: `~/.cache` on Unix, as the XDG Base Directory spec sets, and the
|
|
182
|
+
/// local application data folder on Windows.
|
|
183
|
+
#[cfg(unix)]
|
|
184
|
+
fn cache_home() -> Option<PathBuf> {
|
|
185
|
+
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache"))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
#[cfg(windows)]
|
|
189
|
+
fn cache_home() -> Option<PathBuf> {
|
|
190
|
+
std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
|
|
191
|
+
}
|
|
192
|
+
|
|
158
193
|
/// wasmtime's hash of everything an artifact's compatibility depends on,
|
|
159
194
|
/// its full release version included. `DefaultHasher::new` is unseeded,
|
|
160
195
|
/// so every process of one build derives the same key.
|
|
@@ -166,17 +201,14 @@ fn engine_key(engine: &WtEngine) -> u64 {
|
|
|
166
201
|
|
|
167
202
|
/// A hit refreshes the file's mtime, so the retention window measures time
|
|
168
203
|
/// since last use rather than since creation.
|
|
169
|
-
#[cfg(unix)]
|
|
170
204
|
fn load_artifact(engine: &WtEngine, artifact: &Path) -> Option<WtModule> {
|
|
171
|
-
|
|
172
|
-
let
|
|
173
|
-
let
|
|
174
|
-
let file = fs::File::from(openat(&dir, artifact.file_name()?, flags, Mode::empty()).ok()?);
|
|
175
|
-
let _ = file.set_modified(std::time::SystemTime::now());
|
|
205
|
+
let dir = PrivateDir::open(artifact.parent()?)?;
|
|
206
|
+
let file = dir.open_entry(artifact.file_name()?)?;
|
|
207
|
+
let _ = file.set_modified(SystemTime::now());
|
|
176
208
|
// SAFETY: `Module::deserialize_open_file` trusts the artifact bytes
|
|
177
209
|
// and needs them unchanged while the Module lives. The file was
|
|
178
|
-
// opened through the directory `
|
|
179
|
-
//
|
|
210
|
+
// opened through the directory `PrivateDir::open` checked, which no
|
|
211
|
+
// other user can write, so it is an artifact this module
|
|
180
212
|
// stored, addressed by the content hash of the Guest Binary being
|
|
181
213
|
// constructed — it carries exactly that binary's trust.
|
|
182
214
|
unsafe { WtModule::deserialize_open_file(engine, file) }.ok()
|
|
@@ -188,9 +220,7 @@ fn load_artifact(engine: &WtEngine, artifact: &Path) -> Option<WtModule> {
|
|
|
188
220
|
/// unsafe deserialize would trust. Failures are swallowed because the
|
|
189
221
|
/// cache is only an optimisation, and pruning on write keeps the
|
|
190
222
|
/// directory bounded across rebuilds.
|
|
191
|
-
#[cfg(unix)]
|
|
192
223
|
fn store_artifact(module: &WtModule, artifact: &Path) {
|
|
193
|
-
use rustix::fs::{fsync, renameat};
|
|
194
224
|
use std::io::Write as _;
|
|
195
225
|
let (Some(dir), Some(name)) = (artifact.parent(), artifact.file_name()) else {
|
|
196
226
|
return;
|
|
@@ -198,13 +228,13 @@ fn store_artifact(module: &WtModule, artifact: &Path) {
|
|
|
198
228
|
let Ok(bytes) = module.serialize() else {
|
|
199
229
|
return;
|
|
200
230
|
};
|
|
201
|
-
if
|
|
231
|
+
if PrivateDir::create(dir).is_err() {
|
|
202
232
|
return;
|
|
203
233
|
}
|
|
204
|
-
let Some(dir) =
|
|
234
|
+
let Some(dir) = PrivateDir::open(dir) else {
|
|
205
235
|
return;
|
|
206
236
|
};
|
|
207
|
-
let Some((tmp, mut file)) = create_temp(
|
|
237
|
+
let Some((tmp, mut file)) = dir.create_temp(name) else {
|
|
208
238
|
return;
|
|
209
239
|
};
|
|
210
240
|
if file
|
|
@@ -214,95 +244,27 @@ fn store_artifact(module: &WtModule, artifact: &Path) {
|
|
|
214
244
|
{
|
|
215
245
|
return;
|
|
216
246
|
}
|
|
217
|
-
if
|
|
218
|
-
let _ = fsync(&dir);
|
|
247
|
+
if dir.rename(&tmp, name) {
|
|
219
248
|
prune_stale(&dir, name);
|
|
220
249
|
}
|
|
221
250
|
}
|
|
222
251
|
|
|
223
|
-
/// A temp file no other writer shares: two threads of one process storing
|
|
224
|
-
/// the same artifact at once would otherwise write into one file, and a
|
|
225
|
-
/// reader could load the interleaved bytes the unsafe deserialize trusts.
|
|
226
|
-
#[cfg(unix)]
|
|
227
|
-
fn create_temp(dir: &rustix::fd::OwnedFd, name: &std::ffi::OsStr) -> Option<(PathBuf, fs::File)> {
|
|
228
|
-
use rustix::fs::{openat, Mode, OFlags};
|
|
229
|
-
use std::sync::atomic::{AtomicU64, Ordering};
|
|
230
|
-
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
|
|
231
|
-
let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
|
|
232
|
-
let tmp = Path::new(name).with_extension(format!("tmp{}.{serial}", std::process::id()));
|
|
233
|
-
let flags = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
|
234
|
-
let fd = openat(dir, &tmp, flags, Mode::RUSR | Mode::WUSR).ok()?;
|
|
235
|
-
Some((tmp, fs::File::from(fd)))
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/// The disk cache trusts its directory's owner, which only Unix reports,
|
|
239
|
-
/// so elsewhere every process compiles the Guest Binary itself.
|
|
240
|
-
#[cfg(not(unix))]
|
|
241
|
-
fn load_artifact(_engine: &WtEngine, _artifact: &Path) -> Option<WtModule> {
|
|
242
|
-
None
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
#[cfg(not(unix))]
|
|
246
|
-
fn store_artifact(_module: &WtModule, _artifact: &Path) {}
|
|
247
|
-
|
|
248
|
-
/// Create the cache directory owner-only (`0700`) so no other local user
|
|
249
|
-
/// can plant an artifact the unsafe deserialize would trust.
|
|
250
|
-
#[cfg(unix)]
|
|
251
|
-
fn create_cache_dir(dir: &Path) -> std::io::Result<()> {
|
|
252
|
-
use std::os::unix::fs::DirBuilderExt;
|
|
253
|
-
fs::DirBuilder::new()
|
|
254
|
-
.recursive(true)
|
|
255
|
-
.mode(0o700)
|
|
256
|
-
.create(dir)
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/// The cache directory as one descriptor, once it upholds the trust the
|
|
260
|
-
/// unsafe deserialize relies on: a directory rather than a link in its
|
|
261
|
-
/// place, owned by the current effective user and writable by no one
|
|
262
|
-
/// else. Every later step goes through the descriptor, so a path swapped
|
|
263
|
-
/// after the check reaches nothing. One that fails — another user's,
|
|
264
|
-
/// under a shared `XDG_CACHE_HOME`, say — skips both disk-cache tiers.
|
|
265
|
-
#[cfg(unix)]
|
|
266
|
-
fn open_private_dir(dir: &Path) -> Option<rustix::fd::OwnedFd> {
|
|
267
|
-
use rustix::fs::{fstat, open, Mode, OFlags};
|
|
268
|
-
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
|
269
|
-
let fd = open(dir, flags, Mode::empty()).ok()?;
|
|
270
|
-
let stat = fstat(&fd).ok()?;
|
|
271
|
-
let owned = stat.st_uid == rustix::process::geteuid().as_raw();
|
|
272
|
-
(owned && stat.st_mode & 0o022 == 0).then_some(fd)
|
|
273
|
-
}
|
|
274
|
-
|
|
275
252
|
/// Live temp files are seconds old and never qualify; foreign file names
|
|
276
253
|
/// are left untouched.
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
use std::os::unix::ffi::OsStrExt;
|
|
281
|
-
use std::time::{SystemTime, UNIX_EPOCH};
|
|
282
|
-
let Ok(mut entries) = Dir::read_from(dir) else {
|
|
283
|
-
return;
|
|
284
|
-
};
|
|
285
|
-
while let Some(Ok(entry)) = entries.read() {
|
|
286
|
-
let name = entry.file_name();
|
|
287
|
-
if name.to_bytes() == keep.as_bytes() || !name.to_str().is_ok_and(is_cache_entry_name) {
|
|
254
|
+
fn prune_stale(dir: &PrivateDir, keep: &OsStr) {
|
|
255
|
+
for (name, modified) in dir.entries() {
|
|
256
|
+
if name == keep || !name.to_str().is_some_and(is_cache_entry_name) {
|
|
288
257
|
continue;
|
|
289
258
|
}
|
|
290
|
-
let stale =
|
|
291
|
-
.
|
|
292
|
-
.
|
|
293
|
-
.and_then(|secs| {
|
|
294
|
-
SystemTime::now()
|
|
295
|
-
.duration_since(UNIX_EPOCH + Duration::from_secs(secs))
|
|
296
|
-
.ok()
|
|
297
|
-
})
|
|
298
|
-
.is_some_and(|age| age > ARTIFACT_TTL);
|
|
259
|
+
let stale = SystemTime::now()
|
|
260
|
+
.duration_since(modified)
|
|
261
|
+
.is_ok_and(|age| age > ARTIFACT_TTL);
|
|
299
262
|
if stale {
|
|
300
|
-
|
|
263
|
+
dir.remove(&name);
|
|
301
264
|
}
|
|
302
265
|
}
|
|
303
266
|
}
|
|
304
267
|
|
|
305
|
-
#[cfg(unix)]
|
|
306
268
|
fn is_cache_entry_name(name: &str) -> bool {
|
|
307
269
|
name.ends_with(".cwasm") || name.contains(".tmp")
|
|
308
270
|
}
|
|
@@ -317,6 +279,7 @@ mod tests {
|
|
|
317
279
|
config
|
|
318
280
|
.module_version(ModuleVersionStrategy::Custom(version.into()))
|
|
319
281
|
.expect("a short version string is accepted");
|
|
282
|
+
catch_traps(&mut config);
|
|
320
283
|
WtEngine::new(&config).expect("engine")
|
|
321
284
|
}
|
|
322
285
|
|
|
@@ -340,15 +303,16 @@ mod tests {
|
|
|
340
303
|
// Two writers in one process take temp files in turn; each must get a
|
|
341
304
|
// file of its own rather than reopen the other's.
|
|
342
305
|
// @behavior RT-113
|
|
343
|
-
#[cfg(unix)]
|
|
344
306
|
#[test]
|
|
345
307
|
fn two_writers_of_one_artifact_never_share_a_temp_file() {
|
|
346
308
|
let root = std::env::temp_dir().join(format!("kobako-temp-{}", std::process::id()));
|
|
347
|
-
|
|
348
|
-
let dir =
|
|
309
|
+
PrivateDir::create(&root).expect("a scratch directory");
|
|
310
|
+
let dir = PrivateDir::open(&root).expect("a private directory");
|
|
349
311
|
let name = std::ffi::OsStr::new("entry.cwasm");
|
|
350
|
-
let first = create_temp(
|
|
351
|
-
let second = create_temp(
|
|
312
|
+
let first = dir.create_temp(name).map(|(path, _)| path);
|
|
313
|
+
let second = dir.create_temp(name).map(|(path, _)| path);
|
|
314
|
+
// Let go first: Windows keeps a held directory from being removed.
|
|
315
|
+
drop(dir);
|
|
352
316
|
fs::remove_dir_all(&root).expect("the scratch directory removed");
|
|
353
317
|
let (first, second) = (
|
|
354
318
|
first.expect("a temp file"),
|
|
@@ -360,6 +324,27 @@ mod tests {
|
|
|
360
324
|
);
|
|
361
325
|
}
|
|
362
326
|
|
|
327
|
+
// The in-process cache is keyed by path, so a store and a load through
|
|
328
|
+
// the disk tier alone stand for two processes.
|
|
329
|
+
// @behavior RT-412
|
|
330
|
+
#[test]
|
|
331
|
+
fn an_artifact_one_build_stores_is_the_one_the_next_build_reads() {
|
|
332
|
+
let root = std::env::temp_dir().join(format!("kobako-reread-{}", std::process::id()));
|
|
333
|
+
let artifact = root.join("kobako").join("entry.cwasm");
|
|
334
|
+
let engine = load_engine().expect("an engine");
|
|
335
|
+
let module = WtModule::new(engine, b"\0asm\x01\0\0\0").expect("an empty module compiles");
|
|
336
|
+
store_artifact(&module, &artifact);
|
|
337
|
+
let stored = artifact.exists();
|
|
338
|
+
let read = load_artifact(engine, &artifact).is_some();
|
|
339
|
+
let _ = fs::remove_dir_all(&root);
|
|
340
|
+
assert_eq!(
|
|
341
|
+
(stored, read),
|
|
342
|
+
(true, true),
|
|
343
|
+
"a Guest Binary one build compiled and cached in a private directory must be read \
|
|
344
|
+
back from that cache by the next build"
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
363
348
|
// @behavior RT-108
|
|
364
349
|
#[test]
|
|
365
350
|
fn engines_of_one_release_and_config_share_the_entry() {
|
|
@@ -17,7 +17,7 @@ use crate::exports::{self, Exports};
|
|
|
17
17
|
use crate::guest::Guest;
|
|
18
18
|
use crate::invocation::Invocation;
|
|
19
19
|
use crate::wasi::Wasi;
|
|
20
|
-
use crate::{instance_pre, trap};
|
|
20
|
+
use crate::{instance_pre, limiter, trap};
|
|
21
21
|
use kobako_runtime::dispatch::DispatchHandler;
|
|
22
22
|
use kobako_runtime::endpoint;
|
|
23
23
|
use kobako_runtime::error::{InvokeError, SetupError, Trap};
|
|
@@ -27,6 +27,9 @@ use kobako_runtime::runtime::{Entry, Runtime as ContractRuntime};
|
|
|
27
27
|
use kobako_runtime::snapshot::{Capture, Completion, Snapshot, Usage};
|
|
28
28
|
use kobako_transport::envelope::Preamble;
|
|
29
29
|
|
|
30
|
+
/// The GC heap a Store makes before its memory budget opens.
|
|
31
|
+
const GC_HEAP_PAGE: u64 = 64 * 1024;
|
|
32
|
+
|
|
30
33
|
/// The wasmtime execution unit behind one sandbox runtime.
|
|
31
34
|
pub struct Driver {
|
|
32
35
|
// Pre-linked instantiation template (import wiring, type checks,
|
|
@@ -50,12 +53,24 @@ impl Driver {
|
|
|
50
53
|
})
|
|
51
54
|
}
|
|
52
55
|
|
|
53
|
-
/// The deadline
|
|
54
|
-
/// instantiating the guest and writing its request count
|
|
55
|
-
///
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
/// The deadline, the `wall_time` bracket, and the memory budget open with
|
|
57
|
+
/// the Store, so instantiating the guest and writing its request count
|
|
58
|
+
/// against the caps as the export call does. The GC heap's first page is
|
|
59
|
+
/// made before the budget opens, a fixed cost like what the Guest Binary
|
|
60
|
+
/// declares, so a run that filled its budget can still raise and rescue.
|
|
61
|
+
/// A host with no thread or memory for it stops the run before the guest
|
|
62
|
+
/// starts, as instantiating does.
|
|
63
|
+
fn new_store(&self, wasi: Wasi) -> Result<WtStore<Invocation>, Trap> {
|
|
64
|
+
let engine = load_engine().map_err(|err| Trap::Other(err.to_string()))?;
|
|
65
|
+
let mut store = Invocation::new(wasi)
|
|
66
|
+
.into_store(engine)
|
|
67
|
+
.map_err(|err| Trap::Other(format!("failed to create the Sandbox's store: {err}")))?;
|
|
58
68
|
store.limiter(|state: &mut Invocation| -> &mut dyn ResourceLimiter { state.limiter_mut() });
|
|
69
|
+
store
|
|
70
|
+
.gc_heap_grow(GC_HEAP_PAGE)
|
|
71
|
+
.map_err(|err| Trap::Other(format!("failed to create the Sandbox's GC heap: {err}")))?;
|
|
72
|
+
let declared = limiter::declared(self.instance_pre.module());
|
|
73
|
+
store.data_mut().arm_memory_budget(declared);
|
|
59
74
|
trap::arm_deadline(&mut store, self.config.limits.timeout);
|
|
60
75
|
store.data_mut().start_wall_clock();
|
|
61
76
|
Ok(store)
|
|
@@ -68,9 +83,10 @@ impl Driver {
|
|
|
68
83
|
.instance_pre
|
|
69
84
|
.instantiate(store.as_context_mut())
|
|
70
85
|
.map_err(|e| {
|
|
71
|
-
trap::cap_trap_of(&e).unwrap_or_else(|| {
|
|
86
|
+
let failed = trap::cap_trap_of(&e).unwrap_or_else(|| {
|
|
72
87
|
Trap::Other(format!("failed to instantiate the Sandbox runtime: {e}"))
|
|
73
|
-
})
|
|
88
|
+
});
|
|
89
|
+
trap::charged_to_budget(failed, store.data_mut().limiter_mut())
|
|
74
90
|
})?;
|
|
75
91
|
let exports = Exports::resolve(&instance, store.as_context_mut());
|
|
76
92
|
store.data_mut().set_exports(exports.clone());
|
|
@@ -89,8 +105,14 @@ impl Driver {
|
|
|
89
105
|
) -> Result<wasmtime::Result<u32>, InvokeError> {
|
|
90
106
|
let exports = self.instantiate(store)?;
|
|
91
107
|
let downcall = exports::require(exports.downcall.as_ref())?;
|
|
92
|
-
let (ptr, len) =
|
|
93
|
-
|
|
108
|
+
let (ptr, len) =
|
|
109
|
+
endpoint::write_request(&mut guest_of(store), request).map_err(|err| match err {
|
|
110
|
+
InvokeError::Trap(failed) => InvokeError::Trap(trap::charged_to_budget(
|
|
111
|
+
failed,
|
|
112
|
+
store.data_mut().limiter_mut(),
|
|
113
|
+
)),
|
|
114
|
+
other => other,
|
|
115
|
+
})?;
|
|
94
116
|
// A wait for a lock the call meets ends at the same deadline the guest's
|
|
95
117
|
// code does, so another Sandbox holding it cannot keep this one past it.
|
|
96
118
|
let deadline = store.data().deadline();
|
|
@@ -101,17 +123,6 @@ impl Driver {
|
|
|
101
123
|
Ok(result)
|
|
102
124
|
}
|
|
103
125
|
|
|
104
|
-
/// The pre-initialized image's allocation is folded into the memory
|
|
105
|
-
/// baseline rather than the budget, so the budget arms only once the
|
|
106
|
-
/// image is in place.
|
|
107
|
-
fn arm_memory_budget(&self, store: &mut WtStore<Invocation>, exports: &Exports) {
|
|
108
|
-
let baseline = match exports.memory {
|
|
109
|
-
Some(m) => m.data_size(store.as_context_mut()),
|
|
110
|
-
None => 0,
|
|
111
|
-
};
|
|
112
|
-
store.data_mut().arm_memory_budget(baseline);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
126
|
/// Built the same for every `completion`: captures and usage must
|
|
116
127
|
/// survive a trap just as they do an outcome.
|
|
117
128
|
fn build_snapshot(&self, store: &WtStore<Invocation>, completion: Completion) -> Snapshot {
|
|
@@ -149,12 +160,14 @@ impl ContractRuntime for Driver {
|
|
|
149
160
|
store.data_mut().bind_on_dispatch(handler);
|
|
150
161
|
}
|
|
151
162
|
let called = self.downcall(&mut store, &endpoint::request_of(entry))?;
|
|
152
|
-
let
|
|
153
|
-
Ok(ret) =>
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
163
|
+
let read = match called {
|
|
164
|
+
Ok(ret) => endpoint::read_outcome(&mut guest_of(&mut store), ret),
|
|
165
|
+
Err(e) => Err(trap::to_trap(e)),
|
|
166
|
+
};
|
|
167
|
+
let limiter = store.data_mut().limiter_mut();
|
|
168
|
+
let completion = match read {
|
|
169
|
+
Ok(outcome) => trap::completion_of(outcome, limiter),
|
|
170
|
+
Err(failed) => Completion::Trap(trap::charged_to_budget(failed, limiter)),
|
|
158
171
|
};
|
|
159
172
|
Ok(self.build_snapshot(&store, completion))
|
|
160
173
|
}
|
|
@@ -21,6 +21,8 @@ use kobako_runtime::dispatch::DispatchHandler;
|
|
|
21
21
|
use kobako_runtime::endpoint::{Calls, ABANDONED};
|
|
22
22
|
use kobako_runtime::profile::Profile;
|
|
23
23
|
|
|
24
|
+
use wasmtime::{Engine, Store};
|
|
25
|
+
|
|
24
26
|
use crate::exports::Exports;
|
|
25
27
|
use crate::limiter::MemoryLimiter;
|
|
26
28
|
use crate::wasi::Wasi;
|
|
@@ -46,8 +48,8 @@ pub(crate) struct Invocation {
|
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
impl Invocation {
|
|
49
|
-
/// The guest's growth is charged to the budget `wasi`'s Cred
|
|
50
|
-
///
|
|
51
|
+
/// The guest's growth is charged to the budget `wasi`'s Cred carries, which
|
|
52
|
+
/// counts it against the run's `memory_limit`.
|
|
51
53
|
pub(crate) fn new(wasi: Wasi) -> Self {
|
|
52
54
|
let limiter = MemoryLimiter::new(wasi.cred().memory_budget().clone());
|
|
53
55
|
Self {
|
|
@@ -63,6 +65,19 @@ impl Invocation {
|
|
|
63
65
|
}
|
|
64
66
|
}
|
|
65
67
|
|
|
68
|
+
/// The Store the invocation's guest runs in. Each host call may have the
|
|
69
|
+
/// host copy at most the run's `memory_limit` out of the guest, or
|
|
70
|
+
/// wasmtime's default with no limit, as a one-call lift is overhead the
|
|
71
|
+
/// limit sizes.
|
|
72
|
+
pub(crate) fn into_store(self, engine: &Engine) -> wasmtime::Result<Store<Self>> {
|
|
73
|
+
let fuel = self.limiter.budget().limit();
|
|
74
|
+
let mut store = Store::try_new(engine, self)?;
|
|
75
|
+
if let Some(fuel) = fuel {
|
|
76
|
+
store.set_hostcall_fuel(fuel);
|
|
77
|
+
}
|
|
78
|
+
Ok(store)
|
|
79
|
+
}
|
|
80
|
+
|
|
66
81
|
/// The Preamble bytes the `preamble` import hands the guest; empty until
|
|
67
82
|
/// an entry sets them.
|
|
68
83
|
pub(crate) fn preamble(&self) -> Arc<[u8]> {
|
|
@@ -133,11 +148,10 @@ impl Invocation {
|
|
|
133
148
|
&mut self.limiter
|
|
134
149
|
}
|
|
135
150
|
|
|
136
|
-
///
|
|
137
|
-
///
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
self.limiter.budget().arm(baseline);
|
|
151
|
+
/// Growth past the `declared` bytes the Guest Binary's memories and
|
|
152
|
+
/// tables start with is charged from now on.
|
|
153
|
+
pub(crate) fn arm_memory_budget(&mut self, declared: usize) {
|
|
154
|
+
self.limiter.budget().arm(declared);
|
|
141
155
|
}
|
|
142
156
|
|
|
143
157
|
/// Disarmed once the export returns, so post-run host bookkeeping such
|
|
@@ -2,16 +2,41 @@
|
|
|
2
2
|
|
|
3
3
|
use std::sync::Arc;
|
|
4
4
|
|
|
5
|
-
use kobako_runtime::memcg::{GrowthCharge, MemoryBudget};
|
|
6
|
-
use wasmtime::ResourceLimiter;
|
|
5
|
+
use kobako_runtime::memcg::{GrowthCharge, MemoryBudget, MemoryLimitExceeded};
|
|
6
|
+
use wasmtime::{Module, ResourceLimiter};
|
|
7
7
|
|
|
8
|
-
///
|
|
9
|
-
///
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
/// What one wasm page of a memory takes; the Engine enables no custom page
|
|
9
|
+
/// size.
|
|
10
|
+
const PAGE: usize = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
/// What one table entry takes, a pointer in wasmtime.
|
|
13
|
+
const TABLE_ENTRY: usize = size_of::<usize>();
|
|
14
|
+
|
|
15
|
+
/// The bytes the memories and tables `module` defines start with, which
|
|
16
|
+
/// wasmtime reports as their count and the largest initial size, so a module
|
|
17
|
+
/// whose sizes differ is granted the largest for each.
|
|
18
|
+
pub(crate) fn declared(module: &Module) -> usize {
|
|
19
|
+
let required = module.resources_required();
|
|
20
|
+
let memory = to_usize(required.max_initial_memory_size).saturating_mul(PAGE);
|
|
21
|
+
let table = to_usize(required.max_initial_table_size).saturating_mul(TABLE_ENTRY);
|
|
22
|
+
(required.num_memories as usize)
|
|
23
|
+
.saturating_mul(memory)
|
|
24
|
+
.saturating_add((required.num_tables as usize).saturating_mul(table))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
fn to_usize(size: Option<u64>) -> usize {
|
|
28
|
+
size.map_or(0, |size| usize::try_from(size).unwrap_or(usize::MAX))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// wasmtime asks this as a memory, a table, or the GC heap is created or
|
|
32
|
+
/// grows; a growth past the budget fails and is kept as the refusal that a
|
|
33
|
+
/// run failing after it is attributed to. A growth it allowed may still
|
|
34
|
+
/// fail, past the memory's maximum or for want of host memory, and its
|
|
35
|
+
/// charge is then given back.
|
|
12
36
|
pub(crate) struct MemoryLimiter {
|
|
13
37
|
budget: Arc<MemoryBudget>,
|
|
14
38
|
pending: Option<GrowthCharge>,
|
|
39
|
+
refused: Option<MemoryLimitExceeded>,
|
|
15
40
|
}
|
|
16
41
|
|
|
17
42
|
impl MemoryLimiter {
|
|
@@ -19,6 +44,7 @@ impl MemoryLimiter {
|
|
|
19
44
|
Self {
|
|
20
45
|
budget,
|
|
21
46
|
pending: None,
|
|
47
|
+
refused: None,
|
|
22
48
|
}
|
|
23
49
|
}
|
|
24
50
|
|
|
@@ -26,44 +52,70 @@ impl MemoryLimiter {
|
|
|
26
52
|
pub(crate) fn budget(&self) -> &MemoryBudget {
|
|
27
53
|
&self.budget
|
|
28
54
|
}
|
|
55
|
+
|
|
56
|
+
/// The last growth the budget refused. The guest only sees the growth
|
|
57
|
+
/// fail, so this is what tells a run that then fails apart as the
|
|
58
|
+
/// budget's.
|
|
59
|
+
pub(crate) fn refused(&self) -> Option<&MemoryLimitExceeded> {
|
|
60
|
+
self.refused.as_ref()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// A growth the budget refuses fails, as `memory.grow` answers -1, rather
|
|
64
|
+
/// than ending the run, so the guest can collect what it no longer holds
|
|
65
|
+
/// and try again, as mruby does once its allocator answers none.
|
|
66
|
+
fn charge(&mut self, bytes: usize) -> wasmtime::Result<bool> {
|
|
67
|
+
match self.budget.charge_growth(bytes) {
|
|
68
|
+
Ok(charge) => {
|
|
69
|
+
self.pending = Some(charge);
|
|
70
|
+
Ok(true)
|
|
71
|
+
}
|
|
72
|
+
Err(refusal) => {
|
|
73
|
+
self.refused = Some(refusal);
|
|
74
|
+
Ok(false)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
fn give_back(&mut self) {
|
|
80
|
+
if let Some(charge) = self.pending.take() {
|
|
81
|
+
self.budget.cancel_growth(charge);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
29
84
|
}
|
|
30
85
|
|
|
31
86
|
impl ResourceLimiter for MemoryLimiter {
|
|
32
87
|
fn memory_growing(
|
|
33
88
|
&mut self,
|
|
34
|
-
|
|
89
|
+
current: usize,
|
|
35
90
|
desired: usize,
|
|
36
91
|
_maximum: Option<usize>,
|
|
37
92
|
) -> wasmtime::Result<bool> {
|
|
38
|
-
|
|
39
|
-
.budget
|
|
40
|
-
.charge_growth(desired)
|
|
41
|
-
.map_err(wasmtime::Error::new)?;
|
|
42
|
-
self.pending = Some(charge);
|
|
43
|
-
Ok(true)
|
|
93
|
+
self.charge(desired.saturating_sub(current))
|
|
44
94
|
}
|
|
45
95
|
|
|
46
96
|
fn memory_grow_failed(&mut self, _error: wasmtime::Error) -> wasmtime::Result<()> {
|
|
47
|
-
|
|
48
|
-
self.budget.cancel_growth(charge);
|
|
49
|
-
}
|
|
97
|
+
self.give_back();
|
|
50
98
|
Ok(())
|
|
51
99
|
}
|
|
52
100
|
|
|
53
101
|
fn table_growing(
|
|
54
102
|
&mut self,
|
|
55
|
-
|
|
56
|
-
|
|
103
|
+
current: usize,
|
|
104
|
+
desired: usize,
|
|
57
105
|
_maximum: Option<usize>,
|
|
58
106
|
) -> wasmtime::Result<bool> {
|
|
59
|
-
|
|
107
|
+
self.charge(desired.saturating_sub(current).saturating_mul(TABLE_ENTRY))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fn table_grow_failed(&mut self, _error: wasmtime::Error) -> wasmtime::Result<()> {
|
|
111
|
+
self.give_back();
|
|
112
|
+
Ok(())
|
|
60
113
|
}
|
|
61
114
|
}
|
|
62
115
|
|
|
63
116
|
#[cfg(test)]
|
|
64
117
|
mod tests {
|
|
65
|
-
use
|
|
66
|
-
use wasmtime::{Engine, Memory, MemoryType, Store};
|
|
118
|
+
use wasmtime::{Memory, MemoryType, Store};
|
|
67
119
|
|
|
68
120
|
use super::*;
|
|
69
121
|
|
|
@@ -77,18 +129,19 @@ mod tests {
|
|
|
77
129
|
fn a_growth_the_engine_fails_to_make_costs_the_budget_nothing() {
|
|
78
130
|
let budget = MemoryBudget::new(Some(3 * PAGE));
|
|
79
131
|
budget.arm(PAGE);
|
|
80
|
-
let
|
|
132
|
+
let engine = crate::cache::load_engine().expect("the shared Engine must be built");
|
|
133
|
+
let mut store = Store::new(engine, MemoryLimiter::new(budget.clone()));
|
|
81
134
|
store.limiter(|limiter| limiter);
|
|
82
135
|
let memory = Memory::new(&mut store, MemoryType::new(1, Some(2)))
|
|
83
136
|
.expect("a memory of one page within its maximum must be made");
|
|
84
137
|
let failed = memory.grow(&mut store, 2).is_err();
|
|
85
138
|
let peak = budget.peak();
|
|
86
|
-
let
|
|
139
|
+
let regrown = budget.charge_growth(2 * PAGE).is_ok();
|
|
87
140
|
assert_eq!(
|
|
88
|
-
(failed, peak,
|
|
141
|
+
(failed, peak, regrown),
|
|
89
142
|
(true, 2 * PAGE, true),
|
|
90
143
|
"a growth past a memory's maximum that the budget allowed must fail, give the \
|
|
91
|
-
budget back for the
|
|
144
|
+
budget back for the next growth, and stay in the peak reported"
|
|
92
145
|
);
|
|
93
146
|
}
|
|
94
147
|
}
|