bench-api: configure execution with a flags string (#4096)
As discussed previously, we need a way to be able to configure Wasmtime when running it in the Sightglass benchmark infrastructure. The easiest way to do this seemed to be to pass a string from Sightglass to the `bench-api` library and parse this in the same way that Wasmtime parses its CLI flags. The structure that contains these flags is `CommonOptions`, so it has been moved to its own crate to be depended on by both `wasmtime-cli` and `wasmtime-bench-api`. Also, this change adds an externally-visible function for parsing a string into `CommonOptions`, which is used for configuring an engine.
This commit is contained in:
@@ -17,7 +17,9 @@ crate-type = ["rlib", "cdylib"]
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
shuffling-allocator = { version = "1.1.1", optional = true }
|
||||
target-lexicon = "0.12"
|
||||
wasmtime = { path = "../wasmtime", default-features = true }
|
||||
wasmtime-cli-flags = { path = "../cli-flags", default-features = true }
|
||||
wasmtime-wasi = { path = "../wasi" }
|
||||
wasmtime-wasi-crypto = { path = "../wasi-crypto", optional = true }
|
||||
wasmtime-wasi-nn = { path = "../wasi-nn", optional = true }
|
||||
|
||||
@@ -90,6 +90,8 @@
|
||||
//! execution_timer: ptr::null_mut(),
|
||||
//! execution_start,
|
||||
//! execution_end,
|
||||
//! execution_flags_ptr: ptr::null(),
|
||||
//! execution_flags_len: 0,
|
||||
//! };
|
||||
//!
|
||||
//! let mut bench_api = ptr::null_mut();
|
||||
@@ -138,7 +140,9 @@ use anyhow::{anyhow, Context, Result};
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::slice;
|
||||
use std::{env, path::PathBuf};
|
||||
use target_lexicon::Triple;
|
||||
use wasmtime::{Config, Engine, Instance, Linker, Module, Store};
|
||||
use wasmtime_cli_flags::CommonOptions;
|
||||
use wasmtime_wasi::{sync::WasiCtxBuilder, WasiCtx};
|
||||
|
||||
pub type ExitCode = c_int;
|
||||
@@ -190,6 +194,11 @@ pub struct WasmBenchConfig {
|
||||
pub execution_timer: *mut u8,
|
||||
pub execution_start: extern "C" fn(*mut u8),
|
||||
pub execution_end: extern "C" fn(*mut u8),
|
||||
|
||||
/// The (optional) flags to use when running Wasmtime. These correspond to
|
||||
/// the flags used when running Wasmtime from the command line.
|
||||
pub execution_flags_ptr: *const u8,
|
||||
pub execution_flags_len: usize,
|
||||
}
|
||||
|
||||
impl WasmBenchConfig {
|
||||
@@ -228,6 +237,22 @@ impl WasmBenchConfig {
|
||||
std::str::from_utf8(stdin_path).context("given stdin path is not valid UTF-8")?;
|
||||
Ok(Some(stdin_path.into()))
|
||||
}
|
||||
|
||||
fn execution_flags(&self) -> Result<Option<Config>> {
|
||||
if self.execution_flags_ptr.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let execution_flags = unsafe {
|
||||
std::slice::from_raw_parts(self.execution_flags_ptr, self.execution_flags_len)
|
||||
};
|
||||
let execution_flags = std::str::from_utf8(execution_flags)
|
||||
.context("given execution flags string is not valid UTF-8")?;
|
||||
|
||||
let options = CommonOptions::parse_from_str(execution_flags)?;
|
||||
let config = options.config(Some(&Triple::host().to_string()))?;
|
||||
Ok(Some(config))
|
||||
}
|
||||
}
|
||||
|
||||
/// Exposes a C-compatible way of creating the engine from the bytes of a single
|
||||
@@ -256,8 +281,10 @@ pub extern "C" fn wasm_bench_create(
|
||||
let stdout_path = config.stdout_path()?;
|
||||
let stderr_path = config.stderr_path()?;
|
||||
let stdin_path = config.stdin_path()?;
|
||||
let engine_config = config.execution_flags()?;
|
||||
|
||||
let state = Box::new(BenchState::new(
|
||||
engine_config,
|
||||
config.compilation_timer,
|
||||
config.compilation_start,
|
||||
config.compilation_end,
|
||||
@@ -393,6 +420,7 @@ struct HostState {
|
||||
|
||||
impl BenchState {
|
||||
fn new(
|
||||
engine_config: Option<Config>,
|
||||
compilation_timer: *mut u8,
|
||||
compilation_start: extern "C" fn(*mut u8),
|
||||
compilation_end: extern "C" fn(*mut u8),
|
||||
@@ -405,9 +433,7 @@ impl BenchState {
|
||||
make_wasi_cx: impl FnMut() -> Result<WasiCtx> + 'static,
|
||||
) -> Result<Self> {
|
||||
// NB: do not configure a code cache.
|
||||
let mut config = Config::new();
|
||||
config.wasm_simd(true);
|
||||
let engine = Engine::new(&config)?;
|
||||
let engine = Engine::new(&engine_config.unwrap_or(Config::new()))?;
|
||||
let mut linker = Linker::<HostState>::new(&engine);
|
||||
|
||||
// Define the benchmarking start/end functions.
|
||||
|
||||
28
crates/cli-flags/Cargo.toml
Normal file
28
crates/cli-flags/Cargo.toml
Normal file
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "wasmtime-cli-flags"
|
||||
version = "0.37.0"
|
||||
authors = ["The Wasmtime Project Developers"]
|
||||
description = "Exposes common CLI flags used for running Wasmtime"
|
||||
license = "Apache-2.0 WITH LLVM-exception"
|
||||
repository = "https://github.com/bytecodealliance/wasmtime"
|
||||
documentation = "https://docs.rs/wasmtime-cache/"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.19"
|
||||
clap = { version = "3.1.12", features = ["color", "suggestions", "derive"] }
|
||||
file-per-thread-logger = "0.1.1"
|
||||
pretty_env_logger = "0.4.0"
|
||||
rayon = "1.5.0"
|
||||
wasmtime = { path = "../wasmtime", version = "0.37.0", default-features = false }
|
||||
|
||||
[features]
|
||||
default = [
|
||||
"wasmtime/cache",
|
||||
"wasmtime/cranelift",
|
||||
"wasmtime/jitdump",
|
||||
"wasmtime/vtune",
|
||||
]
|
||||
pooling-allocator = []
|
||||
memory-init-cow = []
|
||||
wasm-backtrace = []
|
||||
220
crates/cli-flags/LICENSE
Normal file
220
crates/cli-flags/LICENSE
Normal file
@@ -0,0 +1,220 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
--- LLVM Exceptions to the Apache 2.0 License ----
|
||||
|
||||
As an exception, if, as a result of your compiling your source code, portions
|
||||
of this Software are embedded into an Object form of such source code, you
|
||||
may redistribute such embedded portions in such Object form without complying
|
||||
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
|
||||
|
||||
In addition, if you combine or link compiled forms of this Software with
|
||||
software that is licensed under the GPLv2 ("Combined Software") and if a
|
||||
court of competent jurisdiction determines that the patent provision (Section
|
||||
3), the indemnity provision (Section 9) or other Section of the License
|
||||
conflicts with the conditions of the GPLv2, you may retroactively and
|
||||
prospectively choose to deem waived or otherwise exclude such Section(s) of
|
||||
the License, but only in their entirety and only with respect to the Combined
|
||||
Software.
|
||||
|
||||
723
crates/cli-flags/src/lib.rs
Normal file
723
crates/cli-flags/src/lib.rs
Normal file
@@ -0,0 +1,723 @@
|
||||
//! Contains the common Wasmtime command line interface (CLI) flags.
|
||||
|
||||
#![deny(trivial_numeric_casts, unused_extern_crates, unstable_features)]
|
||||
#![warn(unused_import_braces)]
|
||||
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
|
||||
#![cfg_attr(
|
||||
feature = "cargo-clippy",
|
||||
warn(
|
||||
clippy::float_arithmetic,
|
||||
clippy::mut_mut,
|
||||
clippy::nonminimal_bool,
|
||||
clippy::map_unwrap_or,
|
||||
clippy::unicode_not_nfc,
|
||||
clippy::use_self
|
||||
)
|
||||
)]
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use clap::Parser;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use wasmtime::{Config, ProfilingStrategy};
|
||||
#[cfg(feature = "pooling-allocator")]
|
||||
use wasmtime::{InstanceLimits, PoolingAllocationStrategy};
|
||||
|
||||
pub const SUPPORTED_WASM_FEATURES: &[(&str, &str)] = &[
|
||||
("all", "enables all supported WebAssembly features"),
|
||||
(
|
||||
"bulk-memory",
|
||||
"enables support for bulk memory instructions",
|
||||
),
|
||||
(
|
||||
"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"),
|
||||
("memory64", "enables support for 64-bit memories"),
|
||||
];
|
||||
|
||||
pub const SUPPORTED_WASI_MODULES: &[(&str, &str)] = &[
|
||||
(
|
||||
"default",
|
||||
"enables all stable WASI modules (no experimental modules)",
|
||||
),
|
||||
(
|
||||
"wasi-common",
|
||||
"enables support for the WASI common APIs, see https://github.com/WebAssembly/WASI",
|
||||
),
|
||||
(
|
||||
"experimental-wasi-nn",
|
||||
"enables support for the WASI neural network API (experimental), see https://github.com/WebAssembly/wasi-nn",
|
||||
),
|
||||
(
|
||||
"experimental-wasi-crypto",
|
||||
"enables support for the WASI cryptography APIs (experimental), see https://github.com/WebAssembly/wasi-crypto",
|
||||
),
|
||||
];
|
||||
|
||||
fn pick_profiling_strategy(jitdump: bool, vtune: bool) -> Result<ProfilingStrategy> {
|
||||
Ok(match (jitdump, vtune) {
|
||||
(true, false) => ProfilingStrategy::JitDump,
|
||||
(false, true) => ProfilingStrategy::VTune,
|
||||
(true, true) => {
|
||||
println!("Can't enable --jitdump and --vtune at the same time. Profiling not enabled.");
|
||||
ProfilingStrategy::None
|
||||
}
|
||||
_ => ProfilingStrategy::None,
|
||||
})
|
||||
}
|
||||
|
||||
fn init_file_per_thread_logger(prefix: &'static str) {
|
||||
file_per_thread_logger::initialize(prefix);
|
||||
|
||||
// Extending behavior of default spawner:
|
||||
// https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
|
||||
// Source code says DefaultSpawner is implementation detail and
|
||||
// shouldn't be used directly.
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.spawn_handler(move |thread| {
|
||||
let mut b = std::thread::Builder::new();
|
||||
if let Some(name) = thread.name() {
|
||||
b = b.name(name.to_owned());
|
||||
}
|
||||
if let Some(stack_size) = thread.stack_size() {
|
||||
b = b.stack_size(stack_size);
|
||||
}
|
||||
b.spawn(move || {
|
||||
file_per_thread_logger::initialize(prefix);
|
||||
thread.run()
|
||||
})?;
|
||||
Ok(())
|
||||
})
|
||||
.build_global()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Common options for commands that translate WebAssembly modules
|
||||
#[derive(Parser)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq))]
|
||||
pub struct CommonOptions {
|
||||
/// Use specified configuration file
|
||||
#[clap(long, parse(from_os_str), value_name = "CONFIG_PATH")]
|
||||
pub config: Option<PathBuf>,
|
||||
|
||||
/// Disable logging.
|
||||
#[clap(long, conflicts_with = "log-to-files")]
|
||||
pub disable_logging: bool,
|
||||
|
||||
/// Log to per-thread log files instead of stderr.
|
||||
#[clap(long)]
|
||||
pub log_to_files: bool,
|
||||
|
||||
/// Generate debug information
|
||||
#[clap(short = 'g')]
|
||||
pub debug_info: bool,
|
||||
|
||||
/// Disable cache system
|
||||
#[clap(long)]
|
||||
pub disable_cache: bool,
|
||||
|
||||
/// Enables or disables WebAssembly features
|
||||
#[clap(long, value_name = "FEATURE,FEATURE,...", parse(try_from_str = parse_wasm_features))]
|
||||
pub wasm_features: Option<WasmFeatures>,
|
||||
|
||||
/// Enables or disables WASI modules
|
||||
#[clap(long, value_name = "MODULE,MODULE,...", parse(try_from_str = parse_wasi_modules))]
|
||||
pub wasi_modules: Option<WasiModules>,
|
||||
|
||||
/// Generate jitdump file (supported on --features=profiling build)
|
||||
#[clap(long, conflicts_with = "vtune")]
|
||||
pub jitdump: bool,
|
||||
|
||||
/// Generate vtune (supported on --features=vtune build)
|
||||
#[clap(long, conflicts_with = "jitdump")]
|
||||
pub vtune: bool,
|
||||
|
||||
/// Run optimization passes on translated functions, on by default
|
||||
#[clap(short = 'O', long)]
|
||||
pub optimize: bool,
|
||||
|
||||
/// Optimization level for generated functions
|
||||
/// Supported levels: 0 (none), 1, 2 (most), or s (size); default is "most"
|
||||
#[clap(
|
||||
long,
|
||||
value_name = "LEVEL",
|
||||
parse(try_from_str = parse_opt_level),
|
||||
verbatim_doc_comment,
|
||||
)]
|
||||
pub opt_level: Option<wasmtime::OptLevel>,
|
||||
|
||||
/// Set a Cranelift setting to a given value.
|
||||
/// Use `wasmtime settings` to list Cranelift settings for a target.
|
||||
#[clap(long = "cranelift-set", value_name = "NAME=VALUE", number_of_values = 1, verbatim_doc_comment, parse(try_from_str = parse_cranelift_flag))]
|
||||
pub cranelift_set: Vec<(String, String)>,
|
||||
|
||||
/// Enable a Cranelift boolean setting or preset.
|
||||
/// Use `wasmtime settings` to list Cranelift settings for a target.
|
||||
#[clap(
|
||||
long,
|
||||
value_name = "SETTING",
|
||||
number_of_values = 1,
|
||||
verbatim_doc_comment
|
||||
)]
|
||||
pub cranelift_enable: Vec<String>,
|
||||
|
||||
/// Maximum size in bytes of wasm memory before it becomes dynamically
|
||||
/// relocatable instead of up-front-reserved.
|
||||
#[clap(long, value_name = "MAXIMUM")]
|
||||
pub static_memory_maximum_size: Option<u64>,
|
||||
|
||||
/// Force using a "static" style for all wasm memories.
|
||||
#[clap(long)]
|
||||
pub static_memory_forced: bool,
|
||||
|
||||
/// Byte size of the guard region after static memories are allocated.
|
||||
#[clap(long, value_name = "SIZE")]
|
||||
pub static_memory_guard_size: Option<u64>,
|
||||
|
||||
/// Byte size of the guard region after dynamic memories are allocated.
|
||||
#[clap(long, value_name = "SIZE")]
|
||||
pub dynamic_memory_guard_size: Option<u64>,
|
||||
|
||||
/// Enable Cranelift's internal debug verifier (expensive)
|
||||
#[clap(long)]
|
||||
pub enable_cranelift_debug_verifier: bool,
|
||||
|
||||
/// Enable Cranelift's internal NaN canonicalization
|
||||
#[clap(long)]
|
||||
pub enable_cranelift_nan_canonicalization: bool,
|
||||
|
||||
/// Enable execution fuel with N units fuel, where execution will trap after
|
||||
/// running out of fuel.
|
||||
///
|
||||
/// Most WebAssembly instructions consume 1 unit of fuel. Some instructions,
|
||||
/// such as `nop`, `drop`, `block`, and `loop`, consume 0 units, as any
|
||||
/// execution cost associated with them involves other instructions which do
|
||||
/// consume fuel.
|
||||
#[clap(long, value_name = "N")]
|
||||
pub fuel: Option<u64>,
|
||||
|
||||
/// Executing wasm code will yield when a global epoch counter
|
||||
/// changes, allowing for async operation without blocking the
|
||||
/// executor.
|
||||
#[clap(long)]
|
||||
pub epoch_interruption: bool,
|
||||
|
||||
/// Disables the on-by-default address map from native code to wasm code.
|
||||
#[clap(long)]
|
||||
pub disable_address_map: bool,
|
||||
|
||||
/// Disables the default of attempting to initialize linear memory via a
|
||||
/// copy-on-write mapping.
|
||||
#[cfg(feature = "memory-init-cow")]
|
||||
#[clap(long)]
|
||||
pub disable_memory_init_cow: bool,
|
||||
|
||||
/// Enables the pooling allocator, in place of the on-demand
|
||||
/// allocator.
|
||||
#[cfg(feature = "pooling-allocator")]
|
||||
#[clap(long)]
|
||||
pub pooling_allocator: bool,
|
||||
}
|
||||
|
||||
impl CommonOptions {
|
||||
pub fn parse_from_str(s: &str) -> Result<Self> {
|
||||
let parts = s.split(" ");
|
||||
let options =
|
||||
Self::try_parse_from(parts).context("unable to parse options from passed flags")?;
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
pub 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();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(&self, target: Option<&str>) -> Result<Config> {
|
||||
let mut config = Config::new();
|
||||
|
||||
// Set the target before setting any cranelift options, since the
|
||||
// target will reset any target-specific options.
|
||||
if let Some(target) = target {
|
||||
config.target(target)?;
|
||||
}
|
||||
|
||||
config
|
||||
.cranelift_debug_verifier(self.enable_cranelift_debug_verifier)
|
||||
.debug_info(self.debug_info)
|
||||
.cranelift_opt_level(self.opt_level())
|
||||
.profiler(pick_profiling_strategy(self.jitdump, self.vtune)?)?
|
||||
.cranelift_nan_canonicalization(self.enable_cranelift_nan_canonicalization);
|
||||
|
||||
self.enable_wasm_features(&mut config);
|
||||
|
||||
for name in &self.cranelift_enable {
|
||||
unsafe {
|
||||
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) => {
|
||||
config.cache_config_load(path)?;
|
||||
}
|
||||
None => {
|
||||
config.cache_config_load_default()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(max) = self.static_memory_maximum_size {
|
||||
config.static_memory_maximum_size(max);
|
||||
}
|
||||
|
||||
config.static_memory_forced(self.static_memory_forced);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// If fuel has been configured, set the `consume fuel` flag on the config.
|
||||
if self.fuel.is_some() {
|
||||
config.consume_fuel(true);
|
||||
}
|
||||
|
||||
config.epoch_interruption(self.epoch_interruption);
|
||||
config.generate_address_map(!self.disable_address_map);
|
||||
#[cfg(feature = "memory-init-cow")]
|
||||
config.memory_init_cow(!self.disable_memory_init_cow);
|
||||
|
||||
#[cfg(feature = "pooling-allocator")]
|
||||
{
|
||||
if self.pooling_allocator {
|
||||
let instance_limits = InstanceLimits::default();
|
||||
config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling {
|
||||
strategy: PoolingAllocationStrategy::NextAvailable,
|
||||
instance_limits,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn enable_wasm_features(&self, config: &mut Config) {
|
||||
let WasmFeatures {
|
||||
simd,
|
||||
bulk_memory,
|
||||
reference_types,
|
||||
multi_value,
|
||||
threads,
|
||||
multi_memory,
|
||||
memory64,
|
||||
} = self.wasm_features.unwrap_or_default();
|
||||
|
||||
if let Some(enable) = simd {
|
||||
config.wasm_simd(enable);
|
||||
}
|
||||
if let Some(enable) = bulk_memory {
|
||||
config.wasm_bulk_memory(enable);
|
||||
}
|
||||
if let Some(enable) = reference_types {
|
||||
#[cfg(feature = "wasm-backtrace")]
|
||||
config.wasm_reference_types(enable);
|
||||
drop(enable); // suppress unused warnings
|
||||
}
|
||||
if let Some(enable) = multi_value {
|
||||
config.wasm_multi_value(enable);
|
||||
}
|
||||
if let Some(enable) = threads {
|
||||
config.wasm_threads(enable);
|
||||
}
|
||||
if let Some(enable) = multi_memory {
|
||||
config.wasm_multi_memory(enable);
|
||||
}
|
||||
if let Some(enable) = memory64 {
|
||||
config.wasm_memory64(enable);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn opt_level(&self) -> wasmtime::OptLevel {
|
||||
match (self.optimize, self.opt_level.clone()) {
|
||||
(true, _) => wasmtime::OptLevel::Speed,
|
||||
(false, other) => other.unwrap_or(wasmtime::OptLevel::Speed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_opt_level(opt_level: &str) -> Result<wasmtime::OptLevel> {
|
||||
match opt_level {
|
||||
"s" => Ok(wasmtime::OptLevel::SpeedAndSize),
|
||||
"0" => Ok(wasmtime::OptLevel::None),
|
||||
"1" => Ok(wasmtime::OptLevel::Speed),
|
||||
"2" => Ok(wasmtime::OptLevel::Speed),
|
||||
other => bail!(
|
||||
"unknown optimization level `{}`, only 0,1,2,s accepted",
|
||||
other
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq))]
|
||||
pub struct WasmFeatures {
|
||||
pub reference_types: Option<bool>,
|
||||
pub multi_value: Option<bool>,
|
||||
pub bulk_memory: Option<bool>,
|
||||
pub simd: Option<bool>,
|
||||
pub threads: Option<bool>,
|
||||
pub multi_memory: Option<bool>,
|
||||
pub memory64: Option<bool>,
|
||||
}
|
||||
|
||||
fn parse_wasm_features(features: &str) -> Result<WasmFeatures> {
|
||||
let features = features.trim();
|
||||
|
||||
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(WasmFeatures {
|
||||
reference_types: all.or(values["reference-types"]),
|
||||
multi_value: all.or(values["multi-value"]),
|
||||
bulk_memory: all.or(values["bulk-memory"]),
|
||||
simd: all.or(values["simd"]),
|
||||
threads: all.or(values["threads"]),
|
||||
multi_memory: all.or(values["multi-memory"]),
|
||||
memory64: all.or(values["memory64"]),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_wasi_modules(modules: &str) -> Result<WasiModules> {
|
||||
let modules = modules.trim();
|
||||
match modules {
|
||||
"default" => Ok(WasiModules::default()),
|
||||
"-default" => Ok(WasiModules::none()),
|
||||
_ => {
|
||||
// Starting from the default set of WASI modules, enable or disable a list of
|
||||
// comma-separated modules.
|
||||
let mut wasi_modules = WasiModules::default();
|
||||
let mut set = |module: &str, enable: bool| match module {
|
||||
"" => Ok(()),
|
||||
"wasi-common" => Ok(wasi_modules.wasi_common = enable),
|
||||
"experimental-wasi-nn" => Ok(wasi_modules.wasi_nn = enable),
|
||||
"experimental-wasi-crypto" => Ok(wasi_modules.wasi_crypto = enable),
|
||||
"default" => bail!("'default' cannot be specified with other WASI modules"),
|
||||
_ => bail!("unsupported WASI module '{}'", module),
|
||||
};
|
||||
|
||||
for module in modules.split(',') {
|
||||
let module = module.trim();
|
||||
let (module, value) = if module.starts_with('-') {
|
||||
(&module[1..], false)
|
||||
} else {
|
||||
(module, true)
|
||||
};
|
||||
set(module, value)?;
|
||||
}
|
||||
|
||||
Ok(wasi_modules)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select which WASI modules are available at runtime for use by Wasm programs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct WasiModules {
|
||||
/// Enable the wasi-common implementation; eventually this should be split into its separate
|
||||
/// parts once the implementation allows for it (e.g. wasi-fs, wasi-clocks, etc.).
|
||||
pub wasi_common: bool,
|
||||
|
||||
/// Enable the experimental wasi-nn implementation.
|
||||
pub wasi_nn: bool,
|
||||
|
||||
/// Enable the experimental wasi-crypto implementation.
|
||||
pub wasi_crypto: bool,
|
||||
}
|
||||
|
||||
impl Default for WasiModules {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
wasi_common: true,
|
||||
wasi_nn: false,
|
||||
wasi_crypto: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WasiModules {
|
||||
/// Enable no modules.
|
||||
pub fn none() -> Self {
|
||||
Self {
|
||||
wasi_common: false,
|
||||
wasi_nn: false,
|
||||
wasi_crypto: 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()
|
||||
} else {
|
||||
bail!("missing name in cranelift flag");
|
||||
};
|
||||
let value = if let Some(value) = split.next() {
|
||||
value.to_string()
|
||||
} else {
|
||||
bail!("missing value in cranelift flag");
|
||||
};
|
||||
Ok((name, value))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_all_features() -> Result<()> {
|
||||
let options = CommonOptions::try_parse_from(vec!["foo", "--wasm-features=all"])?;
|
||||
|
||||
let WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
simd,
|
||||
threads,
|
||||
multi_memory,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert_eq!(reference_types, Some(true));
|
||||
assert_eq!(multi_value, Some(true));
|
||||
assert_eq!(bulk_memory, Some(true));
|
||||
assert_eq!(simd, Some(true));
|
||||
assert_eq!(threads, Some(true));
|
||||
assert_eq!(multi_memory, Some(true));
|
||||
assert_eq!(memory64, Some(true));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_features() -> Result<()> {
|
||||
let options = CommonOptions::try_parse_from(vec!["foo", "--wasm-features=-all"])?;
|
||||
|
||||
let WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
simd,
|
||||
threads,
|
||||
multi_memory,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert_eq!(reference_types, Some(false));
|
||||
assert_eq!(multi_value, Some(false));
|
||||
assert_eq!(bulk_memory, Some(false));
|
||||
assert_eq!(simd, Some(false));
|
||||
assert_eq!(threads, Some(false));
|
||||
assert_eq!(multi_memory, Some(false));
|
||||
assert_eq!(memory64, Some(false));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_features() -> Result<()> {
|
||||
let options = CommonOptions::try_parse_from(vec![
|
||||
"foo",
|
||||
"--wasm-features=-reference-types,simd,multi-memory,memory64",
|
||||
])?;
|
||||
|
||||
let WasmFeatures {
|
||||
reference_types,
|
||||
multi_value,
|
||||
bulk_memory,
|
||||
simd,
|
||||
threads,
|
||||
multi_memory,
|
||||
memory64,
|
||||
} = options.wasm_features.unwrap();
|
||||
|
||||
assert_eq!(reference_types, Some(false));
|
||||
assert_eq!(multi_value, None);
|
||||
assert_eq!(bulk_memory, None);
|
||||
assert_eq!(simd, Some(true));
|
||||
assert_eq!(threads, None);
|
||||
assert_eq!(multi_memory, Some(true));
|
||||
assert_eq!(memory64, Some(true));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! feature_test {
|
||||
($test_name:ident, $name:ident, $flag:literal) => {
|
||||
#[test]
|
||||
fn $test_name() -> Result<()> {
|
||||
let options =
|
||||
CommonOptions::try_parse_from(vec!["foo", concat!("--wasm-features=", $flag)])?;
|
||||
|
||||
let WasmFeatures { $name, .. } = options.wasm_features.unwrap();
|
||||
|
||||
assert_eq!($name, Some(true));
|
||||
|
||||
let options = CommonOptions::try_parse_from(vec![
|
||||
"foo",
|
||||
concat!("--wasm-features=-", $flag),
|
||||
])?;
|
||||
|
||||
let WasmFeatures { $name, .. } = options.wasm_features.unwrap();
|
||||
|
||||
assert_eq!($name, Some(false));
|
||||
|
||||
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_simd_feature, simd, "simd");
|
||||
feature_test!(test_threads_feature, threads, "threads");
|
||||
feature_test!(test_multi_memory_feature, multi_memory, "multi-memory");
|
||||
feature_test!(test_memory64_feature, memory64, "memory64");
|
||||
|
||||
#[test]
|
||||
fn test_default_modules() {
|
||||
let options = CommonOptions::try_parse_from(vec!["foo", "--wasi-modules=default"]).unwrap();
|
||||
assert_eq!(
|
||||
options.wasi_modules.unwrap(),
|
||||
WasiModules {
|
||||
wasi_common: true,
|
||||
wasi_nn: false,
|
||||
wasi_crypto: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_modules() {
|
||||
let options = CommonOptions::try_parse_from(vec!["foo", "--wasi-modules="]).unwrap();
|
||||
assert_eq!(
|
||||
options.wasi_modules.unwrap(),
|
||||
WasiModules {
|
||||
wasi_common: true,
|
||||
wasi_nn: false,
|
||||
wasi_crypto: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_some_modules() {
|
||||
let options = CommonOptions::try_parse_from(vec![
|
||||
"foo",
|
||||
"--wasi-modules=experimental-wasi-nn,-wasi-common",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
options.wasi_modules.unwrap(),
|
||||
WasiModules {
|
||||
wasi_common: false,
|
||||
wasi_nn: true,
|
||||
wasi_crypto: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_modules() {
|
||||
let options =
|
||||
CommonOptions::try_parse_from(vec!["foo", "--wasi-modules=-default"]).unwrap();
|
||||
assert_eq!(
|
||||
options.wasi_modules.unwrap(),
|
||||
WasiModules {
|
||||
wasi_common: false,
|
||||
wasi_nn: false,
|
||||
wasi_crypto: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_from_str() {
|
||||
fn use_func(flags: &str) -> CommonOptions {
|
||||
CommonOptions::parse_from_str(flags).unwrap()
|
||||
}
|
||||
fn use_clap_parser(flags: &[&str]) -> CommonOptions {
|
||||
CommonOptions::try_parse_from(flags).unwrap()
|
||||
}
|
||||
|
||||
assert_eq!(use_func(""), use_clap_parser(&[]));
|
||||
assert_eq!(
|
||||
use_func("foo --wasm-features=threads"),
|
||||
use_clap_parser(&["foo", "--wasm-features=threads"])
|
||||
);
|
||||
assert_eq!(
|
||||
use_func("foo --cranelift-set enable_simd=true"),
|
||||
use_clap_parser(&["foo", "--cranelift-set", "enable_simd=true"])
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user