Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions executor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,28 @@ name = "genvm"
version = "0.2.0"
edition = "2021"

[profile.dev.package.wasmtime]
opt-level = 2
[profile.dev.package.wasmparser]
opt-level = 2
# Wasm compilation (`genvm precompile`, and the first run of any contract) is
# unusable when cranelift is built unoptimized: a profile of `precompile`
# attributes ~80% of its samples to the crates below, so they are optimized even
# in dev while genvm's own code stays at opt-level 0. Generic code (hashbrown,
# smallvec, core) is monomorphized into whichever crate instantiates it, so
# optimizing these covers it too.
[profile.dev.package]
cranelift-assembler-x64.opt-level = 2
cranelift-bforest.opt-level = 2
cranelift-bitset.opt-level = 2
cranelift-codegen.opt-level = 2
cranelift-control.opt-level = 2
cranelift-entity.opt-level = 2
cranelift-frontend.opt-level = 2
gimli.opt-level = 2
log.opt-level = 2
object.opt-level = 2
regalloc2.opt-level = 2
wasmparser.opt-level = 2
wasmtime.opt-level = 2
wasmtime-environ.opt-level = 2
wasmtime-internal-cranelift.opt-level = 2

[profile.dev]
incremental = false
Expand Down
71 changes: 71 additions & 0 deletions executor/crates/sdk-rs/src/abi/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ pub mod __VmError {

impl OomRam {
pub const fn val(&self) -> VmError { VmError(Cow::Borrowed("OOM RAM")) }
pub const fn prefix_(&self) -> &'static str {
"OOM RAM"
}
pub const fn table(&self) -> VmError { VmError(Cow::Borrowed("OOM RAM table")) }
pub const fn memory(&self) -> VmError { VmError(Cow::Borrowed("OOM RAM memory")) }
pub const fn limit(&self) -> VmError { VmError(Cow::Borrowed("OOM RAM limit")) }
Expand All @@ -232,20 +235,29 @@ pub mod __VmError {
pub struct OomReceiptMessage;

impl OomReceiptMessage {
pub const fn prefix_(&self) -> &'static str {
"OOM receipt message"
}
pub const fn internal(&self) -> VmError { VmError(Cow::Borrowed("OOM receipt message internal")) }
pub const fn external(&self) -> VmError { VmError(Cow::Borrowed("OOM receipt message external")) }
}

pub struct OomReceipt;

impl OomReceipt {
pub const fn prefix_(&self) -> &'static str {
"OOM receipt"
}
pub const fn nondet_output(&self) -> VmError { VmError(Cow::Borrowed("OOM receipt nondet_output")) }
pub const fn message(&self) -> OomReceiptMessage { OomReceiptMessage }
}

pub struct OomFees;

impl OomFees {
pub const fn prefix_(&self) -> &'static str {
"OOM fees"
}
pub const fn internal(&self) -> VmError { VmError(Cow::Borrowed("OOM fees internal")) }
pub const fn external(&self) -> VmError { VmError(Cow::Borrowed("OOM fees external")) }
}
Expand All @@ -254,6 +266,9 @@ pub mod __VmError {

impl Oom {
pub const fn val(&self) -> VmError { VmError(Cow::Borrowed("OOM")) }
pub const fn prefix_(&self) -> &'static str {
"OOM"
}
pub const fn storage(&self) -> VmError { VmError(Cow::Borrowed("OOM storage")) }
pub const fn ram(&self) -> OomRam { OomRam }
pub const fn receipt(&self) -> OomReceipt { OomReceipt }
Expand All @@ -263,6 +278,9 @@ pub mod __VmError {
pub struct InvalidContractWasm;

impl InvalidContractWasm {
pub const fn prefix_(&self) -> &'static str {
"invalid_contract wasm"
}
pub const fn validating(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract wasm validating")) }
pub const fn linking(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract wasm linking")) }
pub const fn entrypoint(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract wasm entrypoint")) }
Expand All @@ -272,6 +290,9 @@ pub mod __VmError {

impl InvalidContract {
pub const fn val(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract")) }
pub const fn prefix_(&self) -> &'static str {
"invalid_contract"
}
pub const fn absent_runner_comment(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract absent_runner_comment")) }
pub const fn not_utf8_text(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract not_utf8_text")) }
pub const fn malformed_runner(&self) -> VmError { VmError(Cow::Borrowed("invalid_contract malformed_runner")) }
Expand All @@ -291,6 +312,7 @@ pub mod __VmError {

impl WasmTrap {
pub fn val_str(&self, v: &str) -> VmError {
debug_assert!(!v.is_empty(), "wasm_trap needs a non-empty description");
VmError(Cow::Owned(format!("wasm_trap {v}")))
}
}
Expand All @@ -299,6 +321,7 @@ pub mod __VmError {

impl Host {
pub fn val_str(&self, v: &str) -> VmError {
debug_assert!(!v.is_empty(), "host needs a non-empty description");
VmError(Cow::Owned(format!("host {v}")))
}
}
Expand All @@ -324,6 +347,54 @@ impl VmError {
pub const fn host() -> __VmError::Host { __VmError::Host }
}

#[rustfmt::skip]
impl VmError {
/// Whether `s` is a well-formed `vm_error` path.
pub fn is_valid_(s: &str) -> bool {
if matches!(s,
"timeout" |
"absent" |
"OOM" |
"OOM RAM" |
"OOM RAM table" |
"OOM RAM memory" |
"OOM RAM limit" |
"OOM storage" |
"OOM receipt nondet_output" |
"OOM receipt message internal" |
"OOM receipt message external" |
"OOM fees internal" |
"OOM fees external" |
"invalid_contract" |
"invalid_contract absent_runner_comment" |
"invalid_contract not_utf8_text" |
"invalid_contract malformed_runner" |
"invalid_contract major_mismatch" |
"invalid_contract wasm validating" |
"invalid_contract wasm linking" |
"invalid_contract wasm entrypoint"
) {
return true;
}
if let Some(rest) = s.strip_prefix("exit_code ") {
if rest.parse::<i32>().is_ok_and(|v| v.to_string() == rest) {
return true;
}
}
if let Some(rest) = s.strip_prefix("wasm_trap ") {
if !rest.is_empty() {
return true;
}
}
if let Some(rest) = s.strip_prefix("host ") {
if !rest.is_empty() {
return true;
}
}
false
Comment on lines +379 to +394

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Align dynamic constructors with VmError::is_valid_.

__VmError::WasmTrap::val_str("") and __VmError::Host::val_str("") create wasm_trap and host , but this validator rejects both values because the suffix is empty. Reject empty input in the constructors, or accept empty suffixes here. Add tests for both dynamic constructors.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@executor/crates/sdk-rs/src/abi/consts.rs` around lines 377 - 392, The dynamic
constructors for __VmError::WasmTrap and __VmError::Host must align with
VmError::is_valid_ by rejecting empty input or updating validation to accept
empty suffixes; preserve consistency between val_str and validation, and add
tests covering empty input for both constructors.

}
}

pub const EVENT_MAX_TOPICS: u32 = 4;

// EOF
74 changes: 74 additions & 0 deletions executor/crates/sdk-rs/tests/vm_error_codes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! Every `VmError` a constructor can build must be one `is_valid_` accepts:
//! the constructors are what this executor emits, `is_valid_` is what a
//! validator checks a leader-proposed code against.

use genlayer_sdk::abi::consts::VmError;

fn assert_valid(err: VmError) {
let code: String = err.into();
assert!(
VmError::is_valid_(&code),
"constructed code is rejected: {code:?}"
);
}

#[test]
fn static_codes_are_valid() {
assert_valid(VmError::timeout());
assert_valid(VmError::absent());

assert_valid(VmError::oom().val());
assert_valid(VmError::oom().storage());
assert_valid(VmError::oom().ram().val());
assert_valid(VmError::oom().ram().table());
assert_valid(VmError::oom().ram().memory());
assert_valid(VmError::oom().ram().limit());
assert_valid(VmError::oom().receipt().nondet_output());
assert_valid(VmError::oom().receipt().message().internal());
assert_valid(VmError::oom().receipt().message().external());
assert_valid(VmError::oom().fees().internal());
assert_valid(VmError::oom().fees().external());

assert_valid(VmError::invalid_contract().val());
assert_valid(VmError::invalid_contract().absent_runner_comment());
assert_valid(VmError::invalid_contract().not_utf8_text());
assert_valid(VmError::invalid_contract().malformed_runner());
assert_valid(VmError::invalid_contract().major_mismatch());
assert_valid(VmError::invalid_contract().wasm().validating());
assert_valid(VmError::invalid_contract().wasm().linking());
assert_valid(VmError::invalid_contract().wasm().entrypoint());
}

#[test]
fn exit_code_is_valid() {
assert_valid(VmError::exit_code().val_i32(0));
assert_valid(VmError::exit_code().val_i32(-1));
assert_valid(VmError::exit_code().val_i32(i32::MAX));
}

#[test]
fn wasm_trap_is_valid() {
assert_valid(VmError::wasm_trap().val_str("fault"));
assert_valid(VmError::wasm_trap().val_str("unreachable code executed"));
}

#[test]
fn host_is_valid() {
assert_valid(VmError::host().val_str("i_o_error"));
}

// ── Empty description: the one input a `$str` constructor must not take ────

#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "non-empty description")]
fn wasm_trap_rejects_an_empty_description() {
let _ = VmError::wasm_trap().val_str("");
}

#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "non-empty description")]
fn host_rejects_an_empty_description() {
let _ = VmError::host().val_str("");
}
45 changes: 43 additions & 2 deletions executor/src/exe/precompile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,48 @@ pub struct Args {
info: bool,
}

/// Writes `data` to a uniquely named sibling of `path`, then renames it onto
/// `path`.
///
/// The reader `deserialize_file`s whatever sits at the final path without
/// validating it, so a crash mid-write must not leave a truncated module there.
/// The temp name mixes pid, an in-process counter and the wall clock, so
/// concurrent writers never pick the same one; the fsync keeps the rename from
/// exposing a name whose contents are still only in page cache.
fn write_atomically(path: &std::path::Path, data: &[u8]) -> anyhow::Result<()> {
use std::io::Write as _;

static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since_epoch| since_epoch.as_nanos());
let mut tmp_name = path
.file_name()
.expect("precompiled wasm path has no file name")
.to_owned();
tmp_name.push(format!(
".tmp-{}-{}-{stamp}",
std::process::id(),
COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
));
let tmp_path = path.with_file_name(tmp_name);

let write_tmp = || -> std::io::Result<()> {
let mut file = std::fs::File::create(&tmp_path)?;
file.write_all(data)?;
file.sync_all()?;
std::fs::rename(&tmp_path, path)
};

if let Err(e) = write_tmp() {
let _ = std::fs::remove_file(&tmp_path);
return Err(e).with_context(|| format!("writing {tmp_path:?} and renaming it to {path:?}"));
}

Ok(())
}

fn compile_single_file_single_mode(
result_path: &std::path::Path,
engine: &wasmtime::Engine,
Expand All @@ -40,8 +82,7 @@ fn compile_single_file_single_mode(

let sz = precompiled.len();

std::fs::write(result_path, precompiled)
.with_context(|| format!("writing to {result_path:?}"))?;
write_atomically(result_path, &precompiled)?;

log_info!("size" = sz, result:? = result_path, engine = engine_type, runner:? = runner_path, runner_path:? = path_in_runner, duration:? = time_start.elapsed(); "wasm writing done");

Expand Down
13 changes: 12 additions & 1 deletion executor/src/rt/supervisor/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,17 @@ impl Ctx<'_, '_> {
return Ok(None);
};

// `deserialize_file` below trusts the file as native code without looking
// at the wasm it was built from, so only ids the precompiler can actually
// have written may derive a path here. `precompile` only ever emits
// artifacts for runners listed in `all.json`. Every other id must fall
// through to a normal compile instead of picking up whatever happens to
// sit at that path, notably `custom:<hash>`, which an attacker chooses
// via RegisterRunner and which parses as a plain `name:hash` pair.
if !self.supervisor.runner_cache.has_in_all(id, hash) {
return Ok(None);
}

let special_name = caching::path_in_zip_to_hash(path);
let Some(cache_dir) = &self.supervisor.wasm_mod_cache.cache_dir else {
return Ok(None);
Expand All @@ -435,7 +446,7 @@ impl Ctx<'_, '_> {
cache_dir.set_extension(caching::DET_NON_DET_PRECOMPILED_SUFFIX.non_det);
let non_det_mod = cache_dir;

if !det_mod.exists() {
if !non_det_mod.exists() {
return Ok(None);
}

Expand Down
62 changes: 62 additions & 0 deletions executor/tests/precompile_lookup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//! The precompile cache is read with `Module::deserialize_file`, which trusts the
//! file as native code. Only runners the precompiler actually writes artifacts
//! for, the ones listed in `all.json`, may derive a path into it.

use genvm::runners;

const HASH: &str = "cnn3rjeozkptmzmzt4ymzznvkqfdedcvpapscmyt6r6cyzjrzsgq";

fn unique_dir(tag: &str) -> std::path::PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("genvm-{tag}-{}-{n}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
path
}

/// A registry holding exactly one builtin runner, `py-genlayer:HASH`.
fn registry_with_one_builtin() -> (std::path::PathBuf, runners::cache::Reader) {
let root = unique_dir("registry");
let runners_dir = root.join("runners");
std::fs::create_dir_all(&runners_dir).unwrap();
std::fs::write(
root.join("all.json"),
format!(r#"{{"py-genlayer": ["{HASH}"]}}"#),
)
.unwrap();

let reader = runners::cache::Reader::new(&runners_dir, &root, false).unwrap();
(root, reader)
}

#[test]
fn verify_runner_alone_accepts_custom_ids() {
// This is why the registry lookup exists: `custom:<hash>`, an id an attacker
// picks via RegisterRunner, is a well-formed `name:hash` pair, so the charset
// check waves it through. `chain:` and `contract` are excluded only
// incidentally, by their colon count.
assert_eq!(
runners::verify_runner(&format!("custom:{HASH}")),
Some(("custom", HASH)),
);
}

#[test]
fn custom_runner_is_not_in_the_registry() {
let (root, reader) = registry_with_one_builtin();

assert!(
reader.has_in_all("py-genlayer", HASH),
"the builtin the registry lists must be found",
);
assert!(
!reader.has_in_all("custom", HASH),
"a custom: runner must never resolve a precompiled artifact",
);
assert!(
!reader.has_in_all("py-genlayer", "not-the-listed-hash"),
"a builtin name with an unlisted hash must not resolve either",
);

std::fs::remove_dir_all(&root).unwrap();
}