Merge remote-tracking branch 'upstream/master' into refactoring_error_handling_lightbeam

This commit is contained in:
Patrick Ventuzelo
2019-12-10 11:24:46 +01:00
176 changed files with 3438 additions and 2883 deletions

View File

@@ -1,17 +1,13 @@
const child_process = require('child_process'); const child_process = require('child_process');
const toolchain = process.env.INPUT_TOOLCHAIN; const toolchain = process.env.INPUT_TOOLCHAIN;
for (var i = 0, keys = Object.keys(process.env), ii = keys.length; i < ii; i++) {
console.log(keys[i] + '=' + process.env[keys[i]]);
}
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
child_process.execSync(`curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=none --profile=minimal`); child_process.execSync(`curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=none --profile=minimal`);
const bindir = `${process.env.HOME}/.cargo/bin`; const bindir = `${process.env.HOME}/.cargo/bin`;
console.log(`::add-path::${bindir}`); console.log(`::add-path::${bindir}`);
process.env.PATH = `${process.env.PATH}:${bindir}`; process.env.PATH = `${process.env.PATH}:${bindir}`;
child_process.execFileSync('rustup', ['set', 'profile', 'minimal']);
} }
child_process.execFileSync('rustup', ['set', 'profile', 'minimal']);
child_process.execFileSync('rustup', ['update', toolchain, '--no-self-update']); child_process.execFileSync('rustup', ['update', toolchain, '--no-self-update']);
child_process.execFileSync('rustup', ['default', toolchain]); child_process.execFileSync('rustup', ['default', toolchain]);

View File

@@ -92,7 +92,6 @@ jobs:
name: Test name: Test
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
build: [stable, beta, nightly, windows, macos] build: [stable, beta, nightly, windows, macos]
include: include:
@@ -102,9 +101,11 @@ jobs:
- build: beta - build: beta
os: ubuntu-latest os: ubuntu-latest
rust: beta rust: beta
# FIXME need to wait for rust-lang/rust#67065 to get into nightlies,
# and then this can be updated to `nightly` again.
- build: nightly - build: nightly
os: ubuntu-latest os: ubuntu-latest
rust: nightly rust: nightly-2019-12-03
- build: macos - build: macos
os: macos-latest os: macos-latest
rust: stable rust: stable
@@ -163,7 +164,6 @@ jobs:
name: Python Wheel name: Python Wheel
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
@@ -260,7 +260,6 @@ jobs:
name: Build wasmtime name: Build wasmtime
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
@@ -328,7 +327,26 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] build: [linux-debug, linux-release, macos-debug, macos-release, windows-debug, windows-release]
include:
- build: linux-debug
os: ubuntu-latest
config: debug
- build: linux-release
os: ubuntu-latest
config: release
- build: macos-debug
os: macos-latest
config: debug
- build: macos-release
os: macos-latest
config: release
- build: windows-debug
os: windows-latest
config: debug
- build: windows-release
os: windows-latest
config: release
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
with: with:
@@ -339,12 +357,14 @@ jobs:
- uses: actions/setup-dotnet@v1 - uses: actions/setup-dotnet@v1
with: with:
dotnet-version: '3.0.101' dotnet-version: '3.0.101'
- run: | - name: Test
run: |
cd crates/misc/dotnet/tests cd crates/misc/dotnet/tests
dotnet test dotnet test -c ${{ matrix.config }}
- run: | - name: Create package
run: |
cd crates/misc/dotnet/src cd crates/misc/dotnet/src
dotnet pack dotnet pack -c ${{ matrix.config }}
if: matrix.os == 'macos-latest' # Currently the pack target only supports macOS if: matrix.os == 'macos-latest' # Currently the pack target only supports macOS
# Consumes all published artifacts from all the previous build steps, creates # Consumes all published artifacts from all the previous build steps, creates

View File

