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

Store and restore hash from a compiled module #4654

Merged
merged 18 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ tracing = { version = "0.1" }
wat = { version = "=1.0.71", optional = true }
rustc-demangle = "0.1"
shared-buffer = { workspace = true }
xxhash-rust = { version = "0.8.10", features = ["xxh64"] }
maminrayej marked this conversation as resolved.
Show resolved Hide resolved

# Dependencies and Development Dependencies for `sys`.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
Expand Down
9 changes: 7 additions & 2 deletions lib/api/src/js/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use tracing::{debug, warn};
use wasm_bindgen::JsValue;
use wasmer_types::{
CompileError, DeserializeError, ExportsIterator, ExternType, FunctionType, GlobalType,
ImportsIterator, MemoryType, ModuleInfo, Mutability, Pages, SerializeError, TableType, Type,
ImportsIterator, MemoryType, ModuleHash, ModuleInfo, Mutability, Pages, SerializeError,
TableType, Type,
};

/// WebAssembly in the browser doesn't yet output the descriptor/types
Expand Down Expand Up @@ -115,7 +116,7 @@ impl Module {
type_hints,
name,
#[cfg(feature = "js-serializable-module")]
raw_bytes: Some(binary),
raw_bytes: Some(binary.clone()),
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down Expand Up @@ -210,6 +211,10 @@ impl Module {
self.name.as_ref().map(|s| s.as_ref())
}

pub fn hash(&self) -> Option<ModuleHash> {
None
}

maminrayej marked this conversation as resolved.
Show resolved Hide resolved
pub fn serialize(&self) -> Result<Bytes, SerializeError> {
#[cfg(feature = "js-serializable-module")]
return self.raw_bytes.clone().ok_or(SerializeError::Generic(
Expand Down
8 changes: 7 additions & 1 deletion lib/api/src/jsc/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use bytes::Bytes;
use rusty_jsc::{JSObject, JSString, JSValue};
use std::path::Path;
use tracing::{debug, warn};
use wasmer_types::ModuleHash;
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
use wasmer_types::{
CompileError, DeserializeError, ExportsIterator, ExternType, FunctionType, GlobalType,
ImportsIterator, MemoryType, ModuleInfo, Mutability, Pages, SerializeError, TableType, Type,
Expand Down Expand Up @@ -67,8 +68,9 @@ impl Module {
///
pub(crate) unsafe fn from_js_module(module: JSObject, binary: impl IntoBytes) -> Self {
let binary = binary.into_bytes();

// The module is now validated, so we can safely parse it's types
let info = crate::module_info_polyfill::translate_module(&binary[..])
let mut info = crate::module_info_polyfill::translate_module(&binary[..])
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
.unwrap()
.info;

Expand Down Expand Up @@ -175,6 +177,10 @@ impl Module {
self.name.as_ref().map(|s| s.as_ref())
}

pub fn hash(&self) -> Option<ModuleHash> {
self.info.hash
}

maminrayej marked this conversation as resolved.
Show resolved Hide resolved
pub fn serialize(&self) -> Result<Bytes, SerializeError> {
return self.raw_bytes.clone().ok_or(SerializeError::Generic(
"Not able to serialize module".to_string(),
Expand Down
6 changes: 6 additions & 0 deletions lib/api/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use wasmer_types::ModuleHash;
maminrayej marked this conversation as resolved.
Show resolved Hide resolved

use crate::engine::AsEngineRef;
use thiserror::Error;
Expand Down Expand Up @@ -366,6 +367,11 @@ impl Module {
self.0.name()
}

/// Returns the xxhash module hash
pub fn hash(&self) -> Option<ModuleHash> {
self.0.hash()
}

/// Sets the name of the current module.
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
/// This is normally useful for stacktraces and debugging.
///
Expand Down
4 changes: 3 additions & 1 deletion lib/api/src/module_info_polyfill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::vec::Vec;
use wasmer_types::entity::EntityRef;
use wasmer_types::{
ExportIndex, FunctionIndex, FunctionType, GlobalIndex, GlobalType, ImportIndex, MemoryIndex,
MemoryType, ModuleInfo, Pages, SignatureIndex, TableIndex, TableType, Type,
MemoryType, ModuleHash, ModuleInfo, Pages, SignatureIndex, TableIndex, TableType, Type,
};

use wasmparser::{
Expand Down Expand Up @@ -253,6 +253,8 @@ fn transform_err(err: BinaryReaderError) -> String {
pub fn translate_module<'data>(data: &'data [u8]) -> WasmResult<ModuleInfoPolyfill> {
let mut module_info: ModuleInfoPolyfill = Default::default();

module_info.info.hash = Some(ModuleHash::xxhash(data));

maminrayej marked this conversation as resolved.
Show resolved Hide resolved
for payload in Parser::new(0).parse_all(data) {
match payload.map_err(transform_err)? {
Payload::TypeSection(types) => {
Expand Down
7 changes: 6 additions & 1 deletion lib/api/src/sys/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use std::sync::Arc;
use bytes::Bytes;
use wasmer_compiler::{Artifact, ArtifactCreate};
use wasmer_types::{
CompileError, DeserializeError, ExportsIterator, ImportsIterator, ModuleInfo, SerializeError,
CompileError, DeserializeError, ExportsIterator, ImportsIterator, ModuleHash, ModuleInfo,
SerializeError,
};
use wasmer_types::{ExportType, ImportType};

Expand Down Expand Up @@ -174,6 +175,10 @@ impl Module {
self.info().name.as_deref()
}

pub(crate) fn hash(&self) -> Option<ModuleHash> {
self.info().hash
}

maminrayej marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) fn set_name(&mut self, name: &str) -> bool {
Arc::get_mut(&mut self.artifact).map_or(false, |artifact| {
artifact.set_module_info_name(name.to_string())
Expand Down
12 changes: 5 additions & 7 deletions lib/cli/src/commands/run/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use wasmer::{
use wasmer_compiler::ArtifactBuild;
use wasmer_config::package::PackageSource as PackageSpecifier;
use wasmer_registry::{wasmer_env::WasmerEnv, Package};
use wasmer_types::ModuleHash;
#[cfg(feature = "journal")]
use wasmer_wasix::journal::{LogFileJournal, SnapshotTrigger};
use wasmer_wasix::{
Expand All @@ -43,9 +44,7 @@ use wasmer_wasix::{
MappedCommand, MappedDirectory, Runner,
},
runtime::{
module_cache::{CacheError, ModuleHash},
package_loader::PackageLoader,
resolver::QueryError,
module_cache::CacheError, package_loader::PackageLoader, resolver::QueryError,
task_manager::VirtualTaskManagerExt,
},
Runtime, WasiError,
Expand Down Expand Up @@ -712,10 +711,9 @@ impl ExecutableTarget {
let engine = runtime.engine();
pb.set_message("Deserializing pre-compiled WebAssembly module");
let module = unsafe { Module::deserialize_from_file(&engine, path)? };
let module_hash = {
let wasm = std::fs::read(path)?;
ModuleHash::xxhash(wasm)
};

// FIXME: what if the artifact does not have the hash
let module_hash = module.hash().unwrap_or(ModuleHash::XXHash([0u8; 8]));
maminrayej marked this conversation as resolved.
Show resolved Hide resolved

Ok(ExecutableTarget::WebAssembly {
module,
Expand Down
3 changes: 2 additions & 1 deletion lib/cli/src/commands/run/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use virtual_fs::{DeviceFile, FileSystem, PassthruFileSystem, RootFileSystemBuild
use wasmer::{Engine, Function, Instance, Memory32, Memory64, Module, RuntimeError, Store, Value};
use wasmer_config::package::PackageSource as PackageSpecifier;
use wasmer_registry::wasmer_env::WasmerEnv;
use wasmer_types::ModuleHash;
#[cfg(feature = "journal")]
use wasmer_wasix::journal::{LogFileJournal, SnapshotTrigger};
use wasmer_wasix::{
Expand All @@ -27,7 +28,7 @@ use wasmer_wasix::{
rewind_ext,
runners::{MappedCommand, MappedDirectory},
runtime::{
module_cache::{FileSystemCache, ModuleCache, ModuleHash},
module_cache::{FileSystemCache, ModuleCache},
package_loader::{BuiltinPackageLoader, PackageLoader},
resolver::{FileSystemSource, InMemorySource, MultiSource, Source, WapmSource, WebSource},
task_manager::{
Expand Down
1 change: 1 addition & 0 deletions lib/compiler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ serde = { version = "1.0", features = ["derive"], optional = true }
thiserror = "1.0"
serde_bytes = { version = "0.11", optional = true }
smallvec = "1.6"
xxhash-rust = { version = "0.8.10", features = ["xxh64"] }

backtrace = "0.3"
memmap2 = "0.5"
Expand Down
5 changes: 4 additions & 1 deletion lib/compiler/src/translator/environ.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ use crate::wasmparser::{Operator, ValType};
use std::convert::{TryFrom, TryInto};
use std::ops::Range;
use wasmer_types::entity::PrimaryMap;
use wasmer_types::FunctionType;
use wasmer_types::WasmResult;
use wasmer_types::{
CustomSectionIndex, DataIndex, DataInitializer, DataInitializerLocation, ElemIndex,
ExportIndex, FunctionIndex, GlobalIndex, GlobalInit, GlobalType, ImportIndex,
LocalFunctionIndex, MemoryIndex, MemoryType, ModuleInfo, SignatureIndex, TableIndex,
TableInitializer, TableType,
};
use wasmer_types::{FunctionType, ModuleHash};

/// Contains function data: bytecode and its offset in the module.
#[derive(Hash)]
Expand Down Expand Up @@ -89,6 +89,9 @@ impl<'data> ModuleEnvironment<'data> {
assert!(self.module_translation_state.is_none());
let module_translation_state = translate_module(data, &mut self)?;
self.module_translation_state = Some(module_translation_state);

self.module.hash = Some(ModuleHash::xxhash(data));
maminrayej marked this conversation as resolved.
Show resolved Hide resolved

Ok(self)
}

Expand Down
4 changes: 3 additions & 1 deletion lib/compiler/src/translator/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use super::sections::{
parse_start_section, parse_table_section, parse_type_section,
};
use super::state::ModuleTranslationState;
use wasmer_types::WasmResult;
use wasmer_types::{ModuleHash, WasmResult};
use wasmparser::{NameSectionReader, Parser, Payload};

/// Translate a sequence of bytes forming a valid Wasm binary into a
Expand All @@ -22,6 +22,8 @@ pub fn translate_module<'data>(
) -> WasmResult<ModuleTranslationState> {
let mut module_translation_state = ModuleTranslationState::new();

environ.module.hash = Some(ModuleHash::xxhash(data));

maminrayej marked this conversation as resolved.
Show resolved Hide resolved
for payload in Parser::new(0).parse_all(data) {
match payload.map_err(from_binaryreadererror_wasmerror)? {
Payload::Version { .. } | Payload::End { .. } => {}
Expand Down
11 changes: 11 additions & 0 deletions lib/types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ enum-iterator = "0.7.0"
target-lexicon = { version = "0.12.2", default-features = false }
enumset.workspace = true
bytecheck = "0.6.8"
rand = "0.8"
maminrayej marked this conversation as resolved.
Show resolved Hide resolved
webc = { workspace = true }
xxhash-rust = { version = "0.8.8", features = ["xxh64"] }
sha2 = { version = "0.10" }
hex = { version = "^0.4" }

# `rand` uses `getrandom` transitively, and to be able to
# compile the project for `js`, we need to enable this feature
[dependencies.getrandom]
version = "*"
features = ["js"]

[dev-dependencies]
memoffset.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion lib/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ pub use crate::initializers::{
OwnedDataInitializer, TableInitializer,
};
pub use crate::memory::{Memory32, Memory64, MemorySize};
pub use crate::module::{ExportsIterator, ImportKey, ImportsIterator, ModuleInfo};
pub use crate::module::{ExportsIterator, ImportKey, ImportsIterator, ModuleHash, ModuleInfo};
pub use crate::units::{
Bytes, PageCountOutOfRange, Pages, WASM_MAX_PAGES, WASM_MIN_PAGES, WASM_PAGE_SIZE,
};
Expand Down
Loading
Loading