Merge pull request #2791 from peterhuene/compile-command
Add a compile command to Wasmtime.
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
use anyhow::Result;
|
||||
use structopt::{clap::AppSettings, clap::ErrorKind, StructOpt};
|
||||
use wasmtime_cli::commands::{
|
||||
ConfigCommand, RunCommand, WasmToObjCommand, WastCommand, WASM2OBJ_AFTER_HELP,
|
||||
CompileCommand, ConfigCommand, RunCommand, SettingsCommand, WasmToObjCommand, WastCommand,
|
||||
};
|
||||
|
||||
/// Wasmtime WebAssembly Runtime
|
||||
@@ -38,10 +38,14 @@ enum WasmtimeApp {
|
||||
// !!! IMPORTANT: if subcommands are added or removed, update `parse_module` in `src/commands/run.rs`. !!!
|
||||
/// Controls Wasmtime configuration settings
|
||||
Config(ConfigCommand),
|
||||
/// Compiles a WebAssembly module.
|
||||
Compile(CompileCommand),
|
||||
/// Runs a WebAssembly module
|
||||
Run(RunCommand),
|
||||
/// Displays available Cranelift settings for a target.
|
||||
Settings(SettingsCommand),
|
||||
/// Translates a WebAssembly module to native object file
|
||||
#[structopt(name = "wasm2obj", after_help = WASM2OBJ_AFTER_HELP)]
|
||||
#[structopt(name = "wasm2obj")]
|
||||
WasmToObj(WasmToObjCommand),
|
||||
/// Runs a WebAssembly test script file
|
||||
Wast(WastCommand),
|
||||
@@ -49,10 +53,12 @@ enum WasmtimeApp {
|
||||
|
||||
impl WasmtimeApp {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
pub fn execute(self) -> Result<()> {
|
||||
match self {
|
||||
Self::Config(c) => c.execute(),
|
||||
Self::Compile(c) => c.execute(),
|
||||
Self::Run(c) => c.execute(),
|
||||
Self::Settings(c) => c.execute(),
|
||||
Self::WasmToObj(c) => c.execute(),
|
||||
Self::Wast(c) => c.execute(),
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The module for the Wasmtime CLI commands.
|
||||
|
||||
mod compile;
|
||||
mod config;
|
||||
mod run;
|
||||
mod settings;
|
||||
mod wasm2obj;
|
||||
mod wast;
|
||||
|
||||
pub use self::{config::*, run::*, wasm2obj::*, wast::*};
|
||||
pub use self::{compile::*, config::*, run::*, settings::*, wasm2obj::*, wast::*};
|
||||
|
||||
273
src/commands/compile.rs
Normal file
273
src/commands/compile.rs
Normal file
@@ -0,0 +1,273 @@
|
||||
//! The module that implements the `wasmtime compile` command.
|
||||
|
||||
use crate::CommonOptions;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
use target_lexicon::Triple;
|
||||
use wasmtime::Engine;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref AFTER_HELP: String = {
|
||||
format!(
|
||||
"By default, no CPU features or presets will be enabled for the compilation.\n\
|
||||
\n\
|
||||
{}\
|
||||
\n\
|
||||
Usage examples:\n\
|
||||
\n\
|
||||
Compiling a WebAssembly module for the current platform:\n\
|
||||
\n \
|
||||
wasmtime compile example.wasm
|
||||
\n\
|
||||
Specifying the output file:\n\
|
||||
\n \
|
||||
wasmtime compile -o output.cwasm input.wasm\n\
|
||||
\n\
|
||||
Compiling for a specific platform (Linux) and CPU preset (Skylake):\n\
|
||||
\n \
|
||||
wasmtime compile --target x86_64-unknown-linux --cranelift-enable skylake foo.wasm\n",
|
||||
crate::WASM_FEATURES.as_str()
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// Compiles a WebAssembly module.
|
||||
#[derive(StructOpt)]
|
||||
#[structopt(
|
||||
name = "compile",
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
setting = AppSettings::ColoredHelp,
|
||||
after_help = AFTER_HELP.as_str()
|
||||
)]
|
||||
pub struct CompileCommand {
|
||||
#[structopt(flatten)]
|
||||
common: CommonOptions,
|
||||
|
||||
/// Enable support for interrupting WebAssembly code.
|
||||
#[structopt(long)]
|
||||
interruptable: bool,
|
||||
|
||||
/// The target triple; default is the host triple
|
||||
#[structopt(long, value_name = "TARGET")]
|
||||
target: Option<String>,
|
||||
|
||||
/// The path of the output compiled module; defaults to <MODULE>.cwasm
|
||||
#[structopt(short = "o", long, value_name = "OUTPUT", parse(from_os_str))]
|
||||
output: Option<PathBuf>,
|
||||
|
||||
/// The path of the WebAssembly to compile
|
||||
#[structopt(index = 1, value_name = "MODULE", parse(from_os_str))]
|
||||
module: PathBuf,
|
||||
}
|
||||
|
||||
impl CompileCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(mut self) -> Result<()> {
|
||||
self.common.init_logging();
|
||||
|
||||
let target = self
|
||||
.target
|
||||
.take()
|
||||
.unwrap_or_else(|| Triple::host().to_string());
|
||||
|
||||
let mut config = self.common.config(Some(&target))?;
|
||||
config.interruptable(self.interruptable);
|
||||
|
||||
let engine = Engine::new(&config)?;
|
||||
|
||||
if self.module.file_name().is_none() {
|
||||
bail!(
|
||||
"'{}' is not a valid input module path",
|
||||
self.module.display()
|
||||
);
|
||||
}
|
||||
|
||||
let input = fs::read(&self.module).with_context(|| "failed to read input file")?;
|
||||
|
||||
let output = self.output.take().unwrap_or_else(|| {
|
||||
let mut output: PathBuf = self.module.file_name().unwrap().into();
|
||||
output.set_extension("cwasm");
|
||||
output
|
||||
});
|
||||
|
||||
fs::write(output, engine.precompile_module(&input)?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use tempfile::NamedTempFile;
|
||||
use wasmtime::{Instance, Module, Store};
|
||||
|
||||
#[test]
|
||||
fn test_successful_compile() -> Result<()> {
|
||||
let (mut input, input_path) = NamedTempFile::new()?.into_parts();
|
||||
input.write_all(
|
||||
"(module (func (export \"f\") (param i32) (result i32) local.get 0))".as_bytes(),
|
||||
)?;
|
||||
drop(input);
|
||||
|
||||
let output_path = NamedTempFile::new()?.into_temp_path();
|
||||
|
||||
let command = CompileCommand::from_iter_safe(vec![
|
||||
"compile",
|
||||
"--disable-logging",
|
||||
"-o",
|
||||
output_path.to_str().unwrap(),
|
||||
input_path.to_str().unwrap(),
|
||||
])?;
|
||||
|
||||
command.execute()?;
|
||||
|
||||
let engine = Engine::default();
|
||||
let module = Module::from_file(&engine, output_path)?;
|
||||
let store = Store::new(&engine);
|
||||
let instance = Instance::new(&store, &module, &[])?;
|
||||
let f = instance.get_typed_func::<i32, i32>("f")?;
|
||||
assert_eq!(f.call(1234).unwrap(), 1234);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[test]
|
||||
fn test_x64_flags_compile() -> Result<()> {
|
||||
let (mut input, input_path) = NamedTempFile::new()?.into_parts();
|
||||
input.write_all("(module)".as_bytes())?;
|
||||
drop(input);
|
||||
|
||||
let output_path = NamedTempFile::new()?.into_temp_path();
|
||||
|
||||
// Set all the x64 flags to make sure they work
|
||||
let command = CompileCommand::from_iter_safe(vec![
|
||||
"compile",
|
||||
"--disable-logging",
|
||||
"--cranelift-enable",
|
||||
"has_sse3",
|
||||
"--cranelift-enable",
|
||||
"has_ssse3",
|
||||
"--cranelift-enable",
|
||||
"has_sse41",
|
||||
"--cranelift-enable",
|
||||
"has_sse42",
|
||||
"--cranelift-enable",
|
||||
"has_avx",
|
||||
"--cranelift-enable",
|
||||
"has_avx2",
|
||||
"--cranelift-enable",
|
||||
"has_avx512dq",
|
||||
"--cranelift-enable",
|
||||
"has_avx512vl",
|
||||
"--cranelift-enable",
|
||||
"has_avx512f",
|
||||
"--cranelift-enable",
|
||||
"has_popcnt",
|
||||
"--cranelift-enable",
|
||||
"has_bmi1",
|
||||
"--cranelift-enable",
|
||||
"has_bmi2",
|
||||
"--cranelift-enable",
|
||||
"has_lzcnt",
|
||||
"-o",
|
||||
output_path.to_str().unwrap(),
|
||||
input_path.to_str().unwrap(),
|
||||
])?;
|
||||
|
||||
command.execute()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
#[test]
|
||||
fn test_aarch64_flags_compile() -> Result<()> {
|
||||
let (mut input, input_path) = NamedTempFile::new()?.into_parts();
|
||||
input.write_all("(module)".as_bytes())?;
|
||||
drop(input);
|
||||
|
||||
let output_path = NamedTempFile::new()?.into_temp_path();
|
||||
|
||||
// Set all the aarch64 flags to make sure they work
|
||||
let command = CompileCommand::from_iter_safe(vec![
|
||||
"compile",
|
||||
"--disable-logging",
|
||||
"--cranelift-enable",
|
||||
"has_lse",
|
||||
"-o",
|
||||
output_path.to_str().unwrap(),
|
||||
input_path.to_str().unwrap(),
|
||||
])?;
|
||||
|
||||
command.execute()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[test]
|
||||
fn test_unsupported_flags_compile() -> Result<()> {
|
||||
let (mut input, input_path) = NamedTempFile::new()?.into_parts();
|
||||
input.write_all("(module)".as_bytes())?;
|
||||
drop(input);
|
||||
|
||||
let output_path = NamedTempFile::new()?.into_temp_path();
|
||||
|
||||
// aarch64 flags should not be supported
|
||||
let command = CompileCommand::from_iter_safe(vec![
|
||||
"compile",
|
||||
"--disable-logging",
|
||||
"--cranelift-enable",
|
||||
"has_lse",
|
||||
"-o",
|
||||
output_path.to_str().unwrap(),
|
||||
input_path.to_str().unwrap(),
|
||||
])?;
|
||||
|
||||
assert_eq!(
|
||||
command.execute().unwrap_err().to_string(),
|
||||
"No existing setting named 'has_lse'"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[test]
|
||||
fn test_x64_presets_compile() -> Result<()> {
|
||||
let (mut input, input_path) = NamedTempFile::new()?.into_parts();
|
||||
input.write_all("(module)".as_bytes())?;
|
||||
drop(input);
|
||||
|
||||
let output_path = NamedTempFile::new()?.into_temp_path();
|
||||
|
||||
for preset in &[
|
||||
"nehalem",
|
||||
"haswell",
|
||||
"broadwell",
|
||||
"skylake",
|
||||
"cannonlake",
|
||||
"icelake",
|
||||
"znver1",
|
||||
] {
|
||||
let command = CompileCommand::from_iter_safe(vec![
|
||||
"compile",
|
||||
"--disable-logging",
|
||||
"--cranelift-enable",
|
||||
preset,
|
||||
"-o",
|
||||
output_path.to_str().unwrap(),
|
||||
input_path.to_str().unwrap(),
|
||||
])?;
|
||||
|
||||
command.execute()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ pub enum ConfigCommand {
|
||||
|
||||
impl ConfigCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
pub fn execute(self) -> Result<()> {
|
||||
match self {
|
||||
Self::New(c) => c.execute(),
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub struct ConfigNewCommand {
|
||||
|
||||
impl ConfigNewCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
pub fn execute(self) -> Result<()> {
|
||||
let path = wasmtime_cache::create_new_config(self.path.as_ref())?;
|
||||
|
||||
println!(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The module that implements the `wasmtime run` command.
|
||||
|
||||
use crate::{init_file_per_thread_logger, CommonOptions};
|
||||
use crate::CommonOptions;
|
||||
use anyhow::{bail, Context as _, Result};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
@@ -28,9 +28,8 @@ use wasmtime_wasi_crypto::{
|
||||
fn parse_module(s: &OsStr) -> Result<PathBuf, OsString> {
|
||||
// Do not accept wasmtime subcommand names as the module name
|
||||
match s.to_str() {
|
||||
Some("help") | Some("config") | Some("run") | Some("wasm2obj") | Some("wast") => {
|
||||
Err("module name cannot be the same as a subcommand".into())
|
||||
}
|
||||
Some("help") | Some("config") | Some("run") | Some("wasm2obj") | Some("wast")
|
||||
| Some("compile") => Err("module name cannot be the same as a subcommand".into()),
|
||||
_ => Ok(s.into()),
|
||||
}
|
||||
}
|
||||
@@ -69,9 +68,15 @@ fn parse_preloads(s: &str) -> Result<(String, PathBuf)> {
|
||||
Ok((parts[0].into(), parts[1].into()))
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref AFTER_HELP: String = {
|
||||
crate::WASM_FEATURES.to_string()
|
||||
};
|
||||
}
|
||||
|
||||
/// Runs a WebAssembly module
|
||||
#[derive(StructOpt)]
|
||||
#[structopt(name = "run", setting = AppSettings::TrailingVarArg)]
|
||||
#[structopt(name = "run", setting = AppSettings::TrailingVarArg, after_help = AFTER_HELP.as_str())]
|
||||
pub struct RunCommand {
|
||||
#[structopt(flatten)]
|
||||
common: CommonOptions,
|
||||
@@ -96,7 +101,7 @@ pub struct RunCommand {
|
||||
#[structopt(
|
||||
index = 1,
|
||||
required = true,
|
||||
value_name = "WASM_MODULE",
|
||||
value_name = "MODULE",
|
||||
parse(try_from_os_str = parse_module),
|
||||
)]
|
||||
module: PathBuf,
|
||||
@@ -127,14 +132,9 @@ pub struct RunCommand {
|
||||
impl RunCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
if self.common.log_to_files {
|
||||
let prefix = "wasmtime.dbg.";
|
||||
init_file_per_thread_logger(prefix);
|
||||
} else {
|
||||
pretty_env_logger::init();
|
||||
}
|
||||
self.common.init_logging();
|
||||
|
||||
let mut config = self.common.config()?;
|
||||
let mut config = self.common.config(None)?;
|
||||
if self.wasm_timeout.is_some() {
|
||||
config.interruptable(true);
|
||||
}
|
||||
|
||||
98
src/commands/settings.rs
Normal file
98
src/commands/settings.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! The module that implements the `wasmtime settings` command.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::str::FromStr;
|
||||
use structopt::StructOpt;
|
||||
use wasmtime_environ::settings::{self, Setting, SettingKind};
|
||||
use wasmtime_jit::native;
|
||||
|
||||
/// Displays available Cranelift settings for a target.
|
||||
#[derive(StructOpt)]
|
||||
#[structopt(name = "run")]
|
||||
pub struct SettingsCommand {
|
||||
/// The target triple to get the settings for; defaults to the host triple.
|
||||
#[structopt(long, value_name = "TARGET")]
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
impl SettingsCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(self) -> Result<()> {
|
||||
let settings = match &self.target {
|
||||
Some(target) => {
|
||||
native::lookup(target_lexicon::Triple::from_str(target).map_err(|e| anyhow!(e))?)?
|
||||
}
|
||||
None => native::builder(),
|
||||
};
|
||||
|
||||
let mut enums = (Vec::new(), 0, "Enum settings:");
|
||||
let mut nums = (Vec::new(), 0, "Numerical settings:");
|
||||
let mut bools = (Vec::new(), 0, "Boolean settings:");
|
||||
let mut presets = (Vec::new(), 0, "Presets:");
|
||||
|
||||
for setting in settings.iter() {
|
||||
let (collection, max, _) = match setting.kind {
|
||||
SettingKind::Enum => &mut enums,
|
||||
SettingKind::Num => &mut nums,
|
||||
SettingKind::Bool => &mut bools,
|
||||
SettingKind::Preset => &mut presets,
|
||||
};
|
||||
|
||||
if setting.name.len() > *max {
|
||||
*max = setting.name.len();
|
||||
}
|
||||
|
||||
collection.push(setting);
|
||||
}
|
||||
|
||||
if enums.0.is_empty() && nums.0.is_empty() && bools.0.is_empty() && presets.0.is_empty() {
|
||||
println!("Target '{}' has no settings.", settings.triple());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("Cranelift settings for target '{}':", settings.triple());
|
||||
|
||||
for (collection, max, header) in &mut [enums, nums, bools, presets] {
|
||||
if collection.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
collection.sort_by_key(|k| k.name);
|
||||
println!();
|
||||
Self::print_settings(header, collection, *max);
|
||||
}
|
||||
|
||||
if self.target.is_none() {
|
||||
let isa = settings.finish(settings::Flags::new(settings::builder()));
|
||||
println!();
|
||||
println!("Settings inferred for the current host:");
|
||||
|
||||
let mut values = isa.isa_flags();
|
||||
values.sort_by_key(|k| k.name);
|
||||
|
||||
for value in values {
|
||||
if value.as_bool().unwrap_or(false) {
|
||||
println!(" {}", value.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_settings(header: &str, settings: &[Setting], width: usize) {
|
||||
println!("{}", header);
|
||||
for setting in settings {
|
||||
println!(
|
||||
" {:width$} {}{}",
|
||||
setting.name,
|
||||
setting.description,
|
||||
setting
|
||||
.values
|
||||
.map(|v| format!(" Supported values: {}.", v.join(", ")))
|
||||
.unwrap_or("".to_string()),
|
||||
width = width + 2
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,26 @@
|
||||
//! The module that implements the `wasmtime wasm2obj` command.
|
||||
|
||||
use crate::obj::compile_to_obj;
|
||||
use crate::{init_file_per_thread_logger, pick_compilation_strategy, CommonOptions};
|
||||
use anyhow::{anyhow, Context as _, Result};
|
||||
use crate::{parse_target, pick_compilation_strategy, CommonOptions};
|
||||
use anyhow::{Context as _, Result};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
use target_lexicon::Triple;
|
||||
|
||||
/// The after help text for the `wasm2obj` command.
|
||||
pub const WASM2OBJ_AFTER_HELP: &str = "The translation is dependent on the environment chosen.\n\
|
||||
The default is a dummy environment that produces placeholder values.";
|
||||
|
||||
fn parse_target(s: &str) -> Result<Triple> {
|
||||
Triple::from_str(&s).map_err(|e| anyhow!(e))
|
||||
lazy_static::lazy_static! {
|
||||
static ref AFTER_HELP: String = {
|
||||
format!(
|
||||
"The translation is dependent on the environment chosen.\n\
|
||||
The default is a dummy environment that produces placeholder values.\n\
|
||||
\n\
|
||||
{}",
|
||||
crate::WASM_FEATURES.as_str()
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// Translates a WebAssembly module to native object file
|
||||
@@ -26,7 +29,7 @@ fn parse_target(s: &str) -> Result<Triple> {
|
||||
name = "wasm2obj",
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
setting = AppSettings::ColoredHelp,
|
||||
after_help = WASM2OBJ_AFTER_HELP,
|
||||
after_help = AFTER_HELP.as_str(),
|
||||
)]
|
||||
pub struct WasmToObjCommand {
|
||||
#[structopt(flatten)]
|
||||
@@ -47,17 +50,8 @@ pub struct WasmToObjCommand {
|
||||
|
||||
impl WasmToObjCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
self.handle_module()
|
||||
}
|
||||
|
||||
fn handle_module(&self) -> Result<()> {
|
||||
if self.common.log_to_files {
|
||||
let prefix = "wasm2obj.dbg.";
|
||||
init_file_per_thread_logger(prefix);
|
||||
} else {
|
||||
pretty_env_logger::init();
|
||||
}
|
||||
pub fn execute(self) -> Result<()> {
|
||||
self.common.init_logging();
|
||||
|
||||
let strategy = pick_compilation_strategy(self.common.cranelift, self.common.lightbeam)?;
|
||||
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
//! The module that implements the `wasmtime wast` command.
|
||||
|
||||
use crate::{init_file_per_thread_logger, CommonOptions};
|
||||
use crate::CommonOptions;
|
||||
use anyhow::{Context as _, Result};
|
||||
use std::path::PathBuf;
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
use wasmtime::{Engine, Store};
|
||||
use wasmtime_wast::WastContext;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref AFTER_HELP: String = {
|
||||
crate::WASM_FEATURES.to_string()
|
||||
};
|
||||
}
|
||||
|
||||
/// Runs a WebAssembly test script file
|
||||
#[derive(StructOpt)]
|
||||
#[structopt(
|
||||
name = "wast",
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
setting = AppSettings::ColoredHelp,
|
||||
after_help = AFTER_HELP.as_str(),
|
||||
)]
|
||||
pub struct WastCommand {
|
||||
#[structopt(flatten)]
|
||||
@@ -25,15 +32,10 @@ pub struct WastCommand {
|
||||
|
||||
impl WastCommand {
|
||||
/// Executes the command.
|
||||
pub fn execute(&self) -> Result<()> {
|
||||
if self.common.log_to_files {
|
||||
let prefix = "wast.dbg.";
|
||||
init_file_per_thread_logger(prefix);
|
||||
} else {
|
||||
pretty_env_logger::init();
|
||||
}
|
||||
pub fn execute(self) -> Result<()> {
|
||||
self.common.init_logging();
|
||||
|
||||
let config = self.common.config()?;
|
||||
let config = self.common.config(None)?;
|
||||
let store = Store::new(&Engine::new(&config)?);
|
||||
let mut wast_context = WastContext::new(store);
|
||||
|
||||
|
||||
401
src/lib.rs
401
src/lib.rs
@@ -23,12 +23,55 @@
|
||||
)
|
||||
)]
|
||||
|
||||
const SUPPORTED_WASM_FEATURES: &[(&str, &str)] = &[
|
||||
("all", "enables all supported WebAssembly features"),
|
||||
(
|
||||
"bulk-memory",
|
||||
"enables support for bulk memory instructions",
|
||||
),
|
||||
(
|
||||
"module-linking",
|
||||
"enables support for the module-linking proposal",
|
||||
),
|
||||
(
|
||||
"multi-memory",
|
||||
"enables support for the multi-memory proposal",
|
||||
),
|
||||
("multi-value", "enables support for multi-value functions"),
|
||||
("reference-types", "enables support for reference types"),
|
||||
("simd", "enables support for proposed SIMD instructions"),
|
||||
("threads", "enables support for WebAssembly threads"),
|
||||
];
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref WASM_FEATURES: String = {
|
||||
use std::fmt::Write;
|
||||
|
||||
let mut s = String::new();
|
||||
writeln!(&mut s, "Supported values for `--wasm-features`:").unwrap();
|
||||
writeln!(&mut s).unwrap();
|
||||
|
||||
let max = SUPPORTED_WASM_FEATURES.iter().max_by_key(|(name, _)| name.len()).unwrap();
|
||||
|
||||
for (name, desc) in SUPPORTED_WASM_FEATURES.iter() {
|
||||
writeln!(&mut s, "{:width$} {}", name, desc, width = max.0.len() + 2).unwrap();
|
||||
}
|
||||
|
||||
writeln!(&mut s).unwrap();
|
||||
writeln!(&mut s, "Features prefixed with '-' will be disabled.").unwrap();
|
||||
|
||||
s
|
||||
};
|
||||
}
|
||||
|
||||
pub mod commands;
|
||||
mod obj;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
use target_lexicon::Triple;
|
||||
use wasmtime::{Config, ProfilingStrategy, Strategy};
|
||||
|
||||
pub use obj::compile_to_obj;
|
||||
@@ -91,6 +134,10 @@ struct CommonOptions {
|
||||
#[structopt(long, conflicts_with = "lightbeam")]
|
||||
cranelift: bool,
|
||||
|
||||
/// Disable logging.
|
||||
#[structopt(long, conflicts_with = "log_to_files")]
|
||||
disable_logging: bool,
|
||||
|
||||
/// Log to per-thread log files instead of stderr.
|
||||
#[structopt(long)]
|
||||
log_to_files: bool,
|
||||
@@ -103,38 +150,42 @@ struct CommonOptions {
|
||||
#[structopt(long)]
|
||||
disable_cache: bool,
|
||||
|
||||
/// Enable support for proposed SIMD instructions
|
||||
#[structopt(long)]
|
||||
/// Enable support for proposed SIMD instructions (deprecated; use `--wasm-features=simd`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_simd: bool,
|
||||
|
||||
/// Enable support for reference types
|
||||
#[structopt(long)]
|
||||
enable_reference_types: Option<bool>,
|
||||
/// Enable support for reference types (deprecated; use `--wasm-features=reference-types`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_reference_types: bool,
|
||||
|
||||
/// Enable support for multi-value functions
|
||||
#[structopt(long)]
|
||||
enable_multi_value: Option<bool>,
|
||||
/// Enable support for multi-value functions (deprecated; use `--wasm-features=multi-value`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_multi_value: bool,
|
||||
|
||||
/// Enable support for Wasm threads
|
||||
#[structopt(long)]
|
||||
/// Enable support for Wasm threads (deprecated; use `--wasm-features=threads`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_threads: bool,
|
||||
|
||||
/// Enable support for bulk memory instructions
|
||||
#[structopt(long)]
|
||||
enable_bulk_memory: Option<bool>,
|
||||
/// Enable support for bulk memory instructions (deprecated; use `--wasm-features=bulk-memory`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_bulk_memory: bool,
|
||||
|
||||
/// Enable support for the multi-memory proposal
|
||||
#[structopt(long)]
|
||||
/// Enable support for the multi-memory proposal (deprecated; use `--wasm-features=multi-memory`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_multi_memory: bool,
|
||||
|
||||
/// Enable support for the module-linking proposal
|
||||
#[structopt(long)]
|
||||
/// Enable support for the module-linking proposal (deprecated; use `--wasm-features=module-linking`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_module_linking: bool,
|
||||
|
||||
/// Enable all experimental Wasm features
|
||||
#[structopt(long)]
|
||||
/// Enable all experimental Wasm features (deprecated; use `--wasm-features=all`)
|
||||
#[structopt(long, hidden = true)]
|
||||
enable_all: bool,
|
||||
|
||||
/// Enables or disables WebAssembly features
|
||||
#[structopt(long, value_name = "FEATURE,FEATURE,...", parse(try_from_str = parse_wasm_features))]
|
||||
wasm_features: Option<wasmparser::WasmFeatures>,
|
||||
|
||||
/// Use Lightbeam for all compilation
|
||||
#[structopt(long, conflicts_with = "cranelift")]
|
||||
lightbeam: bool,
|
||||
@@ -151,30 +202,42 @@ struct CommonOptions {
|
||||
#[structopt(short = "O", long)]
|
||||
optimize: bool,
|
||||
|
||||
/// Optimization level for generated functions (0 (none), 1, 2 (most), or s
|
||||
/// (size))
|
||||
/// Optimization level for generated functions
|
||||
/// Supported levels: 0 (none), 1, 2 (most), or s (size); default is "most"
|
||||
#[structopt(
|
||||
long,
|
||||
value_name = "LEVEL",
|
||||
parse(try_from_str = parse_opt_level),
|
||||
default_value = "2",
|
||||
verbatim_doc_comment,
|
||||
)]
|
||||
opt_level: wasmtime::OptLevel,
|
||||
opt_level: Option<wasmtime::OptLevel>,
|
||||
|
||||
/// Other Cranelift flags to be passed down to Cranelift.
|
||||
#[structopt(long, parse(try_from_str = parse_cranelift_flag))]
|
||||
cranelift_flags: Vec<CraneliftFlag>,
|
||||
/// Set a Cranelift setting to a given value.
|
||||
/// Use `wasmtime settings` to list Cranelift settings for a target.
|
||||
#[structopt(long = "cranelift-set", value_name = "NAME=VALUE", number_of_values = 1, verbatim_doc_comment, parse(try_from_str = parse_cranelift_flag))]
|
||||
cranelift_set: Vec<(String, String)>,
|
||||
|
||||
/// Enable a Cranelift boolean setting or preset.
|
||||
/// Use `wasmtime settings` to list Cranelift settings for a target.
|
||||
#[structopt(
|
||||
long,
|
||||
value_name = "SETTING",
|
||||
number_of_values = 1,
|
||||
verbatim_doc_comment
|
||||
)]
|
||||
cranelift_enable: Vec<String>,
|
||||
|
||||
/// Maximum size in bytes of wasm memory before it becomes dynamically
|
||||
/// relocatable instead of up-front-reserved.
|
||||
#[structopt(long)]
|
||||
#[structopt(long, value_name = "MAXIMUM")]
|
||||
static_memory_maximum_size: Option<u64>,
|
||||
|
||||
/// Byte size of the guard region after static memories are allocated.
|
||||
#[structopt(long)]
|
||||
#[structopt(long, value_name = "SIZE")]
|
||||
static_memory_guard_size: Option<u64>,
|
||||
|
||||
/// Byte size of the guard region after dynamic memories are allocated.
|
||||
#[structopt(long)]
|
||||
#[structopt(long, value_name = "SIZE")]
|
||||
dynamic_memory_guard_size: Option<u64>,
|
||||
|
||||
/// Enable Cranelift's internal debug verifier (expensive)
|
||||
@@ -187,31 +250,48 @@ struct CommonOptions {
|
||||
}
|
||||
|
||||
impl CommonOptions {
|
||||
fn config(&self) -> Result<Config> {
|
||||
fn init_logging(&self) {
|
||||
if self.disable_logging {
|
||||
return;
|
||||
}
|
||||
if self.log_to_files {
|
||||
let prefix = "wasmtime.dbg.";
|
||||
init_file_per_thread_logger(prefix);
|
||||
} else {
|
||||
pretty_env_logger::init();
|
||||
}
|
||||
}
|
||||
|
||||
fn config(&self, target: Option<&str>) -> Result<Config> {
|
||||
let mut config = Config::new();
|
||||
|
||||
// Set the target before setting any cranelift options
|
||||
if let Some(target) = target {
|
||||
config.target(target)?;
|
||||
}
|
||||
|
||||
config
|
||||
.cranelift_debug_verifier(self.enable_cranelift_debug_verifier)
|
||||
.debug_info(self.debug_info)
|
||||
.wasm_simd(self.enable_simd || self.enable_all)
|
||||
.wasm_bulk_memory(self.enable_bulk_memory.unwrap_or(true) || self.enable_all)
|
||||
.wasm_reference_types(
|
||||
self.enable_reference_types
|
||||
.unwrap_or(cfg!(target_arch = "x86_64"))
|
||||
|| self.enable_all,
|
||||
)
|
||||
.wasm_multi_value(self.enable_multi_value.unwrap_or(true) || self.enable_all)
|
||||
.wasm_threads(self.enable_threads || self.enable_all)
|
||||
.wasm_multi_memory(self.enable_multi_memory || self.enable_all)
|
||||
.wasm_module_linking(self.enable_module_linking || self.enable_all)
|
||||
.cranelift_opt_level(self.opt_level())
|
||||
.strategy(pick_compilation_strategy(self.cranelift, self.lightbeam)?)?
|
||||
.profiler(pick_profiling_strategy(self.jitdump, self.vtune)?)?
|
||||
.cranelift_nan_canonicalization(self.enable_cranelift_nan_canonicalization);
|
||||
for CraneliftFlag { name, value } in &self.cranelift_flags {
|
||||
|
||||
self.enable_wasm_features(&mut config);
|
||||
|
||||
for name in &self.cranelift_enable {
|
||||
unsafe {
|
||||
config.cranelift_other_flag(name, value)?;
|
||||
config.cranelift_flag_enable(name)?;
|
||||
}
|
||||
}
|
||||
|
||||
for (name, value) in &self.cranelift_set {
|
||||
unsafe {
|
||||
config.cranelift_flag_set(name, value)?;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.disable_cache {
|
||||
match &self.config {
|
||||
Some(path) => {
|
||||
@@ -222,22 +302,43 @@ impl CommonOptions {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(max) = self.static_memory_maximum_size {
|
||||
config.static_memory_maximum_size(max);
|
||||
}
|
||||
|
||||
if let Some(size) = self.static_memory_guard_size {
|
||||
config.static_memory_guard_size(size);
|
||||
}
|
||||
|
||||
if let Some(size) = self.dynamic_memory_guard_size {
|
||||
config.dynamic_memory_guard_size(size);
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn enable_wasm_features(&self, config: &mut Config) {
|
||||
let features = self.wasm_features.unwrap_or_default();
|
||||
|
||||
config
|
||||
.wasm_simd(features.simd || self.enable_simd || self.enable_all)
|
||||
.wasm_bulk_memory(features.bulk_memory || self.enable_bulk_memory || self.enable_all)
|
||||
.wasm_reference_types(
|
||||
features.reference_types || self.enable_reference_types || self.enable_all,
|
||||
)
|
||||
.wasm_multi_value(features.multi_value || self.enable_multi_value || self.enable_all)
|
||||
.wasm_threads(features.threads || self.enable_threads || self.enable_all)
|
||||
.wasm_multi_memory(features.multi_memory || self.enable_multi_memory || self.enable_all)
|
||||
.wasm_module_linking(
|
||||
features.module_linking || self.enable_module_linking || self.enable_all,
|
||||
);
|
||||
}
|
||||
|
||||
fn opt_level(&self) -> wasmtime::OptLevel {
|
||||
match (self.optimize, self.opt_level.clone()) {
|
||||
(true, _) => wasmtime::OptLevel::Speed,
|
||||
(false, other) => other,
|
||||
(false, other) => other.unwrap_or(wasmtime::OptLevel::Speed),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,12 +356,59 @@ fn parse_opt_level(opt_level: &str) -> Result<wasmtime::OptLevel> {
|
||||
}
|
||||
}
|
||||
|
||||
struct CraneliftFlag {
|
||||
name: String,
|
||||
value: String,
|
||||
}
|
||||
fn parse_wasm_features(features: &str) -> Result<wasmparser::WasmFeatures> {
|
||||
let features = features.trim();
|
||||
|
||||
fn parse_cranelift_flag(name_and_value: &str) -> Result<CraneliftFlag> {
|
||||
let mut all = None;
|
||||
let mut values: HashMap<_, _> = SUPPORTED_WASM_FEATURES
|
||||
.iter()
|
||||
.map(|(name, _)| (name.to_string(), None))
|
||||
.collect();
|
||||
|
||||
if features == "all" {
|
||||
all = Some(true);
|
||||
} else if features == "-all" {
|
||||
all = Some(false);
|
||||
} else {
|
||||
for feature in features.split(',') {
|
||||
let feature = feature.trim();
|
||||
|
||||
if feature.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (feature, value) = if feature.starts_with('-') {
|
||||
(&feature[1..], false)
|
||||
} else {
|
||||
(feature, true)
|
||||
};
|
||||
|
||||
if feature == "all" {
|
||||
bail!("'all' cannot be specified with other WebAssembly features");
|
||||
}
|
||||
|
||||
match values.get_mut(feature) {
|
||||
Some(v) => *v = Some(value),
|
||||
None => bail!("unsupported WebAssembly feature '{}'", feature),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(wasmparser::WasmFeatures {
|
||||
reference_types: all.unwrap_or(values["reference-types"].unwrap_or(true)),
|
||||
multi_value: all.unwrap_or(values["multi-value"].unwrap_or(true)),
|
||||
bulk_memory: all.unwrap_or(values["bulk-memory"].unwrap_or(true)),
|
||||
module_linking: all.unwrap_or(values["module-linking"].unwrap_or(false)),
|
||||
simd: all.unwrap_or(values["simd"].unwrap_or(false)),
|
||||
threads: all.unwrap_or(values["threads"].unwrap_or(false)),
|
||||
tail_call: false,
|
||||
deterministic_only: false,
|
||||
multi_memory: all.unwrap_or(values["multi-memory"].unwrap_or(false)),
|
||||
exceptions: false,
|
||||
memory64: false,
|
||||
})
|
||||
}
|
||||
fn parse_cranelift_flag(name_and_value: &str) -> Result<(String, String)> {
|
||||
let mut split = name_and_value.splitn(2, '=');
|
||||
let name = if let Some(name) = split.next() {
|
||||
name.to_string()
|
||||
@@ -272,5 +420,158 @@ fn parse_cranelift_flag(name_and_value: &str) -> Result<CraneliftFlag> {
|
||||
} else {
|
||||
bail!("missing value in cranelift flag");
|
||||
};
|
||||
Ok(CraneliftFlag { name, value })
|
||||
Ok((name, value))
|
||||
}
|
||||
|
||||
fn parse_target(s: &str) -> Result<Triple> {
|
||||
use std::str::FromStr;
|
||||
Triple::from_str(&s).map_err(|e| anyhow::anyhow!(e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_all_features() -> Result<()> {
|
||||
let options = CommonOptions::from_iter_safe(vec!["foo", "--wasm-features=all"])?;
|
||||
|
||||
let wasmparser::WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
module_linking,
|
||||
simd,
|
||||
threads,
|
||||
tail_call,
|
||||
deterministic_only,
|
||||
multi_memory,
|
||||
exceptions,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert!(reference_types);
|
||||
assert!(multi_value);
|
||||
assert!(bulk_memory);
|
||||
assert!(module_linking);
|
||||
assert!(simd);
|
||||
assert!(threads);
|
||||
assert!(!tail_call); // Not supported
|
||||
assert!(!deterministic_only); // Not supported
|
||||
assert!(multi_memory);
|
||||
assert!(!exceptions); // Not supported
|
||||
assert!(!memory64); // Not supported
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_features() -> Result<()> {
|
||||
let options = CommonOptions::from_iter_safe(vec!["foo", "--wasm-features=-all"])?;
|
||||
|
||||
let wasmparser::WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
module_linking,
|
||||
simd,
|
||||
threads,
|
||||
tail_call,
|
||||
deterministic_only,
|
||||
multi_memory,
|
||||
exceptions,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert!(!reference_types);
|
||||
assert!(!multi_value);
|
||||
assert!(!bulk_memory);
|
||||
assert!(!module_linking);
|
||||
assert!(!simd);
|
||||
assert!(!threads);
|
||||
assert!(!tail_call);
|
||||
assert!(!deterministic_only);
|
||||
assert!(!multi_memory);
|
||||
assert!(!exceptions);
|
||||
assert!(!memory64);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_features() -> Result<()> {
|
||||
let options = CommonOptions::from_iter_safe(vec![
|
||||
"foo",
|
||||
"--wasm-features=-reference-types,simd,multi-memory",
|
||||
])?;
|
||||
|
||||
let wasmparser::WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
module_linking,
|
||||
simd,
|
||||
threads,
|
||||
tail_call,
|
||||
deterministic_only,
|
||||
multi_memory,
|
||||
exceptions,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert!(!reference_types);
|
||||
assert!(multi_value);
|
||||
assert!(bulk_memory);
|
||||
assert!(!module_linking);
|
||||
assert!(simd);
|
||||
assert!(!threads);
|
||||
assert!(!tail_call); // Not supported
|
||||
assert!(!deterministic_only); // Not supported
|
||||
assert!(multi_memory);
|
||||
assert!(!exceptions); // Not supported
|
||||
assert!(!memory64); // Not supported
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! feature_test {
|
||||
($test_name:ident, $name:ident, $flag:literal) => {
|
||||
#[test]
|
||||
fn $test_name() -> Result<()> {
|
||||
let options =
|
||||
CommonOptions::from_iter_safe(vec!["foo", concat!("--wasm-features=", $flag)])?;
|
||||
|
||||
let wasmparser::WasmFeatures { $name, .. } = options.wasm_features.unwrap();
|
||||
|
||||
assert!($name);
|
||||
|
||||
let options = CommonOptions::from_iter_safe(vec![
|
||||
"foo",
|
||||
concat!("--wasm-features=-", $flag),
|
||||
])?;
|
||||
|
||||
let wasmparser::WasmFeatures { $name, .. } = options.wasm_features.unwrap();
|
||||
|
||||
assert!(!$name);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
feature_test!(
|
||||
test_reference_types_feature,
|
||||
reference_types,
|
||||
"reference-types"
|
||||
);
|
||||
feature_test!(test_multi_value_feature, multi_value, "multi-value");
|
||||
feature_test!(test_bulk_memory_feature, bulk_memory, "bulk-memory");
|
||||
feature_test!(
|
||||
test_module_linking_feature,
|
||||
module_linking,
|
||||
"module-linking"
|
||||
);
|
||||
feature_test!(test_simd_feature, simd, "simd");
|
||||
feature_test!(test_threads_feature, threads, "threads");
|
||||
feature_test!(test_multi_memory_feature, multi_memory, "multi-memory");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user