@@ -15,10 +15,6 @@ publish = false
[dependencies] [dependencies]
# Enable all supported architectures by default. # Enable all supported architectures by default.
cranelift-codegen = { version = "0.50.0", features = ["enable-serde", "all-arch"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
cranelift-native = "0.50.0"
wasmtime = { path = "crates/api" } wasmtime = { path = "crates/api" }
wasmtime-debug = { path = "crates/debug" } wasmtime-debug = { path = "crates/debug" }
wasmtime-environ = { path = "crates/environ" } wasmtime-environ = { path = "crates/environ" }

View File

@@ -13,15 +13,10 @@ name = "wasmtime"
crate-type = ["lib", "staticlib", "cdylib"] crate-type = ["lib", "staticlib", "cdylib"]
[dependencies] [dependencies]
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-native = "0.50.0"
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
cranelift-frontend = "0.50.0"
wasmtime-runtime = { path = "../runtime" } wasmtime-runtime = { path = "../runtime" }
wasmtime-environ = { path = "../environ" } wasmtime-environ = { path = "../environ" }
wasmtime-jit = { path = "../jit" } wasmtime-jit = { path = "../jit" }
wasmparser = { version = "0.39.2", default-features = false } wasmparser = { version = "0.44.0", default-features = false }
target-lexicon = { version = "0.9.0", default-features = false } target-lexicon = { version = "0.9.0", default-features = false }
anyhow = "1.0.19" anyhow = "1.0.19"
thiserror = "1.0.4" thiserror = "1.0.4"

View File

@@ -51,7 +51,7 @@ macro_rules! call {
($func:expr, $($p:expr),*) => { ($func:expr, $($p:expr),*) => {
match $func.borrow().call(&[$($p.into()),*]) { match $func.borrow().call(&[$($p.into()),*]) {
Ok(result) => { Ok(result) => {
let result: i32 = result[0].clone().into(); let result: i32 = result[0].unwrap_i32();
result result
} }
Err(_) => { bail!("> Error on result, expected return"); } Err(_) => { bail!("> Error on result, expected return"); }
@@ -151,7 +151,7 @@ fn main() -> Result<(), Error> {
// Create stand-alone memory. // Create stand-alone memory.
// TODO(wasm+): Once Wasm allows multiple memories, turn this into import. // TODO(wasm+): Once Wasm allows multiple memories, turn this into import.
println!("Creating stand-alone memory..."); println!("Creating stand-alone memory...");
let memorytype = MemoryType::new(Limits::new(5, 5)); let memorytype = MemoryType::new(Limits::new(5, Some(5)));
let mut memory2 = Memory::new(&store, memorytype); let mut memory2 = Memory::new(&store, memorytype);
check!(memory2.size(), 5u32); check!(memory2.size(), 5u32);
check!(memory2.grow(1), false); check!(memory2.grow(1), false);

View File

@@ -9,10 +9,10 @@ struct Callback;
impl Callable for Callback { impl Callable for Callback {
fn call(&self, args: &[Val], results: &mut [Val]) -> Result<(), HostRef<Trap>> { fn call(&self, args: &[Val], results: &mut [Val]) -> Result<(), HostRef<Trap>> {
println!("Calling back..."); println!("Calling back...");
println!("> {} {}", args[0].i32(), args[1].i64()); println!("> {} {}", args[0].unwrap_i32(), args[1].unwrap_i64());
results[0] = Val::I64(args[1].i64() + 1); results[0] = Val::I64(args[1].unwrap_i64() + 1);
results[1] = Val::I32(args[0].i32() + 1); results[1] = Val::I32(args[0].unwrap_i32() + 1);
Ok(()) Ok(())
} }
} }
@@ -88,10 +88,10 @@ fn main() -> Result<()> {
.map_err(|e| format_err!("> Error calling g! {:?}", e))?; .map_err(|e| format_err!("> Error calling g! {:?}", e))?;
println!("Printing result..."); println!("Printing result...");
println!("> {} {}", results[0].i64(), results[1].i32()); println!("> {} {}", results[0].unwrap_i64(), results[1].unwrap_i32());
debug_assert_eq!(results[0].i64(), 4); debug_assert_eq!(results[0].unwrap_i64(), 4);
debug_assert_eq!(results[1].i32(), 2); debug_assert_eq!(results[1].unwrap_i32(), 2);
// Call `$round_trip_many`. // Call `$round_trip_many`.
println!("Calling export \"round_trip_many\"..."); println!("Calling export \"round_trip_many\"...");
@@ -115,7 +115,7 @@ fn main() -> Result<()> {
println!("Printing result..."); println!("Printing result...");
print!(">"); print!(">");
for r in results.iter() { for r in results.iter() {
print!(" {}", r.i64()); print!(" {}", r.unwrap_i64());
} }
println!(); println!();

View File

@@ -1,4 +1,3 @@
use crate::data_structures::ir;
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use crate::runtime::Store; use crate::runtime::Store;
use crate::trampoline::{generate_func_export, take_api_trap}; use crate::trampoline::{generate_func_export, take_api_trap};
@@ -6,6 +5,7 @@ use crate::trap::Trap;
use crate::types::FuncType; use crate::types::FuncType;
use crate::values::Val; use crate::values::Val;
use std::rc::Rc; use std::rc::Rc;
use wasmtime_environ::ir;
use wasmtime_jit::InstanceHandle; use wasmtime_jit::InstanceHandle;
use wasmtime_runtime::Export; use wasmtime_runtime::Export;

View File

@@ -1,9 +1,8 @@
use crate::data_structures::native_isa_builder;
use crate::Config; use crate::Config;
use std::cell::{RefCell, RefMut}; use std::cell::{RefCell, RefMut};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::rc::Rc; use std::rc::Rc;
use wasmtime_jit::{Compiler, Features}; use wasmtime_jit::{native, Compiler, Features};
#[derive(Clone)] #[derive(Clone)]
pub struct Context { pub struct Context {
@@ -14,8 +13,7 @@ pub struct Context {
impl Context { impl Context {
pub fn new(config: &Config) -> Context { pub fn new(config: &Config) -> Context {
let isa_builder = native_isa_builder(); let isa = native::builder().finish(config.flags.clone());
let isa = isa_builder.finish(config.flags.clone());
Context::new_with_compiler(config, Compiler::new(isa, config.strategy)) Context::new_with_compiler(config, Compiler::new(isa, config.strategy))
} }

View File

@@ -1,26 +0,0 @@
pub(crate) mod ir {
pub(crate) use cranelift_codegen::ir::{types, AbiParam, ArgumentPurpose, Signature, Type};
}
pub(crate) mod settings {
pub(crate) use cranelift_codegen::settings::{builder, Flags};
}
pub(crate) use cranelift_codegen::isa::CallConv;
pub(crate) use cranelift_entity::{EntityRef, PrimaryMap};
pub(crate) mod wasm {
pub(crate) use cranelift_wasm::{
DefinedFuncIndex, DefinedTableIndex, FuncIndex, Global, GlobalInit, Memory, Table,
TableElementType,
};
}
pub(crate) fn native_isa_builder() -> cranelift_codegen::isa::Builder {
cranelift_native::builder().expect("host machine is not a supported target")
}
pub(crate) fn native_isa_call_conv() -> CallConv {
use target_lexicon::HOST;
CallConv::triple_default(&HOST)
}

View File

@@ -1,5 +1,4 @@
use crate::callable::{Callable, NativeCallable, WasmtimeFn, WrappedCallable}; use crate::callable::{Callable, NativeCallable, WasmtimeFn, WrappedCallable};
use crate::data_structures::wasm;
use crate::r#ref::{AnyRef, HostRef}; use crate::r#ref::{AnyRef, HostRef};
use crate::runtime::Store; use crate::runtime::Store;
use crate::trampoline::{generate_global_export, generate_memory_export, generate_table_export}; use crate::trampoline::{generate_global_export, generate_memory_export, generate_table_export};
@@ -9,6 +8,7 @@ use crate::values::{from_checked_anyfunc, into_checked_anyfunc, Val};
use std::fmt; use std::fmt;
use std::rc::Rc; use std::rc::Rc;
use std::slice; use std::slice;
use wasmtime_environ::wasm;
use wasmtime_runtime::InstanceHandle; use wasmtime_runtime::InstanceHandle;
// Externals // Externals
@@ -49,10 +49,10 @@ impl Extern {
pub fn r#type(&self) -> ExternType { pub fn r#type(&self) -> ExternType {
match self { match self {
Extern::Func(ft) => ExternType::ExternFunc(ft.borrow().r#type().clone()), Extern::Func(ft) => ExternType::Func(ft.borrow().r#type().clone()),
Extern::Memory(ft) => ExternType::ExternMemory(ft.borrow().r#type().clone()), Extern::Memory(ft) => ExternType::Memory(ft.borrow().r#type().clone()),
Extern::Table(tt) => ExternType::ExternTable(tt.borrow().r#type().clone()), Extern::Table(tt) => ExternType::Table(tt.borrow().r#type().clone()),
Extern::Global(gt) => ExternType::ExternGlobal(gt.borrow().r#type().clone()), Extern::Global(gt) => ExternType::Global(gt.borrow().r#type().clone()),
} }
} }
@@ -148,7 +148,7 @@ impl Func {
} }
pub fn call(&self, params: &[Val]) -> Result<Box<[Val]>, HostRef<Trap>> { pub fn call(&self, params: &[Val]) -> Result<Box<[Val]>, HostRef<Trap>> {
let mut results = vec![Val::default(); self.result_arity()]; let mut results = vec![Val::null(); self.result_arity()];
self.callable.call(params, &mut results)?; self.callable.call(params, &mut results)?;
Ok(results.into_boxed_slice()) Ok(results.into_boxed_slice())
} }
@@ -215,8 +215,8 @@ impl Global {
match self.r#type().content() { match self.r#type().content() {
ValType::I32 => Val::from(*definition.as_i32()), ValType::I32 => Val::from(*definition.as_i32()),
ValType::I64 => Val::from(*definition.as_i64()), ValType::I64 => Val::from(*definition.as_i64()),
ValType::F32 => Val::from_f32_bits(*definition.as_u32()), ValType::F32 => Val::F32(*definition.as_u32()),
ValType::F64 => Val::from_f64_bits(*definition.as_u64()), ValType::F64 => Val::F64(*definition.as_u64()),
_ => unimplemented!("Global::get for {:?}", self.r#type().content()), _ => unimplemented!("Global::get for {:?}", self.r#type().content()),
} }
} }

View File

@@ -4,7 +4,7 @@ use crate::module::Module;
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use crate::runtime::Store; use crate::runtime::Store;
use crate::trampoline::take_api_trap; use crate::trampoline::take_api_trap;
use crate::types::{ExportType, ExternType, Name}; use crate::types::{ExportType, ExternType};
use anyhow::Result; use anyhow::Result;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@@ -122,7 +122,7 @@ impl Instance {
.exports() .exports()
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, e)| e.name().as_str() == name)?; .find(|(_, e)| e.name() == name)?;
Some(&self.exports()[i]) Some(&self.exports()[i])
} }
@@ -141,7 +141,7 @@ impl Instance {
let _ = store.borrow_mut().register_wasmtime_signature(signature); let _ = store.borrow_mut().register_wasmtime_signature(signature);
} }
let extern_type = ExternType::from_wasmtime_export(&export); let extern_type = ExternType::from_wasmtime_export(&export);
exports_types.push(ExportType::new(Name::new(name), extern_type)); exports_types.push(ExportType::new(name, extern_type));
exports.push(Extern::from_wasmtime_export( exports.push(Extern::from_wasmtime_export(
store, store,
instance_handle.clone(), instance_handle.clone(),

View File

@@ -1,10 +1,15 @@
//! Wasmtime embed API. Based on wasm-c-api. //! Wasmtime's embedding API
//!
//! This crate contains a high-level API used to interact with WebAssembly
//! modules. The API here is intended to mirror the proposed [WebAssembly C
//! API](https://github.com/WebAssembly/wasm-c-api), with small extensions here
//! and there to implement Rust idioms. This crate also defines the actual C API
//! itself for consumption from other languages.
#![allow(improper_ctypes)] #![allow(improper_ctypes)]
mod callable; mod callable;
mod context; mod context;
mod data_structures;
mod externals; mod externals;
mod instance; mod instance;
mod module; mod module;

View File

@@ -12,10 +12,7 @@ use wasmparser::{
fn into_memory_type(mt: wasmparser::MemoryType) -> MemoryType { fn into_memory_type(mt: wasmparser::MemoryType) -> MemoryType {
assert!(!mt.shared); assert!(!mt.shared);
MemoryType::new(Limits::new( MemoryType::new(Limits::new(mt.limits.initial, mt.limits.maximum))
mt.limits.initial,
mt.limits.maximum.unwrap_or(std::u32::MAX),
))
} }
fn into_global_type(gt: &wasmparser::GlobalType) -> GlobalType { fn into_global_type(gt: &wasmparser::GlobalType) -> GlobalType {
@@ -53,10 +50,7 @@ fn into_table_type(tt: wasmparser::TableType) -> TableType {
tt.element_type == wasmparser::Type::AnyFunc || tt.element_type == wasmparser::Type::AnyRef tt.element_type == wasmparser::Type::AnyFunc || tt.element_type == wasmparser::Type::AnyRef
); );
let ty = into_valtype(&tt.element_type); let ty = into_valtype(&tt.element_type);
let limits = Limits::new( let limits = Limits::new(tt.limits.initial, tt.limits.maximum);
tt.limits.initial,
tt.limits.maximum.unwrap_or(std::u32::MAX),
);
TableType::new(ty, limits) TableType::new(ty, limits)
} }
@@ -112,31 +106,29 @@ fn read_imports_and_exports(binary: &[u8]) -> Result<(Box<[ImportType]>, Box<[Ex
imports.reserve_exact(section.get_count() as usize); imports.reserve_exact(section.get_count() as usize);
for entry in section { for entry in section {
let entry = entry?; let entry = entry?;
let module = String::from(entry.module).into();
let name = String::from(entry.field).into();
let r#type = match entry.ty { let r#type = match entry.ty {
ImportSectionEntryType::Function(index) => { ImportSectionEntryType::Function(index) => {
func_sig.push(index); func_sig.push(index);
let sig = &sigs[index as usize]; let sig = &sigs[index as usize];
ExternType::ExternFunc(sig.clone()) ExternType::Func(sig.clone())
} }
ImportSectionEntryType::Table(tt) => { ImportSectionEntryType::Table(tt) => {
let table = into_table_type(tt); let table = into_table_type(tt);
tables.push(table.clone()); tables.push(table.clone());
ExternType::ExternTable(table) ExternType::Table(table)
} }
ImportSectionEntryType::Memory(mt) => { ImportSectionEntryType::Memory(mt) => {
let memory = into_memory_type(mt); let memory = into_memory_type(mt);
memories.push(memory.clone()); memories.push(memory.clone());
ExternType::ExternMemory(memory) ExternType::Memory(memory)
} }
ImportSectionEntryType::Global(gt) => { ImportSectionEntryType::Global(gt) => {
let global = into_global_type(&gt); let global = into_global_type(&gt);
globals.push(global.clone()); globals.push(global.clone());
ExternType::ExternGlobal(global) ExternType::Global(global)
} }
}; };
imports.push(ImportType::new(module, name, r#type)); imports.push(ImportType::new(entry.module, entry.field, r#type));
} }
} }
SectionCode::Export => { SectionCode::Export => {
@@ -144,24 +136,23 @@ fn read_imports_and_exports(binary: &[u8]) -> Result<(Box<[ImportType]>, Box<[Ex
exports.reserve_exact(section.get_count() as usize); exports.reserve_exact(section.get_count() as usize);
for entry in section { for entry in section {
let entry = entry?; let entry = entry?;
let name = String::from(entry.field).into();
let r#type = match entry.kind { let r#type = match entry.kind {
ExternalKind::Function => { ExternalKind::Function => {
let sig_index = func_sig[entry.index as usize] as usize; let sig_index = func_sig[entry.index as usize] as usize;
let sig = &sigs[sig_index]; let sig = &sigs[sig_index];
ExternType::ExternFunc(sig.clone()) ExternType::Func(sig.clone())
} }
ExternalKind::Table => { ExternalKind::Table => {
ExternType::ExternTable(tables[entry.index as usize].clone()) ExternType::Table(tables[entry.index as usize].clone())
} }
ExternalKind::Memory => { ExternalKind::Memory => {
ExternType::ExternMemory(memories[entry.index as usize].clone()) ExternType::Memory(memories[entry.index as usize].clone())
} }
ExternalKind::Global => { ExternalKind::Global => {
ExternType::ExternGlobal(globals[entry.index as usize].clone()) ExternType::Global(globals[entry.index as usize].clone())
} }
}; };
exports.push(ExportType::new(name, r#type)); exports.push(ExportType::new(entry.field, r#type));
} }
} }
_ => { _ => {

View File

@@ -1,9 +1,9 @@
use crate::context::Context; use crate::context::Context;
use crate::data_structures::{ir, settings};
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc; use std::rc::Rc;
use wasmtime_environ::{ir, settings};
use wasmtime_jit::{CompilationStrategy, Features}; use wasmtime_jit::{CompilationStrategy, Features};
// Runtime Environment // Runtime Environment

View File

@@ -1,13 +1,13 @@
//! Support for a calling of an imported function. //! Support for a calling of an imported function.
use crate::data_structures::wasm::DefinedFuncIndex;
use crate::data_structures::PrimaryMap;
use crate::runtime::Store; use crate::runtime::Store;
use anyhow::Result; use anyhow::Result;
use std::any::Any; use std::any::Any;
use std::cell::{RefCell, RefMut}; use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::rc::Rc; use std::rc::Rc;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::wasm::DefinedFuncIndex;
use wasmtime_environ::Module; use wasmtime_environ::Module;
use wasmtime_runtime::{Imports, InstanceHandle, VMFunctionBody}; use wasmtime_runtime::{Imports, InstanceHandle, VMFunctionBody};

View File

@@ -1,21 +1,25 @@
//! Support for a calling of an imported function. //! Support for a calling of an imported function.
use super::create_handle::create_handle; use super::create_handle::create_handle;
use super::ir::{ExternalName, Function, InstBuilder, MemFlags, StackSlotData, StackSlotKind};
use super::trap::{record_api_trap, TrapSink, API_TRAP_CODE}; use super::trap::{record_api_trap, TrapSink, API_TRAP_CODE};
use super::{binemit, pretty_error, TargetIsa};
use super::{Context, FunctionBuilder, FunctionBuilderContext};
use crate::data_structures::ir::{self, types};
use crate::data_structures::wasm::{DefinedFuncIndex, FuncIndex};
use crate::data_structures::{native_isa_builder, settings, EntityRef, PrimaryMap};
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use crate::{Callable, FuncType, Store, Val}; use crate::{Callable, FuncType, Store, Val};
use anyhow::Result; use anyhow::Result;
use std::cmp; use std::cmp;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::rc::Rc; use std::rc::Rc;
use wasmtime_environ::{CompiledFunction, Export, Module, TrapInformation}; use wasmtime_environ::entity::{EntityRef, PrimaryMap};
use wasmtime_jit::CodeMemory; use wasmtime_environ::ir::types;
use wasmtime_environ::isa::TargetIsa;
use wasmtime_environ::wasm::{DefinedFuncIndex, FuncIndex};
use wasmtime_environ::{ir, settings, CompiledFunction, Export, Module, TrapInformation};
use wasmtime_jit::trampoline::ir::{
ExternalName, Function, InstBuilder, MemFlags, StackSlotData, StackSlotKind,
};
use wasmtime_jit::trampoline::{
binemit, pretty_error, Context, FunctionBuilder, FunctionBuilderContext,
};
use wasmtime_jit::{native, CodeMemory};
use wasmtime_runtime::{ use wasmtime_runtime::{
get_mut_trap_registry, InstanceHandle, TrapRegistrationGuard, VMContext, VMFunctionBody, get_mut_trap_registry, InstanceHandle, TrapRegistrationGuard, VMContext, VMFunctionBody,
}; };
@@ -76,7 +80,7 @@ unsafe extern "C" fn stub_fn(vmctx: *mut VMContext, call_id: u32, values_vec: *m
(args, signature.returns.len()) (args, signature.returns.len())
}; };
let mut returns = vec![Val::default(); returns_len]; let mut returns = vec![Val::null(); returns_len];
let func = &instance let func = &instance
.host_state() .host_state()
.downcast_mut::<TrampolineState>() .downcast_mut::<TrampolineState>()
@@ -232,7 +236,7 @@ pub fn create_handle_with_function(
let sig = ft.get_wasmtime_signature().clone(); let sig = ft.get_wasmtime_signature().clone();
let isa = { let isa = {
let isa_builder = native_isa_builder(); let isa_builder = native::builder();
let flag_builder = settings::builder(); let flag_builder = settings::builder();
isa_builder.finish(settings::Flags::new(flag_builder)) isa_builder.finish(settings::Flags::new(flag_builder))
}; };

View File

@@ -1,8 +1,8 @@
use super::create_handle::create_handle; use super::create_handle::create_handle;
use crate::data_structures::{wasm, PrimaryMap};
use crate::{GlobalType, Mutability, Val}; use crate::{GlobalType, Mutability, Val};
use anyhow::Result; use anyhow::Result;
use wasmtime_environ::Module; use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::{wasm, Module};
use wasmtime_runtime::{InstanceHandle, VMGlobalDefinition}; use wasmtime_runtime::{InstanceHandle, VMGlobalDefinition};
#[allow(dead_code)] #[allow(dead_code)]

View File

@@ -1,8 +1,8 @@
use super::create_handle::create_handle; use super::create_handle::create_handle;
use crate::data_structures::{wasm, PrimaryMap};
use crate::MemoryType; use crate::MemoryType;
use anyhow::Result; use anyhow::Result;
use wasmtime_environ::Module; use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::{wasm, Module};
use wasmtime_runtime::InstanceHandle; use wasmtime_runtime::InstanceHandle;
#[allow(dead_code)] #[allow(dead_code)]
@@ -12,11 +12,7 @@ pub fn create_handle_with_memory(memory: &MemoryType) -> Result<InstanceHandle>
let memory = wasm::Memory { let memory = wasm::Memory {
minimum: memory.limits().min(), minimum: memory.limits().min(),
maximum: if memory.limits().max() == std::u32::MAX { maximum: memory.limits().max(),
None
} else {
Some(memory.limits().max())
},
shared: false, // TODO shared: false, // TODO
}; };
let tunable = Default::default(); let tunable = Default::default();

View File

@@ -51,61 +51,3 @@ pub fn generate_table_export(
let export = instance.lookup("table").expect("table export"); let export = instance.lookup("table").expect("table export");
Ok((instance, export)) Ok((instance, export))
} }
pub(crate) use cranelift_codegen::print_errors::pretty_error;
pub(crate) mod binemit {
pub(crate) use cranelift_codegen::binemit::{CodeOffset, NullStackmapSink, TrapSink};
pub use cranelift_codegen::{binemit, ir};
/// We don't expect trampoline compilation to produce any relocations, so
/// this `RelocSink` just asserts that it doesn't recieve any.
pub(crate) struct TrampolineRelocSink {}
impl binemit::RelocSink for TrampolineRelocSink {
fn reloc_ebb(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_ebb_offset: binemit::CodeOffset,
) {
panic!("trampoline compilation should not produce ebb relocs");
}
fn reloc_external(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_name: &ir::ExternalName,
_addend: binemit::Addend,
) {
panic!("trampoline compilation should not produce external symbol relocs");
}
fn reloc_constant(
&mut self,
_code_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_constant_offset: ir::ConstantOffset,
) {
panic!("trampoline compilation should not produce constant relocs");
}
fn reloc_jt(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_jt: ir::JumpTable,
) {
panic!("trampoline compilation should not produce jump table relocs");
}
}
}
pub(crate) mod ir {
pub(crate) use cranelift_codegen::ir::{
ExternalName, Function, InstBuilder, MemFlags, SourceLoc, StackSlotData, StackSlotKind,
TrapCode,
};
}
pub(crate) use cranelift_codegen::isa::TargetIsa;
pub(crate) use cranelift_codegen::Context;
pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};

View File

@@ -1,8 +1,8 @@
use super::create_handle::create_handle; use super::create_handle::create_handle;
use crate::data_structures::{wasm, PrimaryMap};
use crate::{TableType, ValType}; use crate::{TableType, ValType};
use anyhow::Result; use anyhow::Result;
use wasmtime_environ::Module; use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::{wasm, Module};
use wasmtime_runtime::InstanceHandle; use wasmtime_runtime::InstanceHandle;
pub fn create_handle_with_table(table: &TableType) -> Result<InstanceHandle> { pub fn create_handle_with_table(table: &TableType) -> Result<InstanceHandle> {
@@ -10,11 +10,7 @@ pub fn create_handle_with_table(table: &TableType) -> Result<InstanceHandle> {
let table = wasm::Table { let table = wasm::Table {
minimum: table.limits().min(), minimum: table.limits().min(),
maximum: if table.limits().max() == std::u32::MAX { maximum: table.limits().max(),
None
} else {
Some(table.limits().max())
},
ty: match table.element() { ty: match table.element() {
ValType::FuncRef => wasm::TableElementType::Func, ValType::FuncRef => wasm::TableElementType::Func,
_ => wasm::TableElementType::Val(table.element().get_wasmtime_type()), _ => wasm::TableElementType::Val(table.element().get_wasmtime_type()),

View File

@@ -1,10 +1,10 @@
use std::cell::Cell; use std::cell::Cell;
use super::binemit;
use super::ir::{SourceLoc, TrapCode};
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use crate::Trap; use crate::Trap;
use wasmtime_environ::ir::{SourceLoc, TrapCode};
use wasmtime_environ::TrapInformation; use wasmtime_environ::TrapInformation;
use wasmtime_jit::trampoline::binemit;
// Randomly selected user TrapCode magic number 13. // Randomly selected user TrapCode magic number 13.
pub const API_TRAP_CODE: TrapCode = TrapCode::User(13); pub const API_TRAP_CODE: TrapCode = TrapCode::User(13);

View File

@@ -1,38 +1,46 @@
use crate::data_structures::{ir, wasm}; use wasmtime_environ::{ir, wasm};
// Type Representations // Type Representations
// Type attributes // Type attributes
/// Indicator of whether a global is mutable or not
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Mutability { pub enum Mutability {
/// The global is constant and its value does not change
Const, Const,
/// The value of the global can change over time
Var, Var,
} }
/// Limits of tables/memories where the units of the limits are defined by the
/// table/memory types.
///
/// A minimum is always available but the maximum may not be present.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Limits { pub struct Limits {
min: u32, min: u32,
max: u32, max: Option<u32>,
} }
impl Limits { impl Limits {
pub fn new(min: u32, max: u32) -> Limits { /// Creates a new set of limits with the minimum and maximum both specified.
pub fn new(min: u32, max: Option<u32>) -> Limits {
Limits { min, max } Limits { min, max }
} }
/// Creates a new `Limits` with the `min` specified and no maximum specified.
pub fn at_least(min: u32) -> Limits { pub fn at_least(min: u32) -> Limits {
Limits { Limits::new(min, None)
min,
max: ::std::u32::MAX,
}
} }
/// Returns the minimum amount for these limits.
pub fn min(&self) -> u32 { pub fn min(&self) -> u32 {
self.min self.min
} }
pub fn max(&self) -> u32 { /// Returs the maximum amount for these limits, if specified.
pub fn max(&self) -> Option<u32> {
self.max self.max
} }
} }
@@ -90,52 +98,63 @@ impl ValType {
// External Types // External Types
/// A list of all possible types which can be externally referenced from a
/// WebAssembly module.
///
/// This list can be found in [`ImportType`] or [`ExportType`], so these types
/// can either be imported or exported.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ExternType { pub enum ExternType {
ExternFunc(FuncType), Func(FuncType),
ExternGlobal(GlobalType), Global(GlobalType),
ExternTable(TableType), Table(TableType),
ExternMemory(MemoryType), Memory(MemoryType),
}
macro_rules! accessors {
($(($variant:ident($ty:ty) $get:ident $unwrap:ident))*) => ($(
/// Attempt to return the underlying type of this external type,
/// returning `None` if it is a different type.
pub fn $get(&self) -> Option<&$ty> {
if let ExternType::$variant(e) = self {
Some(e)
} else {
None
}
}
/// Returns the underlying descriptor of this [`ExternType`], panicking
/// if it is a different type.
///
/// # Panics
///
/// Panics if `self` is not of the right type.
pub fn $unwrap(&self) -> &$ty {
self.$get().expect(concat!("expected ", stringify!($ty)))
}
)*)
} }
impl ExternType { impl ExternType {
pub fn func(&self) -> &FuncType { accessors! {
match self { (Func(FuncType) func unwrap_func)
ExternType::ExternFunc(func) => func, (Global(GlobalType) global unwrap_global)
_ => panic!("ExternType::ExternFunc expected"), (Table(TableType) table unwrap_table)
} (Memory(MemoryType) memory unwrap_memory)
}
pub fn global(&self) -> &GlobalType {
match self {
ExternType::ExternGlobal(func) => func,
_ => panic!("ExternType::ExternGlobal expected"),
}
}
pub fn table(&self) -> &TableType {
match self {
ExternType::ExternTable(table) => table,
_ => panic!("ExternType::ExternTable expected"),
}
}
pub fn memory(&self) -> &MemoryType {
match self {
ExternType::ExternMemory(memory) => memory,
_ => panic!("ExternType::ExternMemory expected"),
}
} }
pub(crate) fn from_wasmtime_export(export: &wasmtime_runtime::Export) -> Self { pub(crate) fn from_wasmtime_export(export: &wasmtime_runtime::Export) -> Self {
match export { match export {
wasmtime_runtime::Export::Function { signature, .. } => { wasmtime_runtime::Export::Function { signature, .. } => {
ExternType::ExternFunc(FuncType::from_wasmtime_signature(signature.clone())) ExternType::Func(FuncType::from_wasmtime_signature(signature.clone()))
} }
wasmtime_runtime::Export::Memory { memory, .. } => { wasmtime_runtime::Export::Memory { memory, .. } => {
ExternType::ExternMemory(MemoryType::from_wasmtime_memory(&memory.memory)) ExternType::Memory(MemoryType::from_wasmtime_memory(&memory.memory))
} }
wasmtime_runtime::Export::Global { global, .. } => { wasmtime_runtime::Export::Global { global, .. } => {
ExternType::ExternGlobal(GlobalType::from_wasmtime_global(&global)) ExternType::Global(GlobalType::from_wasmtime_global(&global))
} }
wasmtime_runtime::Export::Table { table, .. } => { wasmtime_runtime::Export::Table { table, .. } => {
ExternType::ExternTable(TableType::from_wasmtime_table(&table.table)) ExternType::Table(TableType::from_wasmtime_table(&table.table))
} }
} }
} }
@@ -147,6 +166,9 @@ fn from_wasmtime_abiparam(param: &ir::AbiParam) -> ValType {
ValType::from_wasmtime_type(param.value_type) ValType::from_wasmtime_type(param.value_type)
} }
/// A descriptor for a function in a WebAssembly module.
///
/// WebAssembly functions can have 0 or more parameters and results.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FuncType { pub struct FuncType {
params: Box<[ValType]>, params: Box<[ValType]>,
@@ -155,10 +177,14 @@ pub struct FuncType {
} }
impl FuncType { impl FuncType {
/// Creates a new function descriptor from the given parameters and results.
///
/// The function descriptor returned will represent a function which takes
/// `params` as arguments and returns `results` when it is finished.
pub fn new(params: Box<[ValType]>, results: Box<[ValType]>) -> FuncType { pub fn new(params: Box<[ValType]>, results: Box<[ValType]>) -> FuncType {
use crate::data_structures::ir::{types, AbiParam, ArgumentPurpose, Signature}; use wasmtime_environ::ir::{types, AbiParam, ArgumentPurpose, Signature};
use crate::data_structures::native_isa_call_conv; use wasmtime_jit::native;
let call_conv = native_isa_call_conv(); let call_conv = native::call_conv();
let signature: Signature = { let signature: Signature = {
let mut params = params let mut params = params
.iter() .iter()
@@ -182,9 +208,13 @@ impl FuncType {
signature, signature,
} }
} }
/// Returns the list of parameter types for this function.
pub fn params(&self) -> &[ValType] { pub fn params(&self) -> &[ValType] {
&self.params &self.params
} }
/// Returns the list of result types for this function.
pub fn results(&self) -> &[ValType] { pub fn results(&self) -> &[ValType] {
&self.results &self.results
} }
@@ -215,6 +245,11 @@ impl FuncType {
// Global Types // Global Types
/// A WebAssembly global descriptor.
///
/// This type describes an instance of a global in a WebAssembly module. Globals
/// are local to an [`Instance`](crate::Instance) and are either immutable or
/// mutable.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct GlobalType { pub struct GlobalType {
content: ValType, content: ValType,
@@ -222,15 +257,21 @@ pub struct GlobalType {
} }
impl GlobalType { impl GlobalType {
/// Creates a new global descriptor of the specified `content` type and
/// whether or not it's mutable.
pub fn new(content: ValType, mutability: Mutability) -> GlobalType { pub fn new(content: ValType, mutability: Mutability) -> GlobalType {
GlobalType { GlobalType {
content, content,
mutability, mutability,
} }
} }
/// Returns the value type of this global descriptor.
pub fn content(&self) -> &ValType { pub fn content(&self) -> &ValType {
&self.content &self.content
} }
/// Returns whether or not this global is mutable.
pub fn mutability(&self) -> Mutability { pub fn mutability(&self) -> Mutability {
self.mutability self.mutability
} }
@@ -248,6 +289,11 @@ impl GlobalType {
// Table Types // Table Types
/// A descriptor for a table in a WebAssembly module.
///
/// Tables are contiguous chunks of a specific element, typically a `funcref` or
/// an `anyref`. The most common use for tables is a function table through
/// which `call_indirect` can invoke other functions.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TableType { pub struct TableType {
element: ValType, element: ValType,
@@ -255,12 +301,18 @@ pub struct TableType {
} }
impl TableType { impl TableType {
/// Creates a new table descriptor which will contain the specified
/// `element` and have the `limits` applied to its length.
pub fn new(element: ValType, limits: Limits) -> TableType { pub fn new(element: ValType, limits: Limits) -> TableType {
TableType { element, limits } TableType { element, limits }
} }
/// Returns the element value type of this table.
pub fn element(&self) -> &ValType { pub fn element(&self) -> &ValType {
&self.element &self.element
} }
/// Returns the limits, in units of elements, of this table.
pub fn limits(&self) -> &Limits { pub fn limits(&self) -> &Limits {
&self.limits &self.limits
} }
@@ -272,103 +324,113 @@ impl TableType {
false false
}); });
let ty = ValType::FuncRef; let ty = ValType::FuncRef;
let limits = Limits::new(table.minimum, table.maximum.unwrap_or(::std::u32::MAX)); let limits = Limits::new(table.minimum, table.maximum);
TableType::new(ty, limits) TableType::new(ty, limits)
} }
} }
// Memory Types // Memory Types
/// A descriptor for a WebAssembly memory type.
///
/// Memories are described in units of pages (64KB) and represent contiguous
/// chunks of addressable memory.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MemoryType { pub struct MemoryType {
limits: Limits, limits: Limits,
} }
impl MemoryType { impl MemoryType {
/// Creates a new descriptor for a WebAssembly memory given the specified
/// limits of the memory.
pub fn new(limits: Limits) -> MemoryType { pub fn new(limits: Limits) -> MemoryType {
MemoryType { limits } MemoryType { limits }
} }
/// Returns the limits (in pages) that are configured for this memory.
pub fn limits(&self) -> &Limits { pub fn limits(&self) -> &Limits {
&self.limits &self.limits
} }
pub(crate) fn from_wasmtime_memory(memory: &wasm::Memory) -> MemoryType { pub(crate) fn from_wasmtime_memory(memory: &wasm::Memory) -> MemoryType {
MemoryType::new(Limits::new( MemoryType::new(Limits::new(memory.minimum, memory.maximum))
memory.minimum,
memory.maximum.unwrap_or(::std::u32::MAX),
))
} }
} }
// Import Types // Import Types
#[derive(Debug, Clone)] /// A descriptor for an imported value into a wasm module.
pub struct Name(String); ///
/// This type is primarily accessed from the
impl Name { /// [`Module::imports`](crate::Module::imports) API. Each [`ImportType`]
pub fn new(value: &str) -> Self { /// describes an import into the wasm module with the module/name that it's
Name(value.to_owned()) /// imported from as well as the type of item that's being imported.
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<String> for Name {
fn from(s: String) -> Name {
Name(s)
}
}
impl ToString for Name {
fn to_string(&self) -> String {
self.0.to_owned()
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ImportType { pub struct ImportType {
module: Name, module: String,
name: Name, name: String,
r#type: ExternType, ty: ExternType,
} }
impl ImportType { impl ImportType {
pub fn new(module: Name, name: Name, r#type: ExternType) -> ImportType { /// Creates a new import descriptor which comes from `module` and `name` and
/// is of type `ty`.
pub fn new(module: &str, name: &str, ty: ExternType) -> ImportType {
ImportType { ImportType {
module, module: module.to_string(),
name, name: name.to_string(),
r#type, ty,
} }
} }
pub fn module(&self) -> &Name {
/// Returns the module name that this import is expected to come from.
pub fn module(&self) -> &str {
&self.module &self.module
} }
pub fn name(&self) -> &Name {
/// Returns the field name of the module that this import is expected to
/// come from.
pub fn name(&self) -> &str {
&self.name &self.name
} }
pub fn r#type(&self) -> &ExternType {
&self.r#type /// Returns the expected type of this import.
pub fn ty(&self) -> &ExternType {
&self.ty
} }
} }
// Export Types // Export Types
/// A descriptor for an exported WebAssembly value.
///
/// This type is primarily accessed from the
/// [`Module::exports`](crate::Module::exports) accessor and describes what
/// names are exported from a wasm module and the type of the item that is
/// exported.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ExportType { pub struct ExportType {
name: Name, name: String,
r#type: ExternType, ty: ExternType,
} }
impl ExportType { impl ExportType {
pub fn new(name: Name, r#type: ExternType) -> ExportType { /// Creates a new export which is exported with the given `name` and has the
ExportType { name, r#type } /// given `ty`.
pub fn new(name: &str, ty: ExternType) -> ExportType {
ExportType {
name: name.to_string(),
ty,
} }
pub fn name(&self) -> &Name { }
/// Returns the name by which this export is known by.
pub fn name(&self) -> &str {
&self.name &self.name
} }
pub fn r#type(&self) -> &ExternType {
&self.r#type /// Returns the type of this export.
pub fn ty(&self) -> &ExternType {
&self.ty
} }
} }

View File

@@ -1,26 +1,76 @@
use crate::data_structures::ir;
use crate::externals::Func; use crate::externals::Func;
use crate::r#ref::{AnyRef, HostRef}; use crate::r#ref::{AnyRef, HostRef};
use crate::runtime::Store; use crate::runtime::Store;
use crate::types::ValType; use crate::types::ValType;
use std::ptr; use std::ptr;
use wasmtime_environ::ir;
use wasmtime_jit::RuntimeValue; use wasmtime_jit::RuntimeValue;
/// Possible runtime values that a WebAssembly module can either consume or
/// produce.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Val { pub enum Val {
/// A 32-bit integer
I32(i32), I32(i32),
/// A 64-bit integer
I64(i64), I64(i64),
/// A 32-bit float.
///
/// Note that the raw bits of the float are stored here, and you can use
/// `f32::from_bits` to create an `f32` value.
F32(u32), F32(u32),
/// A 64-bit float.
///
/// Note that the raw bits of the float are stored here, and you can use
/// `f64::from_bits` to create an `f64` value.
F64(u64), F64(u64),
/// An `anyref` value which can hold opaque data to the wasm instance itself.
///
/// Note that this is a nullable value as well.
AnyRef(AnyRef), AnyRef(AnyRef),
/// A first-class reference to a WebAssembly function.
FuncRef(HostRef<Func>), FuncRef(HostRef<Func>),
/// A 128-bit number
V128([u8; 16]),
}
macro_rules! accessors {
($bind:ident $(($variant:ident($ty:ty) $get:ident $unwrap:ident $cvt:expr))*) => ($(
/// Attempt to access the underlying value of this `Val`, returning
/// `None` if it is not the correct type.
pub fn $get(&self) -> Option<$ty> {
if let Val::$variant($bind) = self {
Some($cvt)
} else {
None
}
}
/// Returns the underlying value of this `Val`, panicking if it's the
/// wrong type.
///
/// # Panics
///
/// Panics if `self` is not of the right type.
pub fn $unwrap(&self) -> $ty {
self.$get().expect(concat!("expected ", stringify!($ty)))
}
)*)
} }
impl Val { impl Val {
pub fn default() -> Val { /// Returns a null `anyref` value.
pub fn null() -> Val {
Val::AnyRef(AnyRef::null()) Val::AnyRef(AnyRef::null())
} }
/// Returns the corresponding [`ValType`] for this `Val`.
pub fn r#type(&self) -> ValType { pub fn r#type(&self) -> ValType {
match self { match self {
Val::I32(_) => ValType::I32, Val::I32(_) => ValType::I32,
@@ -29,6 +79,7 @@ impl Val {
Val::F64(_) => ValType::F64, Val::F64(_) => ValType::F64,
Val::AnyRef(_) => ValType::AnyRef, Val::AnyRef(_) => ValType::AnyRef,
Val::FuncRef(_) => ValType::FuncRef, Val::FuncRef(_) => ValType::FuncRef,
Val::V128(_) => ValType::V128,
} }
} }
@@ -52,52 +103,36 @@ impl Val {
} }
} }
pub fn from_f32_bits(v: u32) -> Val { accessors! {
Val::F32(v) e
(I32(i32) i32 unwrap_i32 *e)
(I64(i64) i64 unwrap_i64 *e)
(F32(f32) f32 unwrap_f32 f32::from_bits(*e))
(F64(f64) f64 unwrap_f64 f64::from_bits(*e))
(FuncRef(&HostRef<Func>) funcref unwrap_funcref e)
(V128(&[u8; 16]) v128 unwrap_v128 e)
} }
pub fn from_f64_bits(v: u64) -> Val { /// Attempt to access the underlying value of this `Val`, returning
Val::F64(v) /// `None` if it is not the correct type.
} ///
/// This will return `Some` for both the `AnyRef` and `FuncRef` types.
pub fn i32(&self) -> i32 { pub fn anyref(&self) -> Option<AnyRef> {
if let Val::I32(i) = self { match self {
*i Val::AnyRef(e) => Some(e.clone()),
} else { Val::FuncRef(e) => Some(e.anyref()),
panic!("Invalid conversion of {:?} to i32.", self); _ => None,
} }
} }
pub fn i64(&self) -> i64 { /// Returns the underlying value of this `Val`, panicking if it's the
if let Val::I64(i) = self { /// wrong type.
*i ///
} else { /// # Panics
panic!("Invalid conversion of {:?} to i64.", self); ///
} /// Panics if `self` is not of the right type.
} pub fn unwrap_anyref(&self) -> AnyRef {
self.anyref().expect("expected anyref")
pub fn f32(&self) -> f32 {
RuntimeValue::F32(self.f32_bits()).unwrap_f32()
}
pub fn f64(&self) -> f64 {
RuntimeValue::F64(self.f64_bits()).unwrap_f64()
}
pub fn f32_bits(&self) -> u32 {
if let Val::F32(i) = self {
*i
} else {
panic!("Invalid conversion of {:?} to f32.", self);
}
}
pub fn f64_bits(&self) -> u64 {
if let Val::F64(i) = self {
*i
} else {
panic!("Invalid conversion of {:?} to f64.", self);
}
} }
} }
@@ -125,30 +160,6 @@ impl From<f64> for Val {
} }
} }
impl Into<i32> for Val {
fn into(self) -> i32 {
self.i32()
}
}
impl Into<i64> for Val {
fn into(self) -> i64 {
self.i64()
}
}
impl Into<f32> for Val {
fn into(self) -> f32 {
self.f32()
}
}
impl Into<f64> for Val {
fn into(self) -> f64 {
self.f64()
}
}
impl From<AnyRef> for Val { impl From<AnyRef> for Val {
fn from(val: AnyRef) -> Val { fn from(val: AnyRef) -> Val {
match &val { match &val {
@@ -170,16 +181,6 @@ impl From<HostRef<Func>> for Val {
} }
} }
impl Into<AnyRef> for Val {
fn into(self) -> AnyRef {
match self {
Val::AnyRef(r) => r,
Val::FuncRef(f) => f.anyref(),
_ => panic!("Invalid conversion of {:?} to anyref.", self),
}
}
}
impl From<RuntimeValue> for Val { impl From<RuntimeValue> for Val {
fn from(rv: RuntimeValue) -> Self { fn from(rv: RuntimeValue) -> Self {
match rv { match rv {
@@ -187,23 +188,7 @@ impl From<RuntimeValue> for Val {
RuntimeValue::I64(i) => Val::I64(i), RuntimeValue::I64(i) => Val::I64(i),
RuntimeValue::F32(u) => Val::F32(u), RuntimeValue::F32(u) => Val::F32(u),
RuntimeValue::F64(u) => Val::F64(u), RuntimeValue::F64(u) => Val::F64(u),
x => { RuntimeValue::V128(u) => Val::V128(u),
panic!("unsupported {:?}", x);
}
}
}
}
impl Into<RuntimeValue> for Val {
fn into(self) -> RuntimeValue {
match self {
Val::I32(i) => RuntimeValue::I32(i),
Val::I64(i) => RuntimeValue::I64(i),
Val::F32(u) => RuntimeValue::F32(u),
Val::F64(u) => RuntimeValue::F64(u),
x => {
panic!("unsupported {:?}", x);
}
} }
} }
} }

View File

@@ -7,8 +7,8 @@
use super::{ use super::{
AnyRef, Callable, Engine, ExportType, Extern, ExternType, Func, FuncType, Global, GlobalType, AnyRef, Callable, Engine, ExportType, Extern, ExternType, Func, FuncType, Global, GlobalType,
HostInfo, HostRef, ImportType, Instance, Limits, Memory, MemoryType, Module, Name, Store, HostInfo, HostRef, ImportType, Instance, Limits, Memory, MemoryType, Module, Store, Table,
Table, TableType, Trap, Val, ValType, TableType, Trap, Val, ValType,
}; };
use std::rc::Rc; use std::rc::Rc;
use std::{mem, ptr, slice}; use std::{mem, ptr, slice};
@@ -56,7 +56,7 @@ macro_rules! declare_vec {
#[allow(dead_code)] #[allow(dead_code)]
fn as_slice(&self) -> &[$elem_ty] { fn as_slice(&self) -> &[$elem_ty] {
unsafe { slice::from_raw_parts(self.data as *const $elem_ty, self.size) } unsafe { slice::from_raw_parts(self.data, self.size) }
} }
} }
@@ -122,8 +122,8 @@ macro_rules! declare_vec {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn as_slice(&self) -> &[$elem_ty] { fn as_slice(&self) -> &[*mut $elem_ty] {
unsafe { slice::from_raw_parts(self.data as *const $elem_ty, self.size) } unsafe { slice::from_raw_parts(self.data, self.size) }
} }
} }
@@ -714,11 +714,8 @@ pub unsafe extern "C" fn wasm_module_delete(module: *mut wasm_module_t) {
} }
impl wasm_name_t { impl wasm_name_t {
fn from_name(name: &Name) -> wasm_name_t { fn from_name(name: &str) -> wasm_name_t {
let s = name.to_string(); name.to_string().into_bytes().into()
let mut buffer = Vec::new();
buffer.extend_from_slice(s.as_bytes());
buffer.into()
} }
} }
@@ -977,7 +974,7 @@ pub unsafe extern "C" fn wasm_importtype_type(
it: *const wasm_importtype_t, it: *const wasm_importtype_t,
) -> *const wasm_externtype_t { ) -> *const wasm_externtype_t {
let ty = Box::new(wasm_externtype_t { let ty = Box::new(wasm_externtype_t {
ty: (*it).ty.r#type().clone(), ty: (*it).ty.ty().clone(),
cache: wasm_externtype_t_type_cache::Empty, cache: wasm_externtype_t_type_cache::Empty,
}); });
Box::into_raw(ty) Box::into_raw(ty)
@@ -1004,7 +1001,7 @@ pub unsafe extern "C" fn wasm_exporttype_type(
if (*et).type_cache.is_none() { if (*et).type_cache.is_none() {
let et = (et as *mut wasm_exporttype_t).as_mut().unwrap(); let et = (et as *mut wasm_exporttype_t).as_mut().unwrap();
et.type_cache = Some(wasm_externtype_t { et.type_cache = Some(wasm_externtype_t {
ty: (*et).ty.r#type().clone(), ty: (*et).ty.ty().clone(),
cache: wasm_externtype_t_type_cache::Empty, cache: wasm_externtype_t_type_cache::Empty,
}); });
} }
@@ -1018,10 +1015,10 @@ pub unsafe extern "C" fn wasm_exporttype_vec_delete(et: *mut wasm_exporttype_vec
fn from_externtype(ty: &ExternType) -> wasm_externkind_t { fn from_externtype(ty: &ExternType) -> wasm_externkind_t {
match ty { match ty {
ExternType::ExternFunc(_) => 0, ExternType::Func(_) => 0,
ExternType::ExternGlobal(_) => 1, ExternType::Global(_) => 1,
ExternType::ExternTable(_) => 2, ExternType::Table(_) => 2,
ExternType::ExternMemory(_) => 3, ExternType::Memory(_) => 3,
} }
} }
@@ -1044,7 +1041,7 @@ pub unsafe extern "C" fn wasm_externtype_as_functype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_functype_t { ) -> *const wasm_functype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let functype = (*et).ty.func().clone(); let functype = (*et).ty.unwrap_func().clone();
let f = wasm_functype_t { let f = wasm_functype_t {
functype, functype,
params_cache: None, params_cache: None,
@@ -1064,7 +1061,7 @@ pub unsafe extern "C" fn wasm_externtype_as_globaltype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_globaltype_t { ) -> *const wasm_globaltype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let globaltype = (*et).ty.global().clone(); let globaltype = (*et).ty.unwrap_global().clone();
let g = wasm_globaltype_t { let g = wasm_globaltype_t {
globaltype, globaltype,
content_cache: None, content_cache: None,
@@ -1083,7 +1080,7 @@ pub unsafe extern "C" fn wasm_externtype_as_tabletype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_tabletype_t { ) -> *const wasm_tabletype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let tabletype = (*et).ty.table().clone(); let tabletype = (*et).ty.unwrap_table().clone();
let t = wasm_tabletype_t { let t = wasm_tabletype_t {
tabletype, tabletype,
element_cache: None, element_cache: None,
@@ -1103,7 +1100,7 @@ pub unsafe extern "C" fn wasm_externtype_as_memorytype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_memorytype_t { ) -> *const wasm_memorytype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let memorytype = (*et).ty.memory().clone(); let memorytype = (*et).ty.unwrap_memory().clone();
let m = wasm_memorytype_t { let m = wasm_memorytype_t {
memorytype, memorytype,
limits_cache: None, limits_cache: None,
@@ -1210,7 +1207,7 @@ pub unsafe extern "C" fn wasm_memorytype_limits(
let limits = (*mt).memorytype.limits(); let limits = (*mt).memorytype.limits();
mt.limits_cache = Some(wasm_limits_t { mt.limits_cache = Some(wasm_limits_t {
min: limits.min(), min: limits.min(),
max: limits.max(), max: limits.max().unwrap_or(u32::max_value()),
}); });
} }
(*mt).limits_cache.as_ref().unwrap() (*mt).limits_cache.as_ref().unwrap()
@@ -1270,7 +1267,7 @@ pub unsafe extern "C" fn wasm_tabletype_limits(
let limits = (*tt).tabletype.limits(); let limits = (*tt).tabletype.limits();
tt.limits_cache = Some(wasm_limits_t { tt.limits_cache = Some(wasm_limits_t {
min: limits.min(), min: limits.min(),
max: limits.max(), max: limits.max().unwrap_or(u32::max_value()),
}); });
} }
(*tt).limits_cache.as_ref().unwrap() (*tt).limits_cache.as_ref().unwrap()
@@ -1469,7 +1466,12 @@ pub unsafe extern "C" fn wasm_memorytype_delete(mt: *mut wasm_memorytype_t) {
pub unsafe extern "C" fn wasm_memorytype_new( pub unsafe extern "C" fn wasm_memorytype_new(
limits: *const wasm_limits_t, limits: *const wasm_limits_t,
) -> *mut wasm_memorytype_t { ) -> *mut wasm_memorytype_t {
let limits = Limits::new((*limits).min, (*limits).max); let max = if (*limits).max == u32::max_value() {
None
} else {
Some((*limits).max)
};
let limits = Limits::new((*limits).min, max);
let mt = Box::new(wasm_memorytype_t { let mt = Box::new(wasm_memorytype_t {
memorytype: MemoryType::new(limits), memorytype: MemoryType::new(limits),
limits_cache: None, limits_cache: None,
@@ -1553,7 +1555,11 @@ unsafe fn into_funcref(val: Val) -> *mut wasm_ref_t {
if let Val::AnyRef(AnyRef::Null) = val { if let Val::AnyRef(AnyRef::Null) = val {
return ptr::null_mut(); return ptr::null_mut();
} }
let r = Box::new(wasm_ref_t { r: val.into() }); let anyref = match val.anyref() {
Some(anyref) => anyref,
None => return ptr::null_mut(),
};
let r = Box::new(wasm_ref_t { r: anyref });
Box::into_raw(r) Box::into_raw(r)
} }
@@ -1615,7 +1621,12 @@ pub unsafe extern "C" fn wasm_tabletype_new(
limits: *const wasm_limits_t, limits: *const wasm_limits_t,
) -> *mut wasm_tabletype_t { ) -> *mut wasm_tabletype_t {
let ty = Box::from_raw(ty).ty; let ty = Box::from_raw(ty).ty;
let limits = Limits::new((*limits).min, (*limits).max); let max = if (*limits).max == u32::max_value() {
None
} else {
Some((*limits).max)
};
let limits = Limits::new((*limits).min, max);
let tt = Box::new(wasm_tabletype_t { let tt = Box::new(wasm_tabletype_t {
tabletype: TableType::new(ty, limits), tabletype: TableType::new(ty, limits),
element_cache: None, element_cache: None,

View File

@@ -13,10 +13,7 @@ edition = "2018"
[dependencies] [dependencies]
gimli = "0.19.0" gimli = "0.19.0"
wasmparser = "0.39.2" wasmparser = "0.44.0"
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
faerie = "0.13.0" faerie = "0.13.0"
wasmtime-environ = { path = "../environ" } wasmtime-environ = { path = "../environ" }
target-lexicon = { version = "0.9.0", default-features = false } target-lexicon = { version = "0.9.0", default-features = false }

View File

@@ -3,10 +3,10 @@
#![allow(clippy::cast_ptr_alignment)] #![allow(clippy::cast_ptr_alignment)]
use anyhow::Error; use anyhow::Error;
use cranelift_codegen::isa::TargetFrontendConfig;
use faerie::{Artifact, Decl}; use faerie::{Artifact, Decl};
use more_asserts::assert_gt; use more_asserts::assert_gt;
use target_lexicon::{BinaryFormat, Triple}; use target_lexicon::{BinaryFormat, Triple};
use wasmtime_environ::isa::TargetFrontendConfig;
use wasmtime_environ::{ModuleAddressMap, ModuleVmctxInfo, ValueLabelsRanges}; use wasmtime_environ::{ModuleAddressMap, ModuleVmctxInfo, ValueLabelsRanges};
pub use crate::read_debuginfo::{read_debuginfo, DebugInfoData, WasmFileInfo}; pub use crate::read_debuginfo::{read_debuginfo, DebugInfoData, WasmFileInfo};

View File

@@ -1,12 +1,12 @@
use crate::WasmFileInfo; use crate::WasmFileInfo;
use cranelift_codegen::ir::SourceLoc;
use cranelift_entity::{EntityRef, PrimaryMap};
use cranelift_wasm::DefinedFuncIndex;
use gimli::write; use gimli::write;
use more_asserts::assert_le; use more_asserts::assert_le;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::iter::FromIterator; use std::iter::FromIterator;
use wasmtime_environ::entity::{EntityRef, PrimaryMap};
use wasmtime_environ::ir::SourceLoc;
use wasmtime_environ::wasm::DefinedFuncIndex;
use wasmtime_environ::{FunctionAddressMap, ModuleAddressMap}; use wasmtime_environ::{FunctionAddressMap, ModuleAddressMap};
pub type GeneratedAddress = usize; pub type GeneratedAddress = usize;
@@ -492,10 +492,10 @@ impl AddressTransform {
mod tests { mod tests {
use super::{build_function_lookup, get_wasm_code_offset, AddressTransform}; use super::{build_function_lookup, get_wasm_code_offset, AddressTransform};
use crate::read_debuginfo::WasmFileInfo; use crate::read_debuginfo::WasmFileInfo;
use cranelift_codegen::ir::SourceLoc;
use cranelift_entity::PrimaryMap;
use gimli::write::Address; use gimli::write::Address;
use std::iter::FromIterator; use std::iter::FromIterator;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::ir::SourceLoc;
use wasmtime_environ::{FunctionAddressMap, InstructionAddressMap, ModuleAddressMap}; use wasmtime_environ::{FunctionAddressMap, InstructionAddressMap, ModuleAddressMap};
#[test] #[test]

View File

@@ -1,13 +1,12 @@
use super::address_transform::AddressTransform; use super::address_transform::AddressTransform;
use anyhow::Error; use anyhow::Error;
use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
use cranelift_codegen::isa::RegUnit;
use cranelift_codegen::ValueLabelsRanges;
use cranelift_entity::EntityRef;
use cranelift_wasm::{get_vmctx_value_label, DefinedFuncIndex};
use gimli::{self, write, Expression, Operation, Reader, ReaderOffset, Register, X86_64}; use gimli::{self, write, Expression, Operation, Reader, ReaderOffset, Register, X86_64};
use more_asserts::{assert_le, assert_lt}; use more_asserts::{assert_le, assert_lt};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::ir::{StackSlots, ValueLabel, ValueLabelsRanges, ValueLoc};
use wasmtime_environ::isa::RegUnit;
use wasmtime_environ::wasm::{get_vmctx_value_label, DefinedFuncIndex};
#[derive(Debug)] #[derive(Debug)]
pub struct FunctionFrameInfo<'a> { pub struct FunctionFrameInfo<'a> {

View File

@@ -2,13 +2,13 @@ use super::address_transform::AddressTransform;
use super::attr::clone_attr_string; use super::attr::clone_attr_string;
use super::{Reader, TransformError}; use super::{Reader, TransformError};
use anyhow::Error; use anyhow::Error;
use cranelift_entity::EntityRef;
use gimli::{ use gimli::{
write, DebugLine, DebugLineOffset, DebugStr, DebuggingInformationEntry, LineEncoding, Unit, write, DebugLine, DebugLineOffset, DebugStr, DebuggingInformationEntry, LineEncoding, Unit,
}; };
use more_asserts::assert_le; use more_asserts::assert_le;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::iter::FromIterator; use std::iter::FromIterator;
use wasmtime_environ::entity::EntityRef;
#[derive(Debug)] #[derive(Debug)]
enum SavedLineProgramRow { enum SavedLineProgramRow {

View File

@@ -1,7 +1,6 @@
use crate::gc::build_dependencies; use crate::gc::build_dependencies;
use crate::DebugInfoData; use crate::DebugInfoData;
use anyhow::Error; use anyhow::Error;
use cranelift_codegen::isa::TargetFrontendConfig;
use gimli::{ use gimli::{
write, DebugAddr, DebugAddrBase, DebugLine, DebugStr, LocationLists, RangeLists, write, DebugAddr, DebugAddrBase, DebugLine, DebugStr, LocationLists, RangeLists,
UnitSectionOffset, UnitSectionOffset,
@@ -10,6 +9,7 @@ use simulate::generate_simulated_dwarf;
use std::collections::HashSet; use std::collections::HashSet;
use thiserror::Error; use thiserror::Error;
use unit::clone_unit; use unit::clone_unit;
use wasmtime_environ::isa::TargetFrontendConfig;
use wasmtime_environ::{ModuleAddressMap, ModuleVmctxInfo, ValueLabelsRanges}; use wasmtime_environ::{ModuleAddressMap, ModuleVmctxInfo, ValueLabelsRanges};
pub use address_transform::AddressTransform; pub use address_transform::AddressTransform;

View File

@@ -1,10 +1,10 @@
use super::address_transform::AddressTransform; use super::address_transform::AddressTransform;
use super::{DebugInputContext, Reader}; use super::{DebugInputContext, Reader};
use anyhow::Error; use anyhow::Error;
use cranelift_entity::EntityRef;
use cranelift_wasm::DefinedFuncIndex;
use gimli::{write, AttributeValue, DebuggingInformationEntry, RangeListsOffset}; use gimli::{write, AttributeValue, DebuggingInformationEntry, RangeListsOffset};
use more_asserts::assert_lt; use more_asserts::assert_lt;
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::wasm::DefinedFuncIndex;
pub(crate) enum RangeInfoBuilder { pub(crate) enum RangeInfoBuilder {
Undefined, Undefined,

View File

@@ -3,12 +3,12 @@ use super::utils::{add_internal_types, append_vmctx_info, get_function_frame_inf
use super::AddressTransform; use super::AddressTransform;
use crate::read_debuginfo::WasmFileInfo; use crate::read_debuginfo::WasmFileInfo;
use anyhow::Error; use anyhow::Error;
use cranelift_entity::EntityRef;
use cranelift_wasm::get_vmctx_value_label;
use gimli::write; use gimli::write;
use gimli::{self, LineEncoding}; use gimli::{self, LineEncoding};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::PathBuf; use std::path::PathBuf;
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::wasm::get_vmctx_value_label;
use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges}; use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges};
pub use crate::read_debuginfo::{DebugInfoData, FunctionMetadata, WasmType}; pub use crate::read_debuginfo::{DebugInfoData, FunctionMetadata, WasmType};

View File

@@ -6,10 +6,10 @@ use super::range_info_builder::RangeInfoBuilder;
use super::utils::{add_internal_types, append_vmctx_info, get_function_frame_info}; use super::utils::{add_internal_types, append_vmctx_info, get_function_frame_info};
use super::{DebugInputContext, Reader, TransformError}; use super::{DebugInputContext, Reader, TransformError};
use anyhow::Error; use anyhow::Error;
use cranelift_entity::EntityRef;
use gimli::write; use gimli::write;
use gimli::{AttributeValue, DebuggingInformationEntry, Unit, UnitOffset}; use gimli::{AttributeValue, DebuggingInformationEntry, Unit, UnitOffset};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges}; use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges};
pub(crate) type PendingDieRef = (write::UnitEntryId, gimli::DwAt, UnitOffset); pub(crate) type PendingDieRef = (write::UnitEntryId, gimli::DwAt, UnitOffset);

View File

@@ -1,8 +1,8 @@
use super::address_transform::AddressTransform; use super::address_transform::AddressTransform;
use super::expression::{CompiledExpression, FunctionFrameInfo}; use super::expression::{CompiledExpression, FunctionFrameInfo};
use anyhow::Error; use anyhow::Error;
use cranelift_wasm::DefinedFuncIndex;
use gimli::write; use gimli::write;
use wasmtime_environ::wasm::DefinedFuncIndex;
use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges}; use wasmtime_environ::{ModuleVmctxInfo, ValueLabelsRanges};
pub(crate) fn add_internal_types( pub(crate) fn add_internal_types(

View File

@@ -15,7 +15,7 @@ edition = "2018"
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] } cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] } cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] } cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
wasmparser = "0.39.2" wasmparser = "0.44.0"
lightbeam = { path = "../lightbeam", optional = true } lightbeam = { path = "../lightbeam", optional = true }
indexmap = "1.0.2" indexmap = "1.0.2"
rayon = "1.2.1" rayon = "1.2.1"

View File

@@ -0,0 +1,29 @@
#![doc(hidden)]
pub mod ir {
pub use cranelift_codegen::ir::{
types, AbiParam, ArgumentPurpose, Signature, SourceLoc, StackSlots, TrapCode, Type,
ValueLabel, ValueLoc,
};
pub use cranelift_codegen::ValueLabelsRanges;
}
pub mod settings {
pub use cranelift_codegen::settings::{builder, Configurable, Flags};
}
pub mod isa {
pub use cranelift_codegen::isa::{CallConv, RegUnit, TargetFrontendConfig, TargetIsa};
}
pub mod entity {
pub use cranelift_entity::{BoxedSlice, EntityRef, PrimaryMap};
}
pub mod wasm {
pub use cranelift_wasm::{
get_vmctx_value_label, DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex,
DefinedTableIndex, FuncIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex,
SignatureIndex, Table, TableElementType, TableIndex,
};
}

View File

@@ -26,6 +26,7 @@
mod address_map; mod address_map;
mod compilation; mod compilation;
mod data_structures;
mod func_environ; mod func_environ;
mod module; mod module;
mod module_environ; mod module_environ;
@@ -47,6 +48,7 @@ pub use crate::compilation::{
Relocations, TrapInformation, Traps, Relocations, TrapInformation, Traps,
}; };
pub use crate::cranelift::Cranelift; pub use crate::cranelift::Cranelift;
pub use crate::data_structures::*;
pub use crate::func_environ::BuiltinFunctionIndex; pub use crate::func_environ::BuiltinFunctionIndex;
#[cfg(feature = "lightbeam")] #[cfg(feature = "lightbeam")]
pub use crate::lightbeam::Lightbeam; pub use crate::lightbeam::Lightbeam;

View File

@@ -12,13 +12,12 @@ version = "0.1.0"
anyhow = "1.0.22" anyhow = "1.0.22"
arbitrary = "0.2.0" arbitrary = "0.2.0"
binaryen = "0.8.2" binaryen = "0.8.2"
cranelift-codegen = "0.50.0"
cranelift-native = "0.50.0"
env_logger = { version = "0.7.1", optional = true } env_logger = { version = "0.7.1", optional = true }
log = "0.4.8" log = "0.4.8"
wasmparser = "0.42.1" wasmparser = "0.44.0"
wasmprinter = "0.2.0" wasmprinter = "0.2.0"
wasmtime = { path = "../api" } wasmtime = { path = "../api" }
wasmtime-environ = { path = "../environ" }
wasmtime-jit = { path = "../jit" } wasmtime-jit = { path = "../jit" }
[dev-dependencies] [dev-dependencies]

View File

@@ -12,17 +12,17 @@
pub mod dummy; pub mod dummy;
use cranelift_codegen::settings;
use dummy::dummy_imports; use dummy::dummy_imports;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc; use std::rc::Rc;
use wasmtime::{Config, Engine, HostRef, Instance, Module, Store}; use wasmtime::{Config, Engine, HostRef, Instance, Module, Store};
use wasmtime_jit::{CompilationStrategy, CompiledModule, Compiler, NullResolver}; use wasmtime_environ::{isa, settings};
use wasmtime_jit::{native, CompilationStrategy, CompiledModule, Compiler, NullResolver};
fn host_isa() -> Box<dyn cranelift_codegen::isa::TargetIsa> { fn host_isa() -> Box<dyn isa::TargetIsa> {
let flag_builder = settings::builder(); let flag_builder = settings::builder();
let isa_builder = cranelift_native::builder().expect("host machine is not a supported target"); let isa_builder = native::builder();
isa_builder.finish(settings::Flags::new(flag_builder)) isa_builder.finish(settings::Flags::new(flag_builder))
} }

View File

@@ -13,17 +13,17 @@ pub fn dummy_imports(
) -> Result<Vec<Extern>, HostRef<Trap>> { ) -> Result<Vec<Extern>, HostRef<Trap>> {
let mut imports = Vec::with_capacity(import_tys.len()); let mut imports = Vec::with_capacity(import_tys.len());
for imp in import_tys { for imp in import_tys {
imports.push(match imp.r#type() { imports.push(match imp.ty() {
ExternType::ExternFunc(func_ty) => { ExternType::Func(func_ty) => {
Extern::Func(HostRef::new(DummyFunc::new(&store, func_ty.clone()))) Extern::Func(HostRef::new(DummyFunc::new(&store, func_ty.clone())))
} }
ExternType::ExternGlobal(global_ty) => { ExternType::Global(global_ty) => {
Extern::Global(HostRef::new(dummy_global(&store, global_ty.clone())?)) Extern::Global(HostRef::new(dummy_global(&store, global_ty.clone())?))
} }
ExternType::ExternTable(table_ty) => { ExternType::Table(table_ty) => {
Extern::Table(HostRef::new(dummy_table(&store, table_ty.clone())?)) Extern::Table(HostRef::new(dummy_table(&store, table_ty.clone())?))
} }
ExternType::ExternMemory(mem_ty) => { ExternType::Memory(mem_ty) => {
Extern::Memory(HostRef::new(dummy_memory(&store, mem_ty.clone()))) Extern::Memory(HostRef::new(dummy_memory(&store, mem_ty.clone())))
} }
}); });

View File

@@ -12,12 +12,12 @@ edition = "2018"
[dependencies] [dependencies]
anyhow = "1.0.19" anyhow = "1.0.19"
cranelift-codegen = { version = "0.50.0", default-features = false }
walrus = "0.13" walrus = "0.13"
wasmparser = { version = "0.39.2", default-features = false } wasmparser = { version = "0.44.0", default-features = false }
wasm-webidl-bindings = "0.6" wasm-webidl-bindings = "0.6"
wasmtime = { path = '../api' } wasmtime = { path = '../api' }
wasmtime-jit = { path = '../jit' } wasmtime-jit = { path = '../jit' }
wasmtime-environ = { path = '../environ' }
wasmtime-runtime = { path = '../runtime' } wasmtime-runtime = { path = '../runtime' }
wasmtime-wasi = { path = '../wasi' } wasmtime-wasi = { path = '../wasi' }

View File

@@ -8,10 +8,10 @@
#![deny(missing_docs)] #![deny(missing_docs)]
use anyhow::{bail, format_err, Result}; use anyhow::{bail, format_err, Result};
use cranelift_codegen::ir;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::str; use std::str;
use wasm_webidl_bindings::ast; use wasm_webidl_bindings::ast;
use wasmtime_environ::ir;
use wasmtime_jit::RuntimeValue; use wasmtime_jit::RuntimeValue;
use wasmtime_runtime::{Export, InstanceHandle}; use wasmtime_runtime::{Export, InstanceHandle};
@@ -152,7 +152,14 @@ impl ModuleData {
Ok(values) => values Ok(values) => values
.to_vec() .to_vec()
.into_iter() .into_iter()
.map(|v: wasmtime::Val| v.into()) .map(|v: wasmtime::Val| match v {
wasmtime::Val::I32(i) => RuntimeValue::I32(i),
wasmtime::Val::I64(i) => RuntimeValue::I64(i),
wasmtime::Val::F32(i) => RuntimeValue::F32(i),
wasmtime::Val::F64(i) => RuntimeValue::F64(i),
wasmtime::Val::V128(i) => RuntimeValue::V128(i),
_ => panic!("unsupported value {:?}", v),
})
.collect::<Vec<RuntimeValue>>(), .collect::<Vec<RuntimeValue>>(),
Err(trap) => bail!("trapped: {:?}", trap), Err(trap) => bail!("trapped: {:?}", trap),
}; };

View File

@@ -14,6 +14,7 @@ edition = "2018"
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] } cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] } cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] } cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
cranelift-native = "0.50.0"
cranelift-frontend = "0.50.0" cranelift-frontend = "0.50.0"
wasmtime-environ = { path = "../environ" } wasmtime-environ = { path = "../environ" }
wasmtime-runtime = { path = "../runtime" } wasmtime-runtime = { path = "../runtime" }
@@ -21,7 +22,7 @@ wasmtime-debug = { path = "../debug" }
region = "2.0.0" region = "2.0.0"
thiserror = "1.0.4" thiserror = "1.0.4"
target-lexicon = { version = "0.9.0", default-features = false } target-lexicon = { version = "0.9.0", default-features = false }
wasmparser = { version = "0.39.2", default-features = false } wasmparser = { version = "0.44.0", default-features = false }
more-asserts = "0.2.1" more-asserts = "0.2.1"
anyhow = "1.0" anyhow = "1.0"

View File

@@ -2,10 +2,10 @@
use crate::compiler::Compiler; use crate::compiler::Compiler;
use crate::instantiate::SetupError; use crate::instantiate::SetupError;
use cranelift_codegen::ir;
use std::cmp::max; use std::cmp::max;
use std::{fmt, mem, ptr, slice}; use std::{fmt, mem, ptr, slice};
use thiserror::Error; use thiserror::Error;
use wasmtime_environ::ir;
use wasmtime_runtime::{wasmtime_call_trampoline, Export, InstanceHandle, VMInvokeArgument}; use wasmtime_runtime::{wasmtime_call_trampoline, Export, InstanceHandle, VMInvokeArgument};
/// A runtime value. /// A runtime value.

View File

@@ -4,16 +4,17 @@ use crate::code_memory::CodeMemory;
use crate::instantiate::SetupError; use crate::instantiate::SetupError;
use crate::target_tunables::target_tunables; use crate::target_tunables::target_tunables;
use cranelift_codegen::ir::InstBuilder; use cranelift_codegen::ir::InstBuilder;
use cranelift_codegen::isa::{TargetFrontendConfig, TargetIsa};
use cranelift_codegen::print_errors::pretty_error; use cranelift_codegen::print_errors::pretty_error;
use cranelift_codegen::Context; use cranelift_codegen::Context;
use cranelift_codegen::{binemit, ir}; use cranelift_codegen::{binemit, ir};
use cranelift_entity::{EntityRef, PrimaryMap};
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use cranelift_wasm::{DefinedFuncIndex, DefinedMemoryIndex, ModuleTranslationState}; use cranelift_wasm::ModuleTranslationState;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryFrom; use std::convert::TryFrom;
use wasmtime_debug::{emit_debugsections_image, DebugInfoData}; use wasmtime_debug::{emit_debugsections_image, DebugInfoData};
use wasmtime_environ::entity::{EntityRef, PrimaryMap};
use wasmtime_environ::isa::{TargetFrontendConfig, TargetIsa};
use wasmtime_environ::wasm::{DefinedFuncIndex, DefinedMemoryIndex};
use wasmtime_environ::{ use wasmtime_environ::{
Compilation, CompileError, CompiledFunction, Compiler as _C, FunctionBodyData, Module, Compilation, CompileError, CompiledFunction, Compiler as _C, FunctionBodyData, Module,
ModuleVmctxInfo, Relocations, Traps, Tunables, VMOffsets, ModuleVmctxInfo, Relocations, Traps, Tunables, VMOffsets,

View File

@@ -3,12 +3,12 @@ use crate::{
instantiate, ActionError, ActionOutcome, CompilationStrategy, CompiledModule, Compiler, instantiate, ActionError, ActionOutcome, CompilationStrategy, CompiledModule, Compiler,
InstanceHandle, Namespace, RuntimeValue, SetupError, InstanceHandle, Namespace, RuntimeValue, SetupError,
}; };
use cranelift_codegen::isa::TargetIsa;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc; use std::rc::Rc;
use thiserror::Error; use thiserror::Error;
use wasmparser::{validate, OperatorValidatorConfig, ValidatingParserConfig}; use wasmparser::{validate, OperatorValidatorConfig, ValidatingParserConfig};
use wasmtime_environ::isa::TargetIsa;
/// Indicates an unknown instance was specified. /// Indicates an unknown instance was specified.
#[derive(Error, Debug)] #[derive(Error, Debug)]

View File

@@ -6,14 +6,14 @@
use crate::compiler::Compiler; use crate::compiler::Compiler;
use crate::link::link_module; use crate::link::link_module;
use crate::resolver::Resolver; use crate::resolver::Resolver;
use cranelift_entity::{BoxedSlice, PrimaryMap};
use cranelift_wasm::{DefinedFuncIndex, SignatureIndex};
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::io::Write; use std::io::Write;
use std::rc::Rc; use std::rc::Rc;
use thiserror::Error; use thiserror::Error;
use wasmtime_debug::read_debuginfo; use wasmtime_debug::read_debuginfo;
use wasmtime_environ::entity::{BoxedSlice, PrimaryMap};
use wasmtime_environ::wasm::{DefinedFuncIndex, SignatureIndex};
use wasmtime_environ::{ use wasmtime_environ::{
CompileError, DataInitializer, DataInitializerLocation, Module, ModuleEnvironment, CompileError, DataInitializer, DataInitializerLocation, Module, ModuleEnvironment,
}; };

View File

@@ -32,6 +32,9 @@ mod namespace;
mod resolver; mod resolver;
mod target_tunables; mod target_tunables;
pub mod native;
pub mod trampoline;
pub use crate::action::{ActionError, ActionOutcome, RuntimeValue}; pub use crate::action::{ActionError, ActionOutcome, RuntimeValue};
pub use crate::code_memory::CodeMemory; pub use crate::code_memory::CodeMemory;
pub use crate::compiler::{CompilationStrategy, Compiler}; pub use crate::compiler::{CompilationStrategy, Compiler};

View File

@@ -3,11 +3,13 @@
use crate::resolver::Resolver; use crate::resolver::Resolver;
use cranelift_codegen::binemit::Reloc; use cranelift_codegen::binemit::Reloc;
use cranelift_codegen::ir::JumpTableOffsets; use cranelift_codegen::ir::JumpTableOffsets;
use cranelift_entity::PrimaryMap;
use cranelift_wasm::{DefinedFuncIndex, Global, GlobalInit, Memory, Table, TableElementType};
use more_asserts::assert_ge; use more_asserts::assert_ge;
use std::collections::HashSet; use std::collections::HashSet;
use std::ptr::write_unaligned; use std::ptr::write_unaligned;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::wasm::{
DefinedFuncIndex, Global, GlobalInit, Memory, Table, TableElementType,
};
use wasmtime_environ::{ use wasmtime_environ::{
MemoryPlan, MemoryStyle, Module, Relocation, RelocationTarget, Relocations, TablePlan, MemoryPlan, MemoryStyle, Module, Relocation, RelocationTarget, Relocations, TablePlan,
}; };

14
crates/jit/src/native.rs Normal file
View File

@@ -0,0 +1,14 @@
#![allow(missing_docs)]
use cranelift_codegen;
pub fn builder() -> cranelift_codegen::isa::Builder {
cranelift_native::builder().expect("host machine is not a supported target")
}
pub fn call_conv() -> cranelift_codegen::isa::CallConv {
use target_lexicon::HOST;
cranelift_codegen::isa::CallConv::triple_default(&HOST)
}
pub use cranelift_codegen::isa::lookup;

View File

@@ -0,0 +1,56 @@
#![allow(missing_docs)]
pub mod ir {
pub use cranelift_codegen::ir::{
ExternalName, Function, InstBuilder, MemFlags, StackSlotData, StackSlotKind,
};
}
pub use cranelift_codegen::print_errors::pretty_error;
pub use cranelift_codegen::Context;
pub use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
pub mod binemit {
pub use cranelift_codegen::binemit::{CodeOffset, NullStackmapSink, TrapSink};
use cranelift_codegen::{binemit, ir};
/// We don't expect trampoline compilation to produce any relocations, so
/// this `RelocSink` just asserts that it doesn't recieve any.
pub struct TrampolineRelocSink {}
impl binemit::RelocSink for TrampolineRelocSink {
fn reloc_ebb(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_ebb_offset: binemit::CodeOffset,
) {
panic!("trampoline compilation should not produce ebb relocs");
}
fn reloc_external(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_name: &ir::ExternalName,
_addend: binemit::Addend,
) {
panic!("trampoline compilation should not produce external symbol relocs");
}
fn reloc_constant(
&mut self,
_code_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_constant_offset: ir::ConstantOffset,
) {
panic!("trampoline compilation should not produce constant relocs");
}
fn reloc_jt(
&mut self,
_offset: binemit::CodeOffset,
_reloc: binemit::Reloc,
_jt: ir::JumpTable,
) {
panic!("trampoline compilation should not produce jump table relocs");
}
}
}

View File

@@ -17,8 +17,10 @@ namespace Wasmtime
Host = host; Host = host;
Module = module; Module = module;
var bindings = host.GetImportBindings(module); //Save the bindings to root the objects.
var handles = bindings.Select(b => b.Bind(module.Store, host)).ToList(); //Otherwise the GC may collect the delegates from ExternFunction for example.
_bindings = host.GetImportBindings(module);
var handles = _bindings.Select(b => b.Bind(module.Store, host)).ToList();
unsafe unsafe
{ {
@@ -141,5 +143,6 @@ namespace Wasmtime
private Interop.wasm_extern_vec_t _externs; private Interop.wasm_extern_vec_t _externs;
private Dictionary<string, ExternFunction> _functions; private Dictionary<string, ExternFunction> _functions;
private Dictionary<string, ExternGlobal> _globals; private Dictionary<string, ExternGlobal> _globals;
private List<Bindings.Binding> _bindings;
} }
} }

View File

@@ -5,7 +5,7 @@ namespace Wasmtime
/// <summary> /// <summary>
/// Represents the possible kinds of WebAssembly values. /// Represents the possible kinds of WebAssembly values.
/// </summary> /// </summary>
public enum ValueKind public enum ValueKind : byte
{ {
/// <summary> /// <summary>
/// The value is a 32-bit integer. /// The value is a 32-bit integer.

View File

@@ -15,11 +15,6 @@ name = "_wasmtime"
crate-type = ["cdylib"] crate-type = ["cdylib"]
[dependencies] [dependencies]
cranelift-codegen = "0.50.0"
cranelift-native = "0.50.0"
cranelift-entity = "0.50.0"
cranelift-wasm = "0.50.0"
cranelift-frontend = "0.50.0"
wasmtime = { path = "../../api" } wasmtime = { path = "../../api" }
wasmtime-environ = { path = "../../environ" } wasmtime-environ = { path = "../../environ" }
wasmtime-interface-types = { path = "../../interface-types" } wasmtime-interface-types = { path = "../../interface-types" }
@@ -29,7 +24,7 @@ wasmtime-wasi = { path = "../../wasi" }
target-lexicon = { version = "0.9.0", default-features = false } target-lexicon = { version = "0.9.0", default-features = false }
anyhow = "1.0.19" anyhow = "1.0.19"
region = "2.0.0" region = "2.0.0"
wasmparser = "0.39.2" wasmparser = "0.44.0"
pyo3 = { version = "0.8.0", features = ["extension-module"] } pyo3 = { version = "0.8.0", features = ["extension-module"] }
[badges] [badges]

View File

@@ -22,8 +22,8 @@ impl Instance {
let exports = PyDict::new(py); let exports = PyDict::new(py);
let module = self.instance.borrow().module().clone(); let module = self.instance.borrow().module().clone();
for (i, e) in module.borrow().exports().iter().enumerate() { for (i, e) in module.borrow().exports().iter().enumerate() {
match e.r#type() { match e.ty() {
wasmtime::ExternType::ExternFunc(ft) => { wasmtime::ExternType::Func(ft) => {
let mut args_types = Vec::new(); let mut args_types = Vec::new();
for ty in ft.params().iter() { for ty in ft.params().iter() {
args_types.push(ty.clone()); args_types.push(ty.clone());
@@ -39,7 +39,7 @@ impl Instance {
)?; )?;
exports.set_item(e.name().to_string(), f)?; exports.set_item(e.name().to_string(), f)?;
} }
wasmtime::ExternType::ExternMemory(_) => { wasmtime::ExternType::Memory(_) => {
let f = Py::new( let f = Py::new(
py, py,
Memory { Memory {

View File

@@ -111,21 +111,18 @@ pub fn instantiate(
let mut imports: Vec<wasmtime::Extern> = Vec::new(); let mut imports: Vec<wasmtime::Extern> = Vec::new();
for i in module.borrow().imports() { for i in module.borrow().imports() {
let module_name = i.module().as_str(); let module_name = i.module();
if let Some(m) = import_obj.get_item(module_name) { if let Some(m) = import_obj.get_item(module_name) {
let e = find_export_in(m, &store, i.name().as_str())?; let e = find_export_in(m, &store, i.name())?;
imports.push(e); imports.push(e);
} else if wasi.is_some() && module_name == wasi.as_ref().unwrap().0 { } else if wasi.is_some() && module_name == wasi.as_ref().unwrap().0 {
let e = wasi let e = wasi
.as_ref() .as_ref()
.unwrap() .unwrap()
.1 .1
.find_export_by_name(i.name().as_str()) .find_export_by_name(i.name())
.ok_or_else(|| { .ok_or_else(|| {
PyErr::new::<Exception, _>(format!( PyErr::new::<Exception, _>(format!("wasi export {} is not found", i.name(),))
"wasi export {} is not found",
i.name().as_str()
))
})?; })?;
imports.push(e.clone()); imports.push(e.clone());
} else { } else {

View File

@@ -69,13 +69,13 @@ fn generate_load(item: &syn::ItemTrait) -> syn::Result<TokenStream> {
let wasi_instance = #root::wasmtime_wasi::create_wasi_instance(&store, &[], &[], &[]) let wasi_instance = #root::wasmtime_wasi::create_wasi_instance(&store, &[], &[], &[])
.map_err(|e| format_err!("wasm instantiation error: {:?}", e))?; .map_err(|e| format_err!("wasm instantiation error: {:?}", e))?;
for i in module.borrow().imports().iter() { for i in module.borrow().imports().iter() {
if i.module().as_str() != module_name { if i.module() != module_name {
bail!("unknown import module {}", i.module().as_str()); bail!("unknown import module {}", i.module());
} }
if let Some(export) = wasi_instance.find_export_by_name(i.name().as_str()) { if let Some(export) = wasi_instance.find_export_by_name(i.name()) {
imports.push(export.clone()); imports.push(export.clone());
} else { } else {
bail!("unknown import {}:{}", i.module().as_str(), i.name().as_str()) bail!("unknown import {}:{}", i.module(), i.name())
} }
} }
} }

View File

@@ -11,9 +11,6 @@ readme = "README.md"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
wasmtime-environ = { path = "../environ" } wasmtime-environ = { path = "../environ" }
faerie = "0.13.0" faerie = "0.13.0"
more-asserts = "0.2.1" more-asserts = "0.2.1"

View File

@@ -1,12 +1,12 @@
#![allow(clippy::cast_ptr_alignment)] #![allow(clippy::cast_ptr_alignment)]
use cranelift_codegen::isa::TargetFrontendConfig;
use cranelift_entity::EntityRef;
use cranelift_wasm::GlobalInit;
use more_asserts::assert_le; use more_asserts::assert_le;
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use std::collections::HashMap; use std::collections::HashMap;
use std::ptr; use std::ptr;
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::isa::TargetFrontendConfig;
use wasmtime_environ::wasm::GlobalInit;
use wasmtime_environ::{Module, TargetSharedSignatureIndex, VMOffsets}; use wasmtime_environ::{Module, TargetSharedSignatureIndex, VMOffsets};
pub struct TableRelocation { pub struct TableRelocation {

View File

@@ -1,7 +1,7 @@
use cranelift_codegen::settings;
use cranelift_codegen::settings::Configurable;
use cranelift_entity::EntityRef;
use faerie::{Artifact, Decl, Link}; use faerie::{Artifact, Decl, Link};
use wasmtime_environ::entity::EntityRef;
use wasmtime_environ::settings;
use wasmtime_environ::settings::Configurable;
use wasmtime_environ::{Compilation, Module, RelocationTarget, Relocations}; use wasmtime_environ::{Compilation, Module, RelocationTarget, Relocations};
fn get_reloc_target_special_import_name(target: RelocationTarget) -> Option<&'static str> { fn get_reloc_target_special_import_name(target: RelocationTarget) -> Option<&'static str> {

View File

@@ -2,8 +2,8 @@ use crate::context::layout_vmcontext;
use crate::data_segment::{declare_data_segment, emit_data_segment}; use crate::data_segment::{declare_data_segment, emit_data_segment};
use crate::function::{declare_functions, emit_functions}; use crate::function::{declare_functions, emit_functions};
use crate::table::{declare_table, emit_table}; use crate::table::{declare_table, emit_table};
use cranelift_codegen::isa::TargetFrontendConfig;
use faerie::{Artifact, Decl, Link}; use faerie::{Artifact, Decl, Link};
use wasmtime_environ::isa::TargetFrontendConfig;
use wasmtime_environ::{Compilation, DataInitializer, Module, Relocations}; use wasmtime_environ::{Compilation, DataInitializer, Module, Relocations};
fn emit_vmcontext_init( fn emit_vmcontext_init(

View File

@@ -11,9 +11,6 @@ readme = "README.md"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
cranelift-codegen = { version = "0.50.0", features = ["enable-serde"] }
cranelift-entity = { version = "0.50.0", features = ["enable-serde"] }
cranelift-wasm = { version = "0.50.0", features = ["enable-serde"] }
wasmtime-environ = { path = "../environ" } wasmtime-environ = { path = "../environ" }
region = "2.0.0" region = "2.0.0"
lazy_static = "1.2.0" lazy_static = "1.2.0"

View File

@@ -1,8 +1,8 @@
use crate::vmcontext::{ use crate::vmcontext::{
VMContext, VMFunctionBody, VMGlobalDefinition, VMMemoryDefinition, VMTableDefinition, VMContext, VMFunctionBody, VMGlobalDefinition, VMMemoryDefinition, VMTableDefinition,
}; };
use cranelift_codegen::ir; use wasmtime_environ::ir;
use cranelift_wasm::Global; use wasmtime_environ::wasm::Global;
use wasmtime_environ::{MemoryPlan, TablePlan}; use wasmtime_environ::{MemoryPlan, TablePlan};
/// The value of an export passed from one instance to another. /// The value of an export passed from one instance to another.

View File

@@ -1,8 +1,8 @@
use crate::instance::InstanceHandle; use crate::instance::InstanceHandle;
use crate::vmcontext::{VMFunctionImport, VMGlobalImport, VMMemoryImport, VMTableImport}; use crate::vmcontext::{VMFunctionImport, VMGlobalImport, VMMemoryImport, VMTableImport};
use cranelift_entity::{BoxedSlice, PrimaryMap};
use cranelift_wasm::{FuncIndex, GlobalIndex, MemoryIndex, TableIndex};
use std::collections::HashSet; use std::collections::HashSet;
use wasmtime_environ::entity::{BoxedSlice, PrimaryMap};
use wasmtime_environ::wasm::{FuncIndex, GlobalIndex, MemoryIndex, TableIndex};
/// Resolved import pointers. /// Resolved import pointers.
#[derive(Clone)] #[derive(Clone)]

View File

@@ -15,11 +15,6 @@ use crate::vmcontext::{
VMGlobalDefinition, VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex, VMGlobalDefinition, VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMSharedSignatureIndex,
VMTableDefinition, VMTableImport, VMTableDefinition, VMTableImport,
}; };
use cranelift_entity::{BoxedSlice, EntityRef, PrimaryMap};
use cranelift_wasm::{
DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, FuncIndex,
GlobalIndex, GlobalInit, MemoryIndex, SignatureIndex, TableIndex,
};
use memoffset::offset_of; use memoffset::offset_of;
use more_asserts::assert_lt; use more_asserts::assert_lt;
use std::any::Any; use std::any::Any;
@@ -30,6 +25,11 @@ use std::convert::TryFrom;
use std::rc::Rc; use std::rc::Rc;
use std::{mem, ptr, slice}; use std::{mem, ptr, slice};
use thiserror::Error; use thiserror::Error;
use wasmtime_environ::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasmtime_environ::wasm::{
DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, FuncIndex,
GlobalIndex, GlobalInit, MemoryIndex, SignatureIndex, TableIndex,
};
use wasmtime_environ::{DataInitializer, Module, TableElements, VMOffsets}; use wasmtime_environ::{DataInitializer, Module, TableElements, VMOffsets};
fn signature_id( fn signature_id(
@@ -469,37 +469,6 @@ impl Instance {
fn invoke_start_function(&mut self) -> Result<(), InstantiationError> { fn invoke_start_function(&mut self) -> Result<(), InstantiationError> {
if let Some(start_index) = self.module.start_func { if let Some(start_index) = self.module.start_func {
self.invoke_function(start_index) self.invoke_function(start_index)
} else if let Some(start_export) = self.module.exports.get("_start") {
// As a compatibility measure, if the module doesn't have a start
// function but does have a _start function exported, call that.
match *start_export {
wasmtime_environ::Export::Function(func_index) => {
let sig = &self.module.signatures[self.module.functions[func_index]];
// No wasm params or returns; just the vmctx param.
if sig.params.len() == 1 && sig.returns.is_empty() {
self.invoke_function(func_index)
} else {
Ok(())
}
}
_ => Ok(()),
}
} else if let Some(main_export) = self.module.exports.get("main") {
// As a further compatibility measure, if the module doesn't have a
// start function or a _start function exported, but does have a main
// function exported, call that.
match *main_export {
wasmtime_environ::Export::Function(func_index) => {
let sig = &self.module.signatures[self.module.functions[func_index]];
// No wasm params or returns; just the vmctx param.
if sig.params.len() == 1 && sig.returns.is_empty() {
self.invoke_function(func_index)
} else {
Ok(())
}
}
_ => Ok(()),
}
} else { } else {
Ok(()) Ok(())
} }

View File

@@ -3,7 +3,7 @@
//! instructions which compute them directly. //! instructions which compute them directly.
use crate::vmcontext::VMContext; use crate::vmcontext::VMContext;
use cranelift_wasm::{DefinedMemoryIndex, MemoryIndex}; use wasmtime_environ::wasm::{DefinedMemoryIndex, MemoryIndex};
/// Implementation of f32.ceil /// Implementation of f32.ceil
pub extern "C" fn wasmtime_f32_ceil(x: f32) -> f32 { pub extern "C" fn wasmtime_f32_ceil(x: f32) -> f32 {

View File

@@ -2,10 +2,10 @@
//! signature checking. //! signature checking.
use crate::vmcontext::VMSharedSignatureIndex; use crate::vmcontext::VMSharedSignatureIndex;
use cranelift_codegen::ir;
use more_asserts::{assert_lt, debug_assert_lt}; use more_asserts::{assert_lt, debug_assert_lt};
use std::collections::{hash_map, HashMap}; use std::collections::{hash_map, HashMap};
use std::convert::TryFrom; use std::convert::TryFrom;
use wasmtime_environ::ir;
/// WebAssembly requires that the caller and callee signatures in an indirect /// WebAssembly requires that the caller and callee signatures in an indirect
/// call must match. To implement this efficiently, keep a registry of all /// call must match. To implement this efficiently, keep a registry of all

View File

@@ -3,8 +3,8 @@
//! `Table` is to WebAssembly tables what `LinearMemory` is to WebAssembly linear memories. //! `Table` is to WebAssembly tables what `LinearMemory` is to WebAssembly linear memories.
use crate::vmcontext::{VMCallerCheckedAnyfunc, VMTableDefinition}; use crate::vmcontext::{VMCallerCheckedAnyfunc, VMTableDefinition};
use cranelift_wasm::TableElementType;
use std::convert::{TryFrom, TryInto}; use std::convert::{TryFrom, TryInto};
use wasmtime_environ::wasm::TableElementType;
use wasmtime_environ::{TablePlan, TableStyle}; use wasmtime_environ::{TablePlan, TableStyle};
/// A table instance. /// A table instance.

View File

@@ -1,7 +1,7 @@
use cranelift_codegen::ir;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use wasmtime_environ::ir;
lazy_static! { lazy_static! {
static ref REGISTRY: RwLock<TrapRegistry> = RwLock::new(TrapRegistry::default()); static ref REGISTRY: RwLock<TrapRegistry> = RwLock::new(TrapRegistry::default());

View File

@@ -4,9 +4,9 @@
use crate::trap_registry::get_trap_registry; use crate::trap_registry::get_trap_registry;
use crate::trap_registry::TrapDescription; use crate::trap_registry::TrapDescription;
use crate::vmcontext::{VMContext, VMFunctionBody}; use crate::vmcontext::{VMContext, VMFunctionBody};
use cranelift_codegen::ir;
use std::cell::Cell; use std::cell::Cell;
use std::ptr; use std::ptr;
use wasmtime_environ::ir;
extern "C" { extern "C" {
fn WasmtimeCallTrampoline( fn WasmtimeCallTrampoline(

View File

@@ -16,7 +16,6 @@ wasmtime-environ = { path = "../environ" }
wasmtime-jit = { path = "../jit" } wasmtime-jit = { path = "../jit" }
wasmtime-wasi = { path = "../wasi" } wasmtime-wasi = { path = "../wasi" }
wasmtime = { path = "../api" } wasmtime = { path = "../api" }
cranelift-codegen = "0.50.0"
target-lexicon = "0.9.0" target-lexicon = "0.9.0"
pretty_env_logger = "0.3.0" pretty_env_logger = "0.3.0"
tempfile = "3.1.0" tempfile = "3.1.0"

View File

@@ -30,6 +30,8 @@ mod wasi_tests {
println!("cargo:rerun-if-changed={}", test_file_path); println!("cargo:rerun-if-changed={}", test_file_path);
} }
} }
println!("cargo:rerun-if-changed=wasi-tests/Cargo.toml");
println!("cargo:rerun-if-changed=wasi-tests/src/lib.rs");
// Build tests to OUT_DIR (target/*/build/wasi-common-*/out/wasm32-wasi/release/*.wasm) // Build tests to OUT_DIR (target/*/build/wasi-common-*/out/wasm32-wasi/release/*.wasm)
let out_dir = PathBuf::from( let out_dir = PathBuf::from(
env::var("OUT_DIR").expect("The OUT_DIR environment variable must be set"), env::var("OUT_DIR").expect("The OUT_DIR environment variable must be set"),

View File

@@ -1,8 +1,8 @@
use anyhow::{bail, Context}; use anyhow::{bail, Context};
use cranelift_codegen::settings::{self, Configurable};
use std::fs::File; use std::fs::File;
use std::{collections::HashMap, path::Path}; use std::path::Path;
use wasmtime::{Config, Engine, HostRef, Instance, Module, Store}; use wasmtime::{Config, Engine, HostRef, Instance, Module, Store};
use wasmtime_environ::settings::{self, Configurable};
pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> anyhow::Result<()> { pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> anyhow::Result<()> {
// Prepare runtime // Prepare runtime
@@ -18,7 +18,6 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
let engine = HostRef::new(Engine::new(&config)); let engine = HostRef::new(Engine::new(&config));
let store = HostRef::new(Store::new(&engine)); let store = HostRef::new(Store::new(&engine));
let mut module_registry = HashMap::new();
let global_exports = store.borrow().global_exports().clone(); let global_exports = store.borrow().global_exports().clone();
let get_preopens = |workspace: Option<&Path>| -> anyhow::Result<Vec<_>> { let get_preopens = |workspace: Option<&Path>| -> anyhow::Result<Vec<_>> {
if let Some(workspace) = workspace { if let Some(workspace) = workspace {
@@ -33,7 +32,7 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
// Create our wasi context with pretty standard arguments/inheritance/etc. // Create our wasi context with pretty standard arguments/inheritance/etc.
// Additionally register andy preopened directories if we have them. // Additionally register andy preopened directories if we have them.
let mut builder = wasi_common::old::snapshot_0::WasiCtxBuilder::new() let mut builder = wasi_common::WasiCtxBuilder::new()
.arg(bin_name) .arg(bin_name)
.arg(".") .arg(".")
.inherit_stdio(); .inherit_stdio();
@@ -47,19 +46,33 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
// stdin is closed which causes tests to fail. // stdin is closed which causes tests to fail.
let (reader, _writer) = os_pipe::pipe()?; let (reader, _writer) = os_pipe::pipe()?;
builder = builder.stdin(reader_to_file(reader)); builder = builder.stdin(reader_to_file(reader));
let snapshot1 = Instance::from_handle(
&store,
wasmtime_wasi::instantiate_wasi_with_context(
global_exports.clone(),
builder.build().context("failed to build wasi context")?,
)
.context("failed to instantiate wasi")?,
);
// The current stable Rust toolchain uses the old `wasi_unstable` ABI, // ... and then do the same as above but for the old snapshot of wasi, since
// aka `snapshot_0`. // a few tests still test that
module_registry.insert( let mut builder = wasi_common::old::snapshot_0::WasiCtxBuilder::new()
"wasi_unstable".to_owned(), .arg(bin_name)
Instance::from_handle( .arg(".")
.inherit_stdio();
for (dir, file) in get_preopens(workspace)? {
builder = builder.preopened_dir(file, dir);
}
let (reader, _writer) = os_pipe::pipe()?;
builder = builder.stdin(reader_to_file(reader));
let snapshot0 = Instance::from_handle(
&store, &store,
wasmtime_wasi::old::snapshot_0::instantiate_wasi_with_context( wasmtime_wasi::old::snapshot_0::instantiate_wasi_with_context(
global_exports.clone(), global_exports.clone(),
builder.build().context("failed to build wasi context")?, builder.build().context("failed to build wasi context")?,
) )
.context("failed to instantiate wasi")?, .context("failed to instantiate wasi")?,
),
); );
let module = HostRef::new(Module::new(&store, &data).context("failed to create wasm module")?); let module = HostRef::new(Module::new(&store, &data).context("failed to create wasm module")?);
@@ -68,21 +81,23 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
.imports() .imports()
.iter() .iter()
.map(|i| { .map(|i| {
let module_name = i.module().as_str(); let instance = if i.module() == "wasi_unstable" {
if let Some(instance) = module_registry.get(module_name) { &snapshot0
let field_name = i.name().as_str(); } else if i.module() == "wasi_snapshot_preview1" {
&snapshot1
} else {
bail!("import module {} was not found", i.module())
};
let field_name = i.name();
if let Some(export) = instance.find_export_by_name(field_name) { if let Some(export) = instance.find_export_by_name(field_name) {
Ok(export.clone()) Ok(export.clone())
} else { } else {
bail!( bail!(
"import {} was not found in module {}", "import {} was not found in module {}",
field_name, field_name,
module_name i.module(),
) )
} }
} else {
bail!("import module {} was not found", module_name)
}
}) })
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
let _ = HostRef::new(Instance::new(&store, &module, &imports).context(format!( let _ = HostRef::new(Instance::new(&store, &module, &imports).context(format!(

View File

@@ -8,7 +8,8 @@ publish = false
[dependencies] [dependencies]
libc = "0.2.65" libc = "0.2.65"
wasi = "0.7.0" wasi = "0.9.0"
wasi-old = { version = "0.7.0", package = "wasi" }
more-asserts = "0.2.1" more-asserts = "0.2.1"
# This crate is built with the wasm32-wasi target, so it's separate # This crate is built with the wasm32-wasi target, so it's separate

View File

@@ -1,12 +1,9 @@
use wasi::wasi_unstable;
fn test_big_random_buf() { fn test_big_random_buf() {
let mut buf = Vec::new(); let mut buf = Vec::new();
buf.resize(1024, 0); buf.resize(1024, 0);
assert!( unsafe {
wasi_unstable::random_get(&mut buf).is_ok(), wasi::random_get(buf.as_mut_ptr(), 1024).expect("failed to call random_get");
"calling get_random on a large buffer" }
);
// Chances are pretty good that at least *one* byte will be non-zero in // Chances are pretty good that at least *one* byte will be non-zero in
// any meaningful random function producing 1024 u8 values. // any meaningful random function producing 1024 u8 values.
assert!(buf.iter().any(|x| *x != 0), "random_get returned all zeros"); assert!(buf.iter().any(|x| *x != 0), "random_get returned all zeros");

View File

@@ -1,33 +1,15 @@
use more_asserts::assert_le; use more_asserts::assert_le;
use wasi::wasi_unstable;
use wasi_tests::wasi_wrappers::wasi_clock_time_get;
unsafe fn test_clock_time_get() { unsafe fn test_clock_time_get() {
// Test that clock_time_get succeeds. Even in environments where it's not // Test that clock_time_get succeeds. Even in environments where it's not
// desirable to expose high-precision timers, it should still succeed. // desirable to expose high-precision timers, it should still succeed.
// clock_res_get is where information about precision can be provided. // clock_res_get is where information about precision can be provided.
let mut time: wasi_unstable::Timestamp = 0; wasi::clock_time_get(wasi::CLOCKID_MONOTONIC, 1).expect("precision 1 should work");
let status = wasi_clock_time_get(wasi_unstable::CLOCK_MONOTONIC, 1, &mut time);
assert_eq!(
status,
wasi_unstable::raw::__WASI_ESUCCESS,
"clock_time_get with a precision of 1"
);
let status = wasi_clock_time_get(wasi_unstable::CLOCK_MONOTONIC, 0, &mut time); let first_time =
assert_eq!( wasi::clock_time_get(wasi::CLOCKID_MONOTONIC, 0).expect("precision 0 should work");
status,
wasi_unstable::raw::__WASI_ESUCCESS,
"clock_time_get with a precision of 0"
);
let first_time = time;
let status = wasi_clock_time_get(wasi_unstable::CLOCK_MONOTONIC, 0, &mut time); let time = wasi::clock_time_get(wasi::CLOCKID_MONOTONIC, 0).expect("re-fetch time should work");
assert_eq!(
status,
wasi_unstable::raw::__WASI_ESUCCESS,
"clock_time_get with a precision of 0"
);
assert_le!(first_time, time, "CLOCK_MONOTONIC should be monotonic"); assert_le!(first_time, time, "CLOCK_MONOTONIC should be monotonic");
} }

View File

@@ -1,60 +1,46 @@
use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, mem, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_tests::open_scratch_directory_new;
use wasi_tests::open_scratch_directory;
use wasi_tests::wasi_wrappers::wasi_fd_fdstat_get;
unsafe fn test_close_preopen(dir_fd: wasi_unstable::Fd) { unsafe fn test_close_preopen(dir_fd: wasi::Fd) {
let pre_fd: wasi_unstable::Fd = (libc::STDERR_FILENO + 1) as wasi_unstable::Fd; let pre_fd: wasi::Fd = (libc::STDERR_FILENO + 1) as wasi::Fd;
assert_gt!(dir_fd, pre_fd, "dir_fd number"); assert_gt!(dir_fd, pre_fd, "dir_fd number");
// Try to close a preopened directory handle. // Try to close a preopened directory handle.
assert_eq!( assert_eq!(
wasi_unstable::fd_close(pre_fd), wasi::fd_close(pre_fd).unwrap_err().raw_error(),
Err(wasi_unstable::ENOTSUP), wasi::ERRNO_NOTSUP,
"closing a preopened file descriptor", "closing a preopened file descriptor",
); );
// Try to renumber over a preopened directory handle. // Try to renumber over a preopened directory handle.
assert_eq!( assert_eq!(
wasi_unstable::fd_renumber(dir_fd, pre_fd), wasi::fd_renumber(dir_fd, pre_fd).unwrap_err().raw_error(),
Err(wasi_unstable::ENOTSUP), wasi::ERRNO_NOTSUP,
"renumbering over a preopened file descriptor", "renumbering over a preopened file descriptor",
); );
// Ensure that dir_fd is still open. // Ensure that dir_fd is still open.
let mut dir_fdstat: wasi_unstable::FdStat = mem::zeroed(); let dir_fdstat = wasi::fd_fdstat_get(dir_fd).expect("failed fd_fdstat_get");
let mut status = wasi_fd_fdstat_get(dir_fd, &mut dir_fdstat);
assert_eq!(
status,
wasi_unstable::raw::__WASI_ESUCCESS,
"calling fd_fdstat on the scratch directory"
);
assert_eq!( assert_eq!(
dir_fdstat.fs_filetype, dir_fdstat.fs_filetype,
wasi_unstable::FILETYPE_DIRECTORY, wasi::FILETYPE_DIRECTORY,
"expected the scratch directory to be a directory", "expected the scratch directory to be a directory",
); );
// Try to renumber a preopened directory handle. // Try to renumber a preopened directory handle.
assert_eq!( assert_eq!(
wasi_unstable::fd_renumber(pre_fd, dir_fd), wasi::fd_renumber(pre_fd, dir_fd).unwrap_err().raw_error(),
Err(wasi_unstable::ENOTSUP), wasi::ERRNO_NOTSUP,
"renumbering over a preopened file descriptor", "renumbering over a preopened file descriptor",
); );
// Ensure that dir_fd is still open. // Ensure that dir_fd is still open.
status = wasi_fd_fdstat_get(dir_fd, &mut dir_fdstat); let dir_fdstat = wasi::fd_fdstat_get(dir_fd).expect("failed fd_fdstat_get");
assert_eq!(
status,
wasi_unstable::raw::__WASI_ESUCCESS,
"calling fd_fdstat on the scratch directory"
);
assert_eq!( assert_eq!(
dir_fdstat.fs_filetype, dir_fdstat.fs_filetype,
wasi_unstable::FILETYPE_DIRECTORY, wasi::FILETYPE_DIRECTORY,
"expected the scratch directory to be a directory", "expected the scratch directory to be a directory",
); );
} }
@@ -70,7 +56,7 @@ fn main() {
}; };
// Open scratch directory // Open scratch directory
let dir_fd = match open_scratch_directory(&arg) { let dir_fd = match open_scratch_directory_new(&arg) {
Ok(dir_fd) => dir_fd, Ok(dir_fd) => dir_fd,
Err(err) => { Err(err) => {
eprintln!("{}", err); eprintln!("{}", err);

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file}; use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file};
use wasi_tests::wasi_wrappers::wasi_path_open; use wasi_tests::wasi_wrappers::wasi_path_open;

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::cleanup_file; use wasi_tests::utils::cleanup_file;
use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_symlink}; use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_symlink};

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, mem, process}; use std::{env, mem, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, close_fd, create_dir}; use wasi_tests::utils::{cleanup_dir, close_fd, create_dir};
use wasi_tests::wasi_wrappers::{wasi_fd_fdstat_get, wasi_fd_seek, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_fdstat_get, wasi_fd_seek, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{wasi_fd_advise, wasi_fd_filestat_get, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_advise, wasi_fd_filestat_get, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{cmp::min, env, mem, process, slice, str}; use std::{cmp::min, env, mem, process, slice, str};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_fd_readdir, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_fd_readdir, wasi_path_open};

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_filestat_get, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{wasi_fd_pread, wasi_fd_pwrite, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_pread, wasi_fd_pwrite, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{wasi_fd_seek, wasi_fd_tell, wasi_fd_write, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_seek, wasi_fd_tell, wasi_fd_write, wasi_path_open};

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd, create_file}; use wasi_tests::utils::{cleanup_file, close_fd, create_file};
use wasi_tests::wasi_wrappers::{wasi_fd_read, wasi_fd_write, wasi_path_open}; use wasi_tests::wasi_wrappers::{wasi_fd_read, wasi_fd_write, wasi_path_open};

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{close_fd, create_dir, create_file}; use wasi_tests::utils::{close_fd, create_dir, create_file};
use wasi_tests::wasi_wrappers::{ use wasi_tests::wasi_wrappers::{

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::wasi_path_open; use wasi_tests::wasi_wrappers::wasi_path_open;

View File

@@ -1,7 +1,7 @@
use libc; use libc;
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd, create_dir, create_file}; use wasi_tests::utils::{cleanup_file, close_fd, create_dir, create_file};
use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_remove_directory, wasi_path_symlink}; use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_remove_directory, wasi_path_symlink};

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::{ use wasi_tests::wasi_wrappers::{

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file}; use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file};
use wasi_tests::wasi_wrappers::{ use wasi_tests::wasi_wrappers::{

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, close_fd}; use wasi_tests::utils::{cleanup_file, close_fd};
use wasi_tests::wasi_wrappers::wasi_path_open; use wasi_tests::wasi_wrappers::wasi_path_open;

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::close_fd; use wasi_tests::utils::close_fd;
use wasi_tests::wasi_wrappers::wasi_path_open; use wasi_tests::wasi_wrappers::wasi_path_open;

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, cleanup_file, close_fd, create_dir, create_file}; use wasi_tests::utils::{cleanup_dir, cleanup_file, close_fd, create_dir, create_file};
use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_rename}; use wasi_tests::wasi_wrappers::{wasi_path_open, wasi_path_rename};

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file}; use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file};
use wasi_tests::wasi_wrappers::wasi_path_rename; use wasi_tests::wasi_wrappers::wasi_path_rename;

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file}; use wasi_tests::utils::{cleanup_dir, cleanup_file, create_dir, create_file};
use wasi_tests::wasi_wrappers::wasi_path_symlink; use wasi_tests::wasi_wrappers::wasi_path_symlink;

View File

@@ -1,6 +1,6 @@
use more_asserts::assert_gt; use more_asserts::assert_gt;
use std::{env, mem::MaybeUninit, process}; use std::{env, mem::MaybeUninit, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::{ use wasi_tests::{
open_scratch_directory, open_scratch_directory,
utils::{cleanup_file, close_fd}, utils::{cleanup_file, close_fd},

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::{cleanup_file, create_file}; use wasi_tests::utils::{cleanup_file, create_file};
use wasi_tests::wasi_wrappers::{wasi_path_readlink, wasi_path_symlink}; use wasi_tests::wasi_wrappers::{wasi_path_readlink, wasi_path_symlink};

View File

@@ -1,5 +1,5 @@
use std::{env, process}; use std::{env, process};
use wasi::wasi_unstable; use wasi_old::wasi_unstable;
use wasi_tests::open_scratch_directory; use wasi_tests::open_scratch_directory;
use wasi_tests::utils::cleanup_file; use wasi_tests::utils::cleanup_file;
use wasi_tests::wasi_wrappers::{wasi_path_readlink, wasi_path_symlink}; use wasi_tests::wasi_wrappers::{wasi_path_readlink, wasi_path_symlink};

Some files were not shown because too many files have changed in this diff Show More