Skip to content

Commit

Permalink
Add Engine::detect_precompiled_file() (bytecodealliance#6937)
Browse files Browse the repository at this point in the history
This is handy for users of `deserialize_file()` to determine which version to call.
  • Loading branch information
acfoltzer authored and eduardomourar committed Sep 6, 2023
1 parent 1454387 commit b2e68fe
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 6 additions & 1 deletion crates/wasmtime/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,12 @@ impl Engine {
/// this will return `Some(...)` indicating so. Otherwise `None` is
/// returned.
pub fn detect_precompiled(&self, bytes: &[u8]) -> Option<Precompiled> {
serialization::detect_precompiled(bytes)
serialization::detect_precompiled_bytes(bytes)
}

/// Like [`Engine::detect_precompiled`], but performs the detection on a file.
pub fn detect_precompiled_file(&self, path: impl AsRef<Path>) -> Result<Option<Precompiled>> {
serialization::detect_precompiled_file(path)
}
}

Expand Down
15 changes: 13 additions & 2 deletions crates/wasmtime/src/engine/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ 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()?;
fn detect_precompiled<'data, R: object::ReadRef<'data>>(
obj: File<'data, R>,
) -> Option<Precompiled> {
match obj.flags() {
FileFlags::Elf {
os_abi: obj::ELFOSABI_WASMTIME,
Expand All @@ -162,6 +163,16 @@ pub fn detect_precompiled(bytes: &[u8]) -> Option<Precompiled> {
}
}

pub fn detect_precompiled_bytes(bytes: &[u8]) -> Option<Precompiled> {
detect_precompiled(File::parse(bytes).ok()?)
}

pub fn detect_precompiled_file(path: impl AsRef<std::path::Path>) -> Result<Option<Precompiled>> {
let read_cache = object::ReadCache::new(std::fs::File::open(path)?);
let obj = File::parse(&read_cache)?;
Ok(detect_precompiled(obj))
}

#[derive(Serialize, Deserialize)]
struct Metadata {
target: String,
Expand Down

0 comments on commit b2e68fe

Please sign in to comment.