Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an API to detect precompiled modules/components #6832

Merged
merged 1 commit into from
Aug 10, 2023
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
29 changes: 29 additions & 0 deletions crates/wasmtime/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,26 @@ impl Engine {
code.publish()?;
Ok(Arc::new(code))
}

/// Detects whether the bytes provided are a precompiled object produced by
/// Wasmtime.
///
/// This function will inspect the header of `bytes` to determine if it
/// looks like a precompiled core wasm module or a precompiled component.
/// This does not validate the full structure or guarantee that
/// deserialization will succeed, instead it helps higher-levels of the
/// stack make a decision about what to do next when presented with the
/// `bytes` as an input module.
///
/// If the `bytes` looks like a precompiled object previously produced by
/// [`Module::serialize`](crate::Module::serialize),
/// [`Component::serialize`](crate::component::Component::serialize),
/// [`Engine::precompile_module`], or [`Engine::precompile_component`], then
/// this will return `Some(...)` indicating so. Otherwise `None` is
/// returned.
pub fn detect_precompiled(&self, bytes: &[u8]) -> Option<Precompiled> {
serialization::detect_precompiled(bytes)
}
}

impl Default for Engine {
Expand All @@ -637,6 +657,15 @@ impl Default for Engine {
}
}

/// Return value from the [`Engine::detect_precompiled`] API.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Precompiled {
/// The input bytes look like a precompiled core wasm module.
Module,
/// The input bytes look like a precompiled wasm component.
Component,
}

#[cfg(test)]
mod tests {
use std::{
Expand Down
19 changes: 18 additions & 1 deletion crates/wasmtime/src/engine/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
//! other random ELF files, as well as provide better error messages for
//! using wasmtime artifacts across versions.

use crate::{Engine, ModuleVersionStrategy};
use crate::{Engine, ModuleVersionStrategy, Precompiled};
use anyhow::{anyhow, bail, Context, Result};
use object::write::{Object, StandardSegment};
use object::{File, FileFlags, Object as _, ObjectSection, SectionKind};
Expand Down Expand Up @@ -145,6 +145,23 @@ pub fn check_compatible(engine: &Engine, mmap: &MmapVec, expected: ObjectKind) -
bincode::deserialize::<Metadata>(data)?.check_compatible(engine)
}

pub fn detect_precompiled(bytes: &[u8]) -> Option<Precompiled> {
let obj = File::parse(bytes).ok()?;
match obj.flags() {
FileFlags::Elf {
os_abi: obj::ELFOSABI_WASMTIME,
abi_version: 0,
e_flags: obj::EF_WASMTIME_MODULE,
} => Some(Precompiled::Module),
FileFlags::Elf {
os_abi: obj::ELFOSABI_WASMTIME,
abi_version: 0,
e_flags: obj::EF_WASMTIME_COMPONENT,
} => Some(Precompiled::Component),
_ => None,
}
}

#[derive(Serialize, Deserialize)]
struct Metadata {
target: String,
Expand Down
16 changes: 15 additions & 1 deletion tests/all/component_model/aot.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::Result;
use wasmtime::component::{Component, Linker};
use wasmtime::{Module, Store};
use wasmtime::{Module, Precompiled, Store};

#[test]
fn module_component_mismatch() -> Result<()> {
Expand Down Expand Up @@ -119,3 +119,17 @@ fn usable_exported_modules() -> Result<()> {
core_linker.instantiate(&mut store, &module)?;
Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn detect_precompiled() -> Result<()> {
let engine = super::engine();
let buffer = Component::new(&engine, "(component)")?.serialize()?;
assert_eq!(engine.detect_precompiled(&[]), None);
assert_eq!(engine.detect_precompiled(&buffer[..5]), None);
assert_eq!(
engine.detect_precompiled(&buffer),
Some(Precompiled::Component)
);
Ok(())
}
17 changes: 17 additions & 0 deletions tests/all/module_serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,20 @@ fn deserialize_from_serialized() -> Result<()> {
assert!(buffer1 == buffer2);
Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn detect_precompiled() -> Result<()> {
let engine = Engine::default();
let buffer = serialize(
&engine,
"(module (func (export \"run\") (result i32) i32.const 42))",
)?;
assert_eq!(engine.detect_precompiled(&[]), None);
assert_eq!(engine.detect_precompiled(&buffer[..5]), None);
assert_eq!(
engine.detect_precompiled(&buffer),
Some(Precompiled::Module)
);
Ok(())
}