Remove Artifact trait

In favor of using UniversalArtifact everywhere
This commit is contained in:
Manos Pitsidianakis
2022-07-01 16:25:25 +03:00
parent 37773f29d7
commit 187d2e6364
44 changed files with 361 additions and 294 deletions

3
Cargo.lock generated
View File

@@ -2954,7 +2954,6 @@ dependencies = [
"serde", "serde",
"serde_bytes", "serde_bytes",
"smallvec", "smallvec",
"target-lexicon 0.12.4",
"thiserror", "thiserror",
"wasmer-types", "wasmer-types",
"wasmer-vm", "wasmer-vm",
@@ -3105,11 +3104,13 @@ name = "wasmer-types"
version = "2.3.0" version = "2.3.0"
dependencies = [ dependencies = [
"enum-iterator", "enum-iterator",
"enumset",
"indexmap", "indexmap",
"more-asserts", "more-asserts",
"rkyv", "rkyv",
"serde", "serde",
"serde_bytes", "serde_bytes",
"target-lexicon 0.12.4",
"thiserror", "thiserror",
] ]

View File

@@ -21,8 +21,8 @@
use std::str::FromStr; use std::str::FromStr;
use wasmer::{wat2wasm, Module, RuntimeError, Store}; use wasmer::{wat2wasm, Module, RuntimeError, Store};
use wasmer_compiler::Universal; use wasmer_compiler::Universal;
use wasmer_compiler::{CpuFeature, Target, Triple};
use wasmer_compiler_cranelift::Cranelift; use wasmer_compiler_cranelift::Cranelift;
use wasmer_types::{CpuFeature, Target, Triple};
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
// Let's declare the Wasm module with the text representation. // Let's declare the Wasm module with the text representation.

View File

@@ -15,8 +15,8 @@
use std::path::Path; use std::path::Path;
use std::str::FromStr; use std::str::FromStr;
use wasmer::{wat2wasm, Module, RuntimeError, Store}; use wasmer::{wat2wasm, Module, RuntimeError, Store};
use wasmer_compiler::{CpuFeature, Target, Triple};
use wasmer_compiler_cranelift::Cranelift; use wasmer_compiler_cranelift::Cranelift;
use wasmer_types::{CpuFeature, Target, Triple};
/* /*
use wasmer_engine_dylib::Dylib; use wasmer_engine_dylib::Dylib;
*/ */

View File

@@ -36,14 +36,12 @@ pub use target_lexicon::{Architecture, CallingConvention, OperatingSystem, Tripl
pub use wasmer_compiler::{ pub use wasmer_compiler::{
wasmparser, CompilerConfig, FunctionMiddleware, MiddlewareReaderState, ModuleMiddleware, wasmparser, CompilerConfig, FunctionMiddleware, MiddlewareReaderState, ModuleMiddleware,
}; };
pub use wasmer_compiler::{ pub use wasmer_compiler::{Engine, Features, FrameInfo, LinkError, RuntimeError, Tunables};
CpuFeature, Engine, Features, FrameInfo, LinkError, RuntimeError, Target, Tunables,
};
pub use wasmer_derive::ValueType; pub use wasmer_derive::ValueType;
pub use wasmer_types::is_wasm; pub use wasmer_types::is_wasm;
pub use wasmer_types::{ pub use wasmer_types::{
ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, CpuFeature, ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType,
TableType, Type, Mutability, TableType, Target, Type,
}; };
pub use wasmer_types::{ pub use wasmer_types::{

View File

@@ -6,7 +6,8 @@ use std::io;
use std::path::Path; use std::path::Path;
use std::sync::Arc; use std::sync::Arc;
use thiserror::Error; use thiserror::Error;
use wasmer_compiler::Artifact; use wasmer_compiler::ArtifactCreate;
use wasmer_compiler::UniversalArtifact;
#[cfg(feature = "wat")] #[cfg(feature = "wat")]
use wasmer_types::WasmError; use wasmer_types::WasmError;
use wasmer_types::{ use wasmer_types::{
@@ -49,7 +50,7 @@ pub struct Module {
// //
// In the future, this code should be refactored to properly describe the // In the future, this code should be refactored to properly describe the
// ownership of the code and its metadata. // ownership of the code and its metadata.
artifact: Arc<dyn Artifact>, artifact: Arc<UniversalArtifact>,
module_info: Arc<ModuleInfo>, module_info: Arc<ModuleInfo>,
} }
@@ -280,7 +281,7 @@ impl Module {
Ok(Self::from_artifact(artifact)) Ok(Self::from_artifact(artifact))
} }
fn from_artifact(artifact: Arc<dyn Artifact>) -> Self { fn from_artifact(artifact: Arc<UniversalArtifact>) -> Self {
Self { Self {
module_info: Arc::new(artifact.create_module_info()), module_info: Arc::new(artifact.create_module_info()),
artifact, artifact,
@@ -455,7 +456,7 @@ impl Module {
/// this functionality is required for some core functionality though, like /// this functionality is required for some core functionality though, like
/// the object file engine. /// the object file engine.
#[doc(hidden)] #[doc(hidden)]
pub fn artifact(&self) -> &Arc<dyn Artifact> { pub fn artifact(&self) -> &Arc<UniversalArtifact> {
&self.artifact &self.artifact
} }
} }

View File

@@ -1,7 +1,7 @@
use crate::sys::{MemoryType, Pages, TableType}; use crate::sys::{MemoryType, Pages, TableType};
use std::ptr::NonNull; use std::ptr::NonNull;
use target_lexicon::PointerWidth; use wasmer_compiler::Tunables;
use wasmer_compiler::{Target, Tunables}; use wasmer_types::{PointerWidth, Target};
use wasmer_vm::MemoryError; use wasmer_vm::MemoryError;
use wasmer_vm::{ use wasmer_vm::{
MemoryStyle, TableStyle, VMMemory, VMMemoryDefinition, VMTable, VMTableDefinition, MemoryStyle, TableStyle, VMMemory, VMMemoryDefinition, VMTable, VMTableDefinition,

View File

@@ -3,10 +3,12 @@ use crate::warning;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use structopt::StructOpt; use structopt::StructOpt;
use wasmer_compiler::ModuleEnvironment;
use wasmer_compiler::{ArtifactCreate, UniversalArtifactBuild}; use wasmer_compiler::{ArtifactCreate, UniversalArtifactBuild};
use wasmer_compiler::{CpuFeature, ModuleEnvironment, Target, Triple};
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
use wasmer_types::{CompileError, MemoryIndex, MemoryStyle, TableIndex, TableStyle}; use wasmer_types::{
CompileError, CpuFeature, MemoryIndex, MemoryStyle, TableIndex, TableStyle, Target, Triple,
};
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
/// The options for the `wasmer compile` subcommand /// The options for the `wasmer compile` subcommand

View File

@@ -3,8 +3,7 @@ use anyhow::{bail, Context, Result};
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
use structopt::StructOpt; use structopt::StructOpt;
use wasmer_compiler::{CpuFeature, Target, Triple}; use wasmer_types::{is_wasm, CpuFeature, Target, Triple};
use wasmer_types::is_wasm;
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
/// The options for the `wasmer validate` subcommand /// The options for the `wasmer validate` subcommand

View File

@@ -8,8 +8,8 @@ use std::string::ToString;
use std::sync::Arc; use std::sync::Arc;
use structopt::StructOpt; use structopt::StructOpt;
use wasmer_compiler::UniversalEngineBuilder; use wasmer_compiler::UniversalEngineBuilder;
use wasmer_compiler::{CompilerConfig, Features, PointerWidth, Target}; use wasmer_compiler::{CompilerConfig, Features};
use wasmer_types::{MemoryStyle, MemoryType, Pages, TableStyle, TableType}; use wasmer_types::{MemoryStyle, MemoryType, Pages, PointerWidth, TableStyle, TableType, Target};
/// Minimul Subset of Tunable parameters for WebAssembly compilation. /// Minimul Subset of Tunable parameters for WebAssembly compilation.
#[derive(Clone)] #[derive(Clone)]

View File

@@ -21,18 +21,17 @@ use gimli::write::{Address, EhFrame, FrameTable};
#[cfg(feature = "rayon")] #[cfg(feature = "rayon")]
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use std::sync::Arc; use std::sync::Arc;
use wasmer_compiler::{CallingConvention, ModuleTranslationState, Target};
use wasmer_compiler::{ use wasmer_compiler::{
Compiler, FunctionBinaryReader, FunctionBodyData, MiddlewareBinaryReader, ModuleMiddleware, Compiler, FunctionBinaryReader, FunctionBodyData, MiddlewareBinaryReader, ModuleMiddleware,
ModuleMiddlewareChain, ModuleMiddlewareChain, ModuleTranslationState,
}; };
use wasmer_types::entity::{EntityRef, PrimaryMap}; use wasmer_types::entity::{EntityRef, PrimaryMap};
use wasmer_types::{ use wasmer_types::{
Compilation, CompileModuleInfo, CompiledFunction, CompiledFunctionFrameInfo, CallingConvention, Compilation, CompileError, CompileModuleInfo, CompiledFunction,
CompiledFunctionUnwindInfo, Dwarf, FunctionBody, TrapInformation, CompiledFunctionFrameInfo, CompiledFunctionUnwindInfo, Dwarf, FunctionBody, FunctionIndex,
LocalFunctionIndex, ModuleInfo, Relocation, RelocationTarget, SectionIndex, SignatureIndex,
Target, TrapCode, TrapInformation,
}; };
use wasmer_types::{CompileError, FunctionIndex, LocalFunctionIndex, ModuleInfo, SignatureIndex};
use wasmer_types::{Relocation, RelocationTarget, SectionIndex, TrapCode};
/// A compiler that compiles a WebAssembly module with Cranelift, translating the Wasm to Cranelift IR, /// A compiler that compiles a WebAssembly module with Cranelift, translating the Wasm to Cranelift IR,
/// optimizing it and then translating to assembly. /// optimizing it and then translating to assembly.

View File

@@ -3,9 +3,8 @@ use cranelift_codegen::isa::{lookup, TargetIsa};
use cranelift_codegen::settings::{self, Configurable}; use cranelift_codegen::settings::{self, Configurable};
use cranelift_codegen::CodegenResult; use cranelift_codegen::CodegenResult;
use std::sync::Arc; use std::sync::Arc;
use wasmer_compiler::{ use wasmer_compiler::{Compiler, CompilerConfig, ModuleMiddleware};
Architecture, Compiler, CompilerConfig, CpuFeature, ModuleMiddleware, Target, use wasmer_types::{Architecture, CpuFeature, Target};
};
// Runtime Environment // Runtime Environment

View File

@@ -1,11 +1,10 @@
use gimli::write::{Address, EndianVec, Result, Writer}; use gimli::write::{Address, EndianVec, Result, Writer};
use gimli::{RunTimeEndian, SectionId}; use gimli::{RunTimeEndian, SectionId};
use wasmer_compiler::Endianness;
use wasmer_types::entity::EntityRef; use wasmer_types::entity::EntityRef;
use wasmer_types::LocalFunctionIndex; use wasmer_types::LocalFunctionIndex;
use wasmer_types::{ use wasmer_types::{
CustomSection, CustomSectionProtection, Relocation, RelocationKind, RelocationTarget, CustomSection, CustomSectionProtection, Endianness, Relocation, RelocationKind,
SectionBody, RelocationTarget, SectionBody,
}; };
#[derive(Clone, Debug)] #[derive(Clone, Debug)]

View File

@@ -12,12 +12,12 @@ use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIter
use std::sync::Arc; use std::sync::Arc;
use wasmer_compiler::{ use wasmer_compiler::{
Compiler, FunctionBodyData, ModuleMiddleware, ModuleTranslationState, Symbol, SymbolRegistry, Compiler, FunctionBodyData, ModuleMiddleware, ModuleTranslationState, Symbol, SymbolRegistry,
Target,
}; };
use wasmer_types::entity::{EntityRef, PrimaryMap}; use wasmer_types::entity::{EntityRef, PrimaryMap};
use wasmer_types::{ use wasmer_types::{
Compilation, CompileError, CompileModuleInfo, CustomSection, CustomSectionProtection, Dwarf, Compilation, CompileError, CompileModuleInfo, CustomSection, CustomSectionProtection, Dwarf,
FunctionIndex, LocalFunctionIndex, RelocationTarget, SectionBody, SectionIndex, SignatureIndex, FunctionIndex, LocalFunctionIndex, RelocationTarget, SectionBody, SectionIndex, SignatureIndex,
Target,
}; };
//use std::sync::Mutex; //use std::sync::Mutex;

View File

@@ -8,8 +8,8 @@ use itertools::Itertools;
use std::fmt::Debug; use std::fmt::Debug;
use std::sync::Arc; use std::sync::Arc;
use target_lexicon::Architecture; use target_lexicon::Architecture;
use wasmer_compiler::{Compiler, CompilerConfig, ModuleMiddleware, Target, Triple}; use wasmer_compiler::{Compiler, CompilerConfig, ModuleMiddleware};
use wasmer_types::{FunctionType, LocalFunctionIndex}; use wasmer_types::{FunctionType, LocalFunctionIndex, Target, Triple};
/// The InkWell ModuleInfo type /// The InkWell ModuleInfo type
pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>; pub type InkwellModule<'ctx> = inkwell::module::Module<'ctx>;
@@ -100,7 +100,7 @@ impl LLVM {
// Hack: we're using is_pic to determine whether this is a native // Hack: we're using is_pic to determine whether this is a native
// build or not. // build or not.
let operating_system = if target.triple().operating_system let operating_system = if target.triple().operating_system
== wasmer_compiler::OperatingSystem::Darwin == wasmer_types::OperatingSystem::Darwin
&& !self.is_pic && !self.is_pic
{ {
// LLVM detects static relocation + darwin + 64-bit and // LLVM detects static relocation + darwin + 64-bit and
@@ -112,7 +112,7 @@ impl LLVM {
// but not in the case of Aarch64, there the ABI is slightly different // but not in the case of Aarch64, there the ABI is slightly different
#[allow(clippy::match_single_binding)] #[allow(clippy::match_single_binding)]
match target.triple().architecture { match target.triple().architecture {
_ => wasmer_compiler::OperatingSystem::Linux, _ => wasmer_types::OperatingSystem::Linux,
} }
} else { } else {
target.triple().operating_system target.triple().operating_system

View File

@@ -5,8 +5,7 @@ use crate::location::CombinedRegister;
use crate::location::Reg as AbstractReg; use crate::location::Reg as AbstractReg;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::slice::Iter; use std::slice::Iter;
use wasmer_compiler::CallingConvention; use wasmer_types::{CallingConvention, Type};
use wasmer_types::Type;
/// General-purpose registers. /// General-purpose registers.
#[repr(u8)] #[repr(u8)]

View File

@@ -12,14 +12,15 @@ use smallvec::{smallvec, SmallVec};
use std::cmp; use std::cmp;
use std::iter; use std::iter;
use wasmer_compiler::wasmparser::{Operator, Type as WpType, TypeOrFuncType as WpTypeOrFuncType}; use wasmer_compiler::wasmparser::{Operator, Type as WpType, TypeOrFuncType as WpTypeOrFuncType};
use wasmer_compiler::{CallingConvention, FunctionBodyData}; use wasmer_compiler::FunctionBodyData;
#[cfg(feature = "unwind")] #[cfg(feature = "unwind")]
use wasmer_types::CompiledFunctionUnwindInfo; use wasmer_types::CompiledFunctionUnwindInfo;
use wasmer_types::{ use wasmer_types::{
entity::{EntityRef, PrimaryMap}, entity::{EntityRef, PrimaryMap},
FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, LocalMemoryIndex, MemoryIndex, CallingConvention, FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex,
MemoryStyle, ModuleInfo, Relocation, RelocationTarget, SectionIndex, SignatureIndex, LocalMemoryIndex, MemoryIndex, MemoryStyle, ModuleInfo, Relocation, RelocationTarget,
TableIndex, TableStyle, TrapCode, Type, VMBuiltinFunctionIndex, VMOffsets, SectionIndex, SignatureIndex, TableIndex, TableStyle, TrapCode, Type, VMBuiltinFunctionIndex,
VMOffsets,
}; };
use wasmer_types::{CompiledFunction, CompiledFunctionFrameInfo, FunctionBody}; use wasmer_types::{CompiledFunction, CompiledFunctionFrameInfo, FunctionBody};

View File

@@ -20,17 +20,15 @@ use gimli::write::{EhFrame, FrameTable};
use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use std::sync::Arc; use std::sync::Arc;
use wasmer_compiler::{ use wasmer_compiler::{
Architecture, CallingConvention, Compiler, CompilerConfig, CpuFeature, FunctionBinaryReader, Compiler, CompilerConfig, FunctionBinaryReader, FunctionBodyData, MiddlewareBinaryReader,
FunctionBodyData, MiddlewareBinaryReader, ModuleMiddleware, ModuleMiddlewareChain, ModuleMiddleware, ModuleMiddlewareChain, ModuleTranslationState,
ModuleTranslationState, OperatingSystem, Target,
}; };
use wasmer_types::entity::{EntityRef, PrimaryMap}; use wasmer_types::entity::{EntityRef, PrimaryMap};
use wasmer_types::{ use wasmer_types::{
Compilation, CompileModuleInfo, CompiledFunction, Dwarf, FunctionBody, TrapInformation, Architecture, CallingConvention, Compilation, CompileError, CompileModuleInfo,
}; CompiledFunction, CpuFeature, Dwarf, FunctionBody, FunctionIndex, FunctionType,
use wasmer_types::{ LocalFunctionIndex, MemoryIndex, ModuleInfo, OperatingSystem, SectionIndex, TableIndex, Target,
CompileError, FunctionIndex, FunctionType, LocalFunctionIndex, MemoryIndex, ModuleInfo, TrapCode, TrapInformation, VMOffsets,
SectionIndex, TableIndex, TrapCode, VMOffsets,
}; };
impl From<CodegenError> for CompileError { impl From<CodegenError> for CompileError {
@@ -318,8 +316,8 @@ mod tests {
use super::*; use super::*;
use std::str::FromStr; use std::str::FromStr;
use target_lexicon::triple; use target_lexicon::triple;
use wasmer_compiler::{CpuFeature, Features, Triple}; use wasmer_compiler::Features;
use wasmer_types::{MemoryStyle, TableStyle}; use wasmer_types::{CpuFeature, MemoryStyle, TableStyle, Triple};
fn dummy_compilation_ingredients<'a>() -> ( fn dummy_compilation_ingredients<'a>() -> (
CompileModuleInfo, CompileModuleInfo,
@@ -328,7 +326,7 @@ mod tests {
) { ) {
let compile_info = CompileModuleInfo { let compile_info = CompileModuleInfo {
features: Features::new(), features: Features::new(),
module: Arc::new(ModuleInfo::new()), module: ModuleInfo::new(),
memory_styles: PrimaryMap::<MemoryIndex, MemoryStyle>::new(), memory_styles: PrimaryMap::<MemoryIndex, MemoryStyle>::new(),
table_styles: PrimaryMap::<TableIndex, TableStyle>::new(), table_styles: PrimaryMap::<TableIndex, TableStyle>::new(),
}; };

View File

@@ -3,8 +3,8 @@
use crate::compiler::SinglepassCompiler; use crate::compiler::SinglepassCompiler;
use std::sync::Arc; use std::sync::Arc;
use wasmer_compiler::{Compiler, CompilerConfig, CpuFeature, ModuleMiddleware, Target}; use wasmer_compiler::{Compiler, CompilerConfig, ModuleMiddleware};
use wasmer_types::Features; use wasmer_types::{CpuFeature, Features, Target};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Singlepass { pub struct Singlepass {

View File

@@ -1,10 +1,9 @@
use gimli::write::{Address, EndianVec, Result, Writer}; use gimli::write::{Address, EndianVec, Result, Writer};
use gimli::{RunTimeEndian, SectionId}; use gimli::{RunTimeEndian, SectionId};
use wasmer_compiler::Endianness;
use wasmer_types::entity::EntityRef; use wasmer_types::entity::EntityRef;
use wasmer_types::{ use wasmer_types::{
CustomSection, CustomSectionProtection, LocalFunctionIndex, Relocation, RelocationKind, CustomSection, CustomSectionProtection, Endianness, LocalFunctionIndex, Relocation,
RelocationTarget, SectionBody, RelocationKind, RelocationTarget, SectionBody,
}; };
#[derive(Clone, Debug)] #[derive(Clone, Debug)]

View File

@@ -11,9 +11,10 @@ use dynasmrt::{
aarch64::Aarch64Relocation, AssemblyOffset, DynamicLabel, DynasmApi, DynasmLabelApi, aarch64::Aarch64Relocation, AssemblyOffset, DynamicLabel, DynasmApi, DynasmLabelApi,
VecAssembler, VecAssembler,
}; };
use wasmer_compiler::CallingConvention; use wasmer_types::{
use wasmer_types::{CustomSection, CustomSectionProtection, SectionBody}; CallingConvention, CustomSection, CustomSectionProtection, FunctionBody, FunctionIndex,
use wasmer_types::{FunctionBody, FunctionIndex, FunctionType, Type, VMOffsets}; FunctionType, SectionBody, Type, VMOffsets,
};
type Assembler = VecAssembler<Aarch64Relocation>; type Assembler = VecAssembler<Aarch64Relocation>;

View File

@@ -8,7 +8,7 @@ use crate::machine_x64::AssemblerX64;
pub use crate::x64_decl::{GPR, XMM}; pub use crate::x64_decl::{GPR, XMM};
use dynasm::dynasm; use dynasm::dynasm;
use dynasmrt::{AssemblyOffset, DynamicLabel, DynasmApi, DynasmLabelApi}; use dynasmrt::{AssemblyOffset, DynamicLabel, DynasmApi, DynasmLabelApi};
use wasmer_compiler::CpuFeature; use wasmer_types::CpuFeature;
/// Force `dynasm!` to use the correct arch (x64) when cross-compiling. /// Force `dynasm!` to use the correct arch (x64) when cross-compiling.
/// `dynasm!` proc-macro tries to auto-detect it by default by looking at the /// `dynasm!` proc-macro tries to auto-detect it by default by looking at the

View File

@@ -8,10 +8,11 @@ use std::collections::BTreeMap;
use std::fmt::Debug; use std::fmt::Debug;
pub use wasmer_compiler::wasmparser::MemoryImmediate; pub use wasmer_compiler::wasmparser::MemoryImmediate;
use wasmer_compiler::wasmparser::Type as WpType; use wasmer_compiler::wasmparser::Type as WpType;
use wasmer_compiler::{Architecture, CallingConvention, CpuFeature, Target}; use wasmer_types::{
use wasmer_types::{CustomSection, Relocation, RelocationTarget}; Architecture, CallingConvention, CpuFeature, CustomSection, FunctionBody, FunctionIndex,
use wasmer_types::{FunctionBody, InstructionAddressMap, TrapInformation}; FunctionType, InstructionAddressMap, Relocation, RelocationTarget, Target, TrapCode,
use wasmer_types::{FunctionIndex, FunctionType, TrapCode, VMOffsets}; TrapInformation, VMOffsets,
};
pub type Label = DynamicLabel; pub type Label = DynamicLabel;
pub type Offset = AssemblyOffset; pub type Offset = AssemblyOffset;

View File

@@ -11,10 +11,11 @@ use dynasmrt::{aarch64::Aarch64Relocation, VecAssembler};
#[cfg(feature = "unwind")] #[cfg(feature = "unwind")]
use gimli::{write::CallFrameInstruction, AArch64}; use gimli::{write::CallFrameInstruction, AArch64};
use wasmer_compiler::wasmparser::Type as WpType; use wasmer_compiler::wasmparser::Type as WpType;
use wasmer_compiler::CallingConvention; use wasmer_types::{
use wasmer_types::{CustomSection, Relocation, RelocationKind, RelocationTarget}; CallingConvention, CustomSection, FunctionBody, FunctionIndex, FunctionType,
use wasmer_types::{FunctionBody, InstructionAddressMap, SourceLoc, TrapInformation}; InstructionAddressMap, Relocation, RelocationKind, RelocationTarget, SourceLoc, TrapCode,
use wasmer_types::{FunctionIndex, FunctionType, TrapCode, VMOffsets}; TrapInformation, VMOffsets,
};
type Assembler = VecAssembler<Aarch64Relocation>; type Assembler = VecAssembler<Aarch64Relocation>;
type Location = AbstractLocation<GPR, NEON>; type Location = AbstractLocation<GPR, NEON>;

View File

@@ -14,10 +14,9 @@ use dynasmrt::{x64::X64Relocation, DynasmError, VecAssembler};
use gimli::{write::CallFrameInstruction, X86_64}; use gimli::{write::CallFrameInstruction, X86_64};
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use wasmer_compiler::wasmparser::Type as WpType; use wasmer_compiler::wasmparser::Type as WpType;
use wasmer_compiler::{CallingConvention, CpuFeature};
use wasmer_types::{ use wasmer_types::{
CustomSection, CustomSectionProtection, Relocation, RelocationKind, RelocationTarget, CallingConvention, CpuFeature, CustomSection, CustomSectionProtection, Relocation,
SectionBody, RelocationKind, RelocationTarget, SectionBody,
}; };
use wasmer_types::{FunctionBody, InstructionAddressMap, SourceLoc, TrapInformation}; use wasmer_types::{FunctionBody, InstructionAddressMap, SourceLoc, TrapInformation};
use wasmer_types::{FunctionIndex, FunctionType, TrapCode, Type, VMOffsets}; use wasmer_types::{FunctionIndex, FunctionType, TrapCode, Type, VMOffsets};

View File

@@ -4,7 +4,7 @@ use gimli::write::{Address, CallFrameInstruction, CommonInformationEntry, FrameD
use gimli::{AArch64, Encoding, Format, X86_64}; use gimli::{AArch64, Encoding, Format, X86_64};
use std::fmt::Debug; use std::fmt::Debug;
#[cfg(feature = "unwind")] #[cfg(feature = "unwind")]
use wasmer_compiler::Architecture; use wasmer_types::Architecture;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum UnwindOps { pub enum UnwindOps {

View File

@@ -6,8 +6,7 @@ use crate::location::CombinedRegister;
use crate::location::Reg as AbstractReg; use crate::location::Reg as AbstractReg;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::slice::Iter; use std::slice::Iter;
use wasmer_compiler::CallingConvention; use wasmer_types::{CallingConvention, Type};
use wasmer_types::Type;
/// General-purpose registers. /// General-purpose registers.
#[repr(u8)] #[repr(u8)]

View File

@@ -13,7 +13,6 @@ edition = "2018"
[dependencies] [dependencies]
wasmer-types = { path = "../types", version = "=2.3.0", default-features = false } wasmer-types = { path = "../types", version = "=2.3.0", default-features = false }
wasmparser = { version = "0.83", optional = true, default-features = false } wasmparser = { version = "0.83", optional = true, default-features = false }
target-lexicon = { version = "0.12.2", default-features = false }
enumset = "1.0.2" enumset = "1.0.2"
hashbrown = { version = "0.11", optional = true } hashbrown = { version = "0.11", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true } serde = { version = "1.0", features = ["derive"], optional = true }

View File

@@ -1,16 +1,16 @@
//! Generic Artifact abstraction for Wasmer Engines. //! Generic Artifact abstraction for Wasmer Engines.
use crate::{CpuFeature, Features}; use crate::Features;
use enumset::EnumSet; use enumset::EnumSet;
use std::any::Any; use std::any::Any;
use std::convert::TryInto; use std::convert::TryInto;
use std::path::Path; use std::path::Path;
use std::{fs, mem}; use std::{fs, mem};
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
use wasmer_types::{DeserializeError, SerializeError};
use wasmer_types::{ use wasmer_types::{
MemoryIndex, MemoryStyle, ModuleInfo, OwnedDataInitializer, TableIndex, TableStyle, CpuFeature, MemoryIndex, MemoryStyle, ModuleInfo, OwnedDataInitializer, TableIndex, TableStyle,
}; };
use wasmer_types::{DeserializeError, SerializeError};
/// An `Artifact` is the product that the `Engine` /// An `Artifact` is the product that the `Engine`
/// implementation produce and use. /// implementation produce and use.

View File

@@ -3,12 +3,12 @@
use crate::lib::std::boxed::Box; use crate::lib::std::boxed::Box;
use crate::lib::std::sync::Arc; use crate::lib::std::sync::Arc;
use crate::target::Target;
use crate::translator::ModuleMiddleware; use crate::translator::ModuleMiddleware;
use crate::FunctionBodyData; use crate::FunctionBodyData;
use crate::ModuleTranslationState; use crate::ModuleTranslationState;
use wasmer_types::compilation::function::Compilation; use wasmer_types::compilation::function::Compilation;
use wasmer_types::compilation::module::CompileModuleInfo; use wasmer_types::compilation::module::CompileModuleInfo;
use wasmer_types::compilation::target::Target;
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
use wasmer_types::error::CompileError; use wasmer_types::error::CompileError;
use wasmer_types::SectionIndex; use wasmer_types::SectionIndex;

View File

@@ -1,161 +0,0 @@
use crate::CpuFeature;
use crate::{resolve_imports, InstantiationError, RuntimeError, Tunables};
use crate::{ArtifactCreate, Upcastable};
use std::sync::Arc;
use wasmer_types::entity::BoxedSlice;
use wasmer_types::{DataInitializer, FunctionIndex, LocalFunctionIndex, SignatureIndex};
use wasmer_vm::{
FunctionBodyPtr, InstanceAllocator, InstanceHandle, StoreObjects, TrapHandlerFn, VMExtern,
VMSharedSignatureIndex, VMTrampoline,
};
/// An `Artifact` is the product that the `Engine`
/// implementation produce and use.
///
/// An `Artifact` is the product that the `Engine`
/// implementation produce and use.
///
/// The `ArtifactRun` contains the extra information needed to run the
/// module at runtime, such as [`ModuleInfo`] and [`Features`].
pub trait Artifact: Send + Sync + Upcastable + ArtifactCreate {
/// Register thie `Artifact` stack frame information into the global scope.
///
/// This is required to ensure that any traps can be properly symbolicated.
fn register_frame_info(&self);
/// Returns the functions allocated in memory or this `Artifact`
/// ready to be run.
fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr>;
/// Returns the function call trampolines allocated in memory of this
/// `Artifact`, ready to be run.
fn finished_function_call_trampolines(&self) -> &BoxedSlice<SignatureIndex, VMTrampoline>;
/// Returns the dynamic function trampolines allocated in memory
/// of this `Artifact`, ready to be run.
fn finished_dynamic_function_trampolines(&self) -> &BoxedSlice<FunctionIndex, FunctionBodyPtr>;
/// Returns the associated VM signatures for this `Artifact`.
fn signatures(&self) -> &BoxedSlice<SignatureIndex, VMSharedSignatureIndex>;
/// Do preinstantiation logic that is executed before instantiating
fn preinstantiate(&self) -> Result<(), InstantiationError> {
Ok(())
}
/// Crate an `Instance` from this `Artifact`.
///
/// # Safety
///
/// See [`InstanceHandle::new`].
unsafe fn instantiate(
&self,
tunables: &dyn Tunables,
imports: &[VMExtern],
context: &mut StoreObjects,
) -> Result<InstanceHandle, InstantiationError> {
// Validate the CPU features this module was compiled with against the
// host CPU features.
let host_cpu_features = CpuFeature::for_host();
if !host_cpu_features.is_superset(self.cpu_features()) {
return Err(InstantiationError::CpuFeature(format!(
"{:?}",
self.cpu_features().difference(host_cpu_features)
)));
}
self.preinstantiate()?;
let module = Arc::new(self.create_module_info());
let imports = resolve_imports(
&module,
imports,
context,
self.finished_dynamic_function_trampolines(),
self.memory_styles(),
self.table_styles(),
)
.map_err(InstantiationError::Link)?;
// Get pointers to where metadata about local memories should live in VM memory.
// Get pointers to where metadata about local tables should live in VM memory.
let (allocator, memory_definition_locations, table_definition_locations) =
InstanceAllocator::new(&*module);
let finished_memories = tunables
.create_memories(
context,
&module,
self.memory_styles(),
&memory_definition_locations,
)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
let finished_tables = tunables
.create_tables(
context,
&module,
self.table_styles(),
&table_definition_locations,
)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
let finished_globals = tunables
.create_globals(context, &module)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
self.register_frame_info();
let handle = InstanceHandle::new(
allocator,
module,
context,
self.finished_functions().clone(),
self.finished_function_call_trampolines().clone(),
finished_memories,
finished_tables,
finished_globals,
imports,
self.signatures().clone(),
)
.map_err(|trap| InstantiationError::Start(RuntimeError::from_trap(trap)))?;
Ok(handle)
}
/// Finishes the instantiation of a just created `InstanceHandle`.
///
/// # Safety
///
/// See [`InstanceHandle::finish_instantiation`].
unsafe fn finish_instantiation(
&self,
trap_handler: Option<*const TrapHandlerFn<'static>>,
handle: &mut InstanceHandle,
) -> Result<(), InstantiationError> {
let data_initializers = self
.data_initializers()
.iter()
.map(|init| DataInitializer {
location: init.location.clone(),
data: &*init.data,
})
.collect::<Vec<_>>();
handle
.finish_instantiation(trap_handler, &data_initializers)
.map_err(|trap| InstantiationError::Start(RuntimeError::from_trap(trap)))
}
}
impl dyn Artifact + 'static {
/// Try to downcast the artifact into a given type.
#[inline]
pub fn downcast_ref<T: 'static>(&'_ self) -> Option<&'_ T> {
self.upcast_any_ref().downcast_ref::<T>()
}
/// Try to downcast the artifact into a given type mutably.
#[inline]
pub fn downcast_mut<T: 'static>(&'_ mut self) -> Option<&'_ mut T> {
self.upcast_any_mut().downcast_mut::<T>()
}
}

View File

@@ -1,13 +1,12 @@
//! Engine trait and associated types. //! Engine trait and associated types.
use crate::engine::tunables::Tunables; use crate::engine::tunables::Tunables;
use crate::Artifact; use crate::UniversalArtifact;
use crate::Target;
use memmap2::Mmap; use memmap2::Mmap;
use std::path::Path; use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc; use std::sync::Arc;
use wasmer_types::{CompileError, DeserializeError, FunctionType}; use wasmer_types::{CompileError, DeserializeError, FunctionType, Target};
use wasmer_vm::VMSharedSignatureIndex; use wasmer_vm::VMSharedSignatureIndex;
/// A unimplemented Wasmer `Engine`. /// A unimplemented Wasmer `Engine`.
@@ -34,14 +33,14 @@ pub trait Engine {
&self, &self,
binary: &[u8], binary: &[u8],
tunables: &dyn Tunables, tunables: &dyn Tunables,
) -> Result<Arc<dyn Artifact>, CompileError>; ) -> Result<Arc<UniversalArtifact>, CompileError>;
/// Deserializes a WebAssembly module /// Deserializes a WebAssembly module
/// ///
/// # Safety /// # Safety
/// ///
/// The serialized content must represent a serialized WebAssembly module. /// The serialized content must represent a serialized WebAssembly module.
unsafe fn deserialize(&self, bytes: &[u8]) -> Result<Arc<dyn Artifact>, DeserializeError>; unsafe fn deserialize(&self, bytes: &[u8]) -> Result<Arc<UniversalArtifact>, DeserializeError>;
/// Deserializes a WebAssembly module from a path /// Deserializes a WebAssembly module from a path
/// ///
@@ -51,7 +50,7 @@ pub trait Engine {
unsafe fn deserialize_from_file( unsafe fn deserialize_from_file(
&self, &self,
file_ref: &Path, file_ref: &Path,
) -> Result<Arc<dyn Artifact>, DeserializeError> { ) -> Result<Arc<UniversalArtifact>, DeserializeError> {
let file = std::fs::File::open(file_ref)?; let file = std::fs::File::open(file_ref)?;
let mmap = Mmap::map(&file)?; let mmap = Mmap::map(&file)?;
self.deserialize(&mmap) self.deserialize(&mmap)

View File

@@ -1,6 +1,5 @@
//! Generic Engine abstraction for Wasmer Engines. //! Generic Engine abstraction for Wasmer Engines.
mod artifact;
mod error; mod error;
mod inner; mod inner;
mod resolver; mod resolver;
@@ -10,7 +9,6 @@ mod tunables;
#[cfg(feature = "translator")] #[cfg(feature = "translator")]
mod universal; mod universal;
pub use self::artifact::Artifact;
pub use self::error::{InstantiationError, LinkError}; pub use self::error::{InstantiationError, LinkError};
pub use self::inner::{Engine, EngineId}; pub use self::inner::{Engine, EngineId};
pub use self::resolver::resolve_imports; pub use self::resolver::resolve_imports;

View File

@@ -4,21 +4,25 @@
use super::engine::{UniversalEngine, UniversalEngineInner}; use super::engine::{UniversalEngine, UniversalEngineInner};
use crate::engine::universal::link::link_module; use crate::engine::universal::link::link_module;
use crate::ArtifactCreate; use crate::ArtifactCreate;
use crate::Features;
use crate::UniversalArtifactBuild; use crate::UniversalArtifactBuild;
use crate::{ use crate::{
register_frame_info, Artifact, FunctionExtent, GlobalFrameInfoRegistration, MetadataHeader, register_frame_info, resolve_imports, FunctionExtent, GlobalFrameInfoRegistration,
InstantiationError, MetadataHeader, RuntimeError, Tunables,
}; };
use crate::{CpuFeature, Features, Triple};
#[cfg(feature = "universal_engine")] #[cfg(feature = "universal_engine")]
use crate::{Engine, ModuleEnvironment, Tunables}; use crate::{Engine, ModuleEnvironment};
use enumset::EnumSet; use enumset::EnumSet;
use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
use wasmer_types::entity::{BoxedSlice, PrimaryMap}; use wasmer_types::entity::{BoxedSlice, PrimaryMap};
use wasmer_types::{ use wasmer_types::{
CompileError, DeserializeError, FunctionIndex, LocalFunctionIndex, MemoryIndex, ModuleInfo, CompileError, CpuFeature, DataInitializer, DeserializeError, FunctionIndex, LocalFunctionIndex,
OwnedDataInitializer, SerializableModule, SerializeError, SignatureIndex, TableIndex, MemoryIndex, ModuleInfo, OwnedDataInitializer, SerializableModule, SerializeError,
SignatureIndex, TableIndex, Triple,
}; };
use wasmer_vm::{FunctionBodyPtr, MemoryStyle, TableStyle, VMSharedSignatureIndex, VMTrampoline}; use wasmer_vm::{FunctionBodyPtr, MemoryStyle, TableStyle, VMSharedSignatureIndex, VMTrampoline};
use wasmer_vm::{InstanceAllocator, InstanceHandle, StoreObjects, TrapHandlerFn, VMExtern};
/// A compiled wasm module, ready to be instantiated. /// A compiled wasm module, ready to be instantiated.
pub struct UniversalArtifact { pub struct UniversalArtifact {
@@ -219,8 +223,11 @@ impl ArtifactCreate for UniversalArtifact {
} }
} }
impl Artifact for UniversalArtifact { impl UniversalArtifact {
fn register_frame_info(&self) { /// Register thie `Artifact` stack frame information into the global scope.
///
/// This is required to ensure that any traps can be properly symbolicated.
pub fn register_frame_info(&self) {
let mut info = self.frame_info_registration.lock().unwrap(); let mut info = self.frame_info_registration.lock().unwrap();
if info.is_some() { if info.is_some() {
@@ -244,19 +251,136 @@ impl Artifact for UniversalArtifact {
); );
} }
fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> { /// Returns the functions allocated in memory or this `Artifact`
/// ready to be run.
pub fn finished_functions(&self) -> &BoxedSlice<LocalFunctionIndex, FunctionBodyPtr> {
&self.finished_functions &self.finished_functions
} }
fn finished_function_call_trampolines(&self) -> &BoxedSlice<SignatureIndex, VMTrampoline> { /// Returns the function call trampolines allocated in memory of this
/// `Artifact`, ready to be run.
pub fn finished_function_call_trampolines(&self) -> &BoxedSlice<SignatureIndex, VMTrampoline> {
&self.finished_function_call_trampolines &self.finished_function_call_trampolines
} }
fn finished_dynamic_function_trampolines(&self) -> &BoxedSlice<FunctionIndex, FunctionBodyPtr> { /// Returns the dynamic function trampolines allocated in memory
/// of this `Artifact`, ready to be run.
pub fn finished_dynamic_function_trampolines(
&self,
) -> &BoxedSlice<FunctionIndex, FunctionBodyPtr> {
&self.finished_dynamic_function_trampolines &self.finished_dynamic_function_trampolines
} }
fn signatures(&self) -> &BoxedSlice<SignatureIndex, VMSharedSignatureIndex> { /// Returns the associated VM signatures for this `Artifact`.
pub fn signatures(&self) -> &BoxedSlice<SignatureIndex, VMSharedSignatureIndex> {
&self.signatures &self.signatures
} }
/// Do preinstantiation logic that is executed before instantiating
pub fn preinstantiate(&self) -> Result<(), InstantiationError> {
Ok(())
}
/// Crate an `Instance` from this `Artifact`.
///
/// # Safety
///
/// See [`InstanceHandle::new`].
pub unsafe fn instantiate(
&self,
tunables: &dyn Tunables,
imports: &[VMExtern],
context: &mut StoreObjects,
) -> Result<InstanceHandle, InstantiationError> {
// Validate the CPU features this module was compiled with against the
// host CPU features.
let host_cpu_features = CpuFeature::for_host();
if !host_cpu_features.is_superset(self.cpu_features()) {
return Err(InstantiationError::CpuFeature(format!(
"{:?}",
self.cpu_features().difference(host_cpu_features)
)));
}
self.preinstantiate()?;
let module = Arc::new(self.create_module_info());
let imports = resolve_imports(
&module,
imports,
context,
self.finished_dynamic_function_trampolines(),
self.memory_styles(),
self.table_styles(),
)
.map_err(InstantiationError::Link)?;
// Get pointers to where metadata about local memories should live in VM memory.
// Get pointers to where metadata about local tables should live in VM memory.
let (allocator, memory_definition_locations, table_definition_locations) =
InstanceAllocator::new(&*module);
let finished_memories = tunables
.create_memories(
context,
&module,
self.memory_styles(),
&memory_definition_locations,
)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
let finished_tables = tunables
.create_tables(
context,
&module,
self.table_styles(),
&table_definition_locations,
)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
let finished_globals = tunables
.create_globals(context, &module)
.map_err(InstantiationError::Link)?
.into_boxed_slice();
self.register_frame_info();
let handle = InstanceHandle::new(
allocator,
module,
context,
self.finished_functions().clone(),
self.finished_function_call_trampolines().clone(),
finished_memories,
finished_tables,
finished_globals,
imports,
self.signatures().clone(),
)
.map_err(|trap| InstantiationError::Start(RuntimeError::from_trap(trap)))?;
Ok(handle)
}
/// Finishes the instantiation of a just created `InstanceHandle`.
///
/// # Safety
///
/// See [`InstanceHandle::finish_instantiation`].
pub unsafe fn finish_instantiation(
&self,
trap_handler: Option<*const TrapHandlerFn<'static>>,
handle: &mut InstanceHandle,
) -> Result<(), InstantiationError> {
let data_initializers = self
.data_initializers()
.iter()
.map(|init| DataInitializer {
location: init.location.clone(),
data: &*init.data,
})
.collect::<Vec<_>>();
handle
.finish_instantiation(trap_handler, &data_initializers)
.map_err(|trap| InstantiationError::Start(RuntimeError::from_trap(trap)))
}
} }

View File

@@ -1,5 +1,6 @@
use super::UniversalEngine; use super::UniversalEngine;
use crate::{CompilerConfig, Features, Target}; use crate::{CompilerConfig, Features};
use wasmer_types::Target;
/// The Universal builder /// The Universal builder
pub struct Universal { pub struct Universal {

View File

@@ -2,16 +2,15 @@
#[cfg(feature = "universal_engine")] #[cfg(feature = "universal_engine")]
use crate::Compiler; use crate::Compiler;
use crate::Target;
use crate::UniversalEngineBuilder; use crate::UniversalEngineBuilder;
use crate::{Artifact, Engine, EngineId, FunctionExtent, Tunables};
use crate::{CodeMemory, UniversalArtifact}; use crate::{CodeMemory, UniversalArtifact};
use crate::{Engine, EngineId, FunctionExtent, Tunables};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
use wasmer_types::FunctionBody; use wasmer_types::FunctionBody;
use wasmer_types::{ use wasmer_types::{
CompileError, DeserializeError, Features, FunctionIndex, FunctionType, LocalFunctionIndex, CompileError, DeserializeError, Features, FunctionIndex, FunctionType, LocalFunctionIndex,
ModuleInfo, SignatureIndex, ModuleInfo, SignatureIndex, Target,
}; };
use wasmer_types::{CustomSection, CustomSectionProtection, SectionIndex}; use wasmer_types::{CustomSection, CustomSectionProtection, SectionIndex};
use wasmer_vm::{ use wasmer_vm::{
@@ -106,7 +105,7 @@ impl Engine for UniversalEngine {
&self, &self,
binary: &[u8], binary: &[u8],
tunables: &dyn Tunables, tunables: &dyn Tunables,
) -> Result<Arc<dyn Artifact>, CompileError> { ) -> Result<Arc<UniversalArtifact>, CompileError> {
Ok(Arc::new(UniversalArtifact::new(self, binary, tunables)?)) Ok(Arc::new(UniversalArtifact::new(self, binary, tunables)?))
} }
@@ -116,7 +115,7 @@ impl Engine for UniversalEngine {
&self, &self,
_binary: &[u8], _binary: &[u8],
_tunables: &dyn Tunables, _tunables: &dyn Tunables,
) -> Result<Arc<dyn Artifact>, CompileError> { ) -> Result<Arc<UniversalArtifact>, CompileError> {
Err(CompileError::Codegen( Err(CompileError::Codegen(
"The UniversalEngine is operating in headless mode, so it can not compile Modules." "The UniversalEngine is operating in headless mode, so it can not compile Modules."
.to_string(), .to_string(),
@@ -124,7 +123,7 @@ impl Engine for UniversalEngine {
} }
/// Deserializes a WebAssembly module /// Deserializes a WebAssembly module
unsafe fn deserialize(&self, bytes: &[u8]) -> Result<Arc<dyn Artifact>, DeserializeError> { unsafe fn deserialize(&self, bytes: &[u8]) -> Result<Arc<UniversalArtifact>, DeserializeError> {
Ok(Arc::new(UniversalArtifact::deserialize(self, bytes)?)) Ok(Arc::new(UniversalArtifact::deserialize(self, bytes)?))
} }

View File

@@ -67,17 +67,12 @@ pub use self::universal_artifact::*;
#[cfg(feature = "translator")] #[cfg(feature = "translator")]
mod compiler; mod compiler;
mod target;
#[cfg(feature = "translator")] #[cfg(feature = "translator")]
#[macro_use] #[macro_use]
mod translator; mod translator;
#[cfg(feature = "translator")] #[cfg(feature = "translator")]
pub use crate::compiler::{Compiler, CompilerConfig, Symbol, SymbolRegistry}; pub use crate::compiler::{Compiler, CompilerConfig, Symbol, SymbolRegistry};
pub use crate::target::{
Architecture, BinaryFormat, CallingConvention, CpuFeature, Endianness, OperatingSystem,
PointerWidth, Target, Triple,
};
#[cfg(feature = "translator")] #[cfg(feature = "translator")]
pub use crate::translator::{ pub use crate::translator::{
from_binaryreadererror_wasmerror, translate_module, wptype_to_type, FunctionBinaryReader, from_binaryreadererror_wasmerror, translate_module, wptype_to_type, FunctionBinaryReader,

View File

@@ -3,11 +3,11 @@
#[cfg(feature = "universal_engine")] #[cfg(feature = "universal_engine")]
use super::trampoline::{libcall_trampoline_len, make_libcall_trampolines}; use super::trampoline::{libcall_trampoline_len, make_libcall_trampolines};
use crate::Features;
use crate::MetadataHeader; use crate::MetadataHeader;
use crate::{ArtifactCreate, UniversalEngineBuilder}; use crate::{ArtifactCreate, UniversalEngineBuilder};
use crate::{CpuFeature, Features, Triple};
#[cfg(feature = "universal_engine")] #[cfg(feature = "universal_engine")]
use crate::{ModuleEnvironment, ModuleMiddlewareChain, Target}; use crate::{ModuleEnvironment, ModuleMiddlewareChain};
use enumset::EnumSet; use enumset::EnumSet;
use std::mem; use std::mem;
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
@@ -15,9 +15,9 @@ use wasmer_types::entity::PrimaryMap;
use wasmer_types::CompileModuleInfo; use wasmer_types::CompileModuleInfo;
use wasmer_types::SerializeError; use wasmer_types::SerializeError;
use wasmer_types::{ use wasmer_types::{
CompileError, CustomSection, Dwarf, FunctionIndex, LocalFunctionIndex, MemoryIndex, CompileError, CpuFeature, CustomSection, Dwarf, FunctionIndex, LocalFunctionIndex, MemoryIndex,
MemoryStyle, ModuleInfo, OwnedDataInitializer, Relocation, SectionIndex, SignatureIndex, MemoryStyle, ModuleInfo, OwnedDataInitializer, Relocation, SectionIndex, SignatureIndex,
TableIndex, TableStyle, TableIndex, TableStyle, Target, Triple,
}; };
use wasmer_types::{ use wasmer_types::{
CompiledFunctionFrameInfo, FunctionBody, SerializableCompilation, SerializableModule, CompiledFunctionFrameInfo, FunctionBody, SerializableCompilation, SerializableModule,

View File

@@ -3,11 +3,10 @@
//! This is needed because the target of libcall relocations are not reachable //! This is needed because the target of libcall relocations are not reachable
//! through normal branch instructions. //! through normal branch instructions.
use crate::{Architecture, Target};
use enum_iterator::IntoEnumIterator; use enum_iterator::IntoEnumIterator;
use wasmer_types::{ use wasmer_types::{
CustomSection, CustomSectionProtection, LibCall, Relocation, RelocationKind, RelocationTarget, Architecture, CustomSection, CustomSectionProtection, LibCall, Relocation, RelocationKind,
SectionBody, RelocationTarget, SectionBody, Target,
}; };
// SystemV says that both x16 and x17 are available as intra-procedural scratch // SystemV says that both x16 and x17 are available as intra-procedural scratch

View File

@@ -6,11 +6,12 @@ use object::{
elf, macho, RelocationEncoding, RelocationKind, SectionKind, SymbolFlags, SymbolKind, elf, macho, RelocationEncoding, RelocationKind, SectionKind, SymbolFlags, SymbolKind,
SymbolScope, SymbolScope,
}; };
use wasmer_compiler::{Architecture, BinaryFormat, Endianness, Symbol, SymbolRegistry, Triple}; use wasmer_compiler::{Symbol, SymbolRegistry};
use wasmer_types::entity::PrimaryMap; use wasmer_types::entity::PrimaryMap;
use wasmer_types::LocalFunctionIndex; use wasmer_types::LocalFunctionIndex;
use wasmer_types::{ use wasmer_types::{
Compilation, CustomSectionProtection, RelocationKind as Reloc, RelocationTarget, SectionIndex, Architecture, BinaryFormat, Compilation, CustomSectionProtection, Endianness,
RelocationKind as Reloc, RelocationTarget, SectionIndex, Triple,
}; };
const DWARF_SECTION_NAME: &[u8] = b".eh_frame"; const DWARF_SECTION_NAME: &[u8] = b".eh_frame";
@@ -20,7 +21,7 @@ const DWARF_SECTION_NAME: &[u8] = b".eh_frame";
/// # Usage /// # Usage
/// ///
/// ```rust /// ```rust
/// # use wasmer_compiler::Triple; /// # use wasmer_types::Triple;
/// # use wasmer_object::ObjectError; /// # use wasmer_object::ObjectError;
/// use wasmer_object::get_object_for_target; /// use wasmer_object::get_object_for_target;
/// ///
@@ -72,7 +73,7 @@ pub fn get_object_for_target(triple: &Triple) -> Result<Object, ObjectError> {
/// # Usage /// # Usage
/// ///
/// ```rust /// ```rust
/// # use wasmer_compiler::Triple; /// # use wasmer_types::Triple;
/// # use wasmer_object::ObjectError; /// # use wasmer_object::ObjectError;
/// use wasmer_object::{get_object_for_target, emit_data}; /// use wasmer_object::{get_object_for_target, emit_data};
/// ///
@@ -110,8 +111,8 @@ pub fn emit_data(
/// # Usage /// # Usage
/// ///
/// ```rust /// ```rust
/// # use wasmer_compiler::{SymbolRegistry, Triple}; /// # use wasmer_compiler::SymbolRegistry;
/// # use wasmer_types::Compilation; /// # use wasmer_types::{Compilation, Triple};
/// # use wasmer_object::ObjectError; /// # use wasmer_object::ObjectError;
/// use wasmer_object::{get_object_for_target, emit_compilation}; /// use wasmer_object::{get_object_for_target, emit_compilation};
/// ///

View File

@@ -18,6 +18,8 @@ more-asserts = "0.2"
indexmap = { version = "1.6", features = ["serde-1"] } indexmap = { version = "1.6", features = ["serde-1"] }
rkyv = { version = "0.7.38", features = ["indexmap"] } rkyv = { version = "0.7.38", features = ["indexmap"] }
enum-iterator = "0.7.0" enum-iterator = "0.7.0"
target-lexicon = { version = "0.12.2", default-features = false }
enumset = "1.0"
[features] [features]
default = ["std", "enable-serde"] default = ["std", "enable-serde"]

View File

@@ -6,5 +6,6 @@ pub mod module;
pub mod relocation; pub mod relocation;
pub mod section; pub mod section;
pub mod sourceloc; pub mod sourceloc;
pub mod target;
pub mod trap; pub mod trap;
pub mod unwind; pub mod unwind;

View File

@@ -7,14 +7,14 @@
// See https://github.com/rust-lang/rust-clippy/issues/6902 // See https://github.com/rust-lang/rust-clippy/issues/6902
#![allow(clippy::use_self)] #![allow(clippy::use_self)]
use crate::lib::std::str::FromStr; use crate::error::ParseCpuFeatureError;
use crate::lib::std::string::{String, ToString};
use enumset::{EnumSet, EnumSetType}; use enumset::{EnumSet, EnumSetType};
use std::str::FromStr;
use std::string::{String, ToString};
pub use target_lexicon::{ pub use target_lexicon::{
Architecture, BinaryFormat, CallingConvention, Endianness, OperatingSystem, PointerWidth, Architecture, BinaryFormat, CallingConvention, Endianness, OperatingSystem, PointerWidth,
Triple, Triple,
}; };
use wasmer_types::error::ParseCpuFeatureError;
/// The nomenclature is inspired by the [`cpuid` crate]. /// The nomenclature is inspired by the [`cpuid` crate].
/// The list of supported features was initially retrieved from /// The list of supported features was initially retrieved from

View File

@@ -70,7 +70,11 @@ mod utils;
mod value; mod value;
mod vmoffsets; mod vmoffsets;
pub use crate::serialize::{SerializableCompilation, SerializableModule}; pub use crate::compilation::target::{
Architecture, BinaryFormat, CallingConvention, CpuFeature, Endianness, OperatingSystem,
PointerWidth, Target, Triple,
};
pub use crate::serialize::{MetadataHeader, SerializableCompilation, SerializableModule};
pub use error::{ pub use error::{
CompileError, DeserializeError, ImportError, MiddlewareError, ParseCpuFeatureError, CompileError, DeserializeError, ImportError, MiddlewareError, ParseCpuFeatureError,
PreInstantiationError, SerializeError, WasmError, WasmResult, PreInstantiationError, SerializeError, WasmError, WasmResult,

View File

@@ -1,14 +1,19 @@
use crate::entity::PrimaryMap; use crate::entity::PrimaryMap;
use crate::{ use crate::{
CompileModuleInfo, CompiledFunctionFrameInfo, CustomSection, DeserializeError, Dwarf, compilation::target::CpuFeature, CompileModuleInfo, CompiledFunctionFrameInfo, CustomSection,
FunctionBody, FunctionIndex, LocalFunctionIndex, OwnedDataInitializer, Relocation, DeserializeError, Dwarf, Features, FunctionBody, FunctionIndex, LocalFunctionIndex,
SectionIndex, SerializeError, SignatureIndex, MemoryIndex, MemoryStyle, ModuleInfo, OwnedDataInitializer, Relocation, SectionIndex,
SerializeError, SignatureIndex, TableIndex, TableStyle,
}; };
use enumset::EnumSet;
use rkyv::{ use rkyv::{
archived_value, de::deserializers::SharedDeserializeMap, ser::serializers::AllocSerializer, archived_value, de::deserializers::SharedDeserializeMap, ser::serializers::AllocSerializer,
ser::Serializer as RkyvSerializer, Archive, Deserialize as RkyvDeserialize, ser::Serializer as RkyvSerializer, Archive, Deserialize as RkyvDeserialize,
Serialize as RkyvSerialize, Serialize as RkyvSerialize,
}; };
use std::convert::TryInto;
use std::path::Path;
use std::{fs, mem};
/// The compilation related data for a serialized modules /// The compilation related data for a serialized modules
#[derive(Archive, RkyvDeserialize, RkyvSerialize)] #[derive(Archive, RkyvDeserialize, RkyvSerialize)]
@@ -107,4 +112,109 @@ impl SerializableModule {
RkyvDeserialize::deserialize(archived, &mut deserializer) RkyvDeserialize::deserialize(archived, &mut deserializer)
.map_err(|e| DeserializeError::CorruptedBinary(format!("{:?}", e))) .map_err(|e| DeserializeError::CorruptedBinary(format!("{:?}", e)))
} }
/// Create a `ModuleInfo` for instantiation
pub fn create_module_info(&self) -> ModuleInfo {
self.compile_info.module.clone()
}
/// Returns the features for this Artifact
pub fn features(&self) -> &Features {
&self.compile_info.features
}
/// Returns the CPU features for this Artifact
pub fn cpu_features(&self) -> EnumSet<CpuFeature> {
EnumSet::from_u64(self.cpu_features)
}
/// Returns data initializers to pass to `InstanceHandle::initialize`
pub fn data_initializers(&self) -> &[OwnedDataInitializer] {
&*self.data_initializers
}
/// Returns the memory styles associated with this `Artifact`.
pub fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
&self.compile_info.memory_styles
}
/// Returns the table plans associated with this `Artifact`.
pub fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
&self.compile_info.table_styles
}
/// Serializes an artifact into a file path
pub fn serialize_to_file(&self, path: &Path) -> Result<(), SerializeError> {
let serialized = self.serialize()?;
fs::write(&path, serialized)?;
Ok(())
}
}
/// Metadata header which holds an ABI version and the length of the remaining
/// metadata.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct MetadataHeader {
magic: [u8; 8],
version: u32,
len: u32,
}
impl MetadataHeader {
/// Current ABI version. Increment this any time breaking changes are made
/// to the format of the serialized data.
const CURRENT_VERSION: u32 = 1;
/// Magic number to identify wasmer metadata.
const MAGIC: [u8; 8] = *b"WASMER\0\0";
/// Length of the metadata header.
pub const LEN: usize = 16;
/// Alignment of the metadata.
pub const ALIGN: usize = 16;
/// Creates a new header for metadata of the given length.
pub fn new(len: usize) -> Self {
Self {
magic: Self::MAGIC,
version: Self::CURRENT_VERSION,
len: len.try_into().expect("metadata exceeds maximum length"),
}
}
/// Convert the header into its bytes representation.
pub fn into_bytes(self) -> [u8; 16] {
unsafe { mem::transmute(self) }
}
/// Parses the header and returns the length of the metadata following it.
pub fn parse(bytes: &[u8]) -> Result<usize, DeserializeError> {
if bytes.as_ptr() as usize % 16 != 0 {
return Err(DeserializeError::CorruptedBinary(
"misaligned metadata".to_string(),
));
}
let bytes: [u8; 16] = bytes
.get(..16)
.ok_or_else(|| {
DeserializeError::CorruptedBinary("invalid metadata header".to_string())
})?
.try_into()
.unwrap();
let header: Self = unsafe { mem::transmute(bytes) };
if header.magic != Self::MAGIC {
return Err(DeserializeError::Incompatible(
"The provided bytes were not serialized by Wasmer".to_string(),
));
}
if header.version != Self::CURRENT_VERSION {
return Err(DeserializeError::Incompatible(
"The provided bytes were serialized by an incompatible version of Wasmer"
.to_string(),
));
}
Ok(header.len as usize)
}
} }