Skip to content

Commit 75404ec

Browse files
authored
wasip3: Limit randomness instead of trapping (#12794)
This updates the behavior of the randomness-generating interfaces in WASIp3 to account for recent spec changes, notably the ability for the guest to receive less random bytes than requested to limit allocations the host is forced to do. cc WebAssembly/WASI#901
1 parent 356c6f8 commit 75404ec

2 files changed

Lines changed: 11 additions & 21 deletions

File tree

crates/wasi/src/p3/random/host.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,12 @@ use crate::p3::bindings::random::{insecure, insecure_seed, random};
22
use crate::random::WasiRandomCtx;
33
use cap_rand::Rng;
44
use cap_rand::distributions::Standard;
5-
use wasmtime::bail;
65

76
impl random::Host for WasiRandomCtx {
87
fn get_random_bytes(&mut self, len: u64) -> wasmtime::Result<Vec<u8>> {
9-
if len > self.max_size {
10-
bail!("requested len {len:?} exceeds limit {}", self.max_size);
11-
}
128
Ok((&mut self.random)
139
.sample_iter(Standard)
14-
.take(len as usize)
10+
.take(len.min(self.max_size) as usize)
1511
.collect())
1612
}
1713

@@ -22,12 +18,9 @@ impl random::Host for WasiRandomCtx {
2218

2319
impl insecure::Host for WasiRandomCtx {
2420
fn get_insecure_random_bytes(&mut self, len: u64) -> wasmtime::Result<Vec<u8>> {
25-
if len > self.max_size {
26-
bail!("requested len {len:?} exceeds limit {}", self.max_size);
27-
}
2821
Ok((&mut self.insecure_random)
2922
.sample_iter(Standard)
30-
.take(len as usize)
23+
.take(len.min(self.max_size) as usize)
3124
.collect())
3225
}
3326

tests/all/cli_tests.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2844,18 +2844,15 @@ start a print 1234
28442844

28452845
for rand in ["random", "insecure"] {
28462846
run_wasmtime(&["run", "-Sp3", "-Wcomponent-model-async", c, rand, "256"])?;
2847-
assert!(
2848-
run_wasmtime(&[
2849-
"run",
2850-
"-Sp3",
2851-
"-Wcomponent-model-async",
2852-
"-Smax-random-size=255",
2853-
c,
2854-
rand,
2855-
"256"
2856-
])
2857-
.is_err()
2858-
);
2847+
run_wasmtime(&[
2848+
"run",
2849+
"-Sp3",
2850+
"-Wcomponent-model-async",
2851+
"-Smax-random-size=255",
2852+
c,
2853+
rand,
2854+
"256",
2855+
])?;
28592856
}
28602857

28612858
Ok(())

0 commit comments

Comments
 (0)