From 1b678dbd56335ac46528d7768c618bda6507da98 Mon Sep 17 00:00:00 2001 From: Steve Fan <29133953+stevefan1999-personal@users.noreply.github.com> Date: Wed, 10 Jun 2026 15:36:10 +0800 Subject: [PATCH] allow cranelift and satellite crates to be able to build in no-std --- .gitignore | 1 + Cargo.lock | 19 +++- Cargo.toml | 27 +++--- cranelift/Cargo.toml | 2 +- cranelift/codegen/Cargo.toml | 8 +- cranelift/codegen/src/lib.rs | 2 +- cranelift/filetests/Cargo.toml | 2 +- cranelift/frontend/Cargo.toml | 1 - cranelift/frontend/src/lib.rs | 2 +- cranelift/fuzzgen/Cargo.toml | 2 +- cranelift/interpreter/Cargo.toml | 9 +- cranelift/interpreter/src/environment.rs | 5 ++ cranelift/interpreter/src/frame.rs | 7 +- cranelift/interpreter/src/interpreter.rs | 4 +- cranelift/interpreter/src/lib.rs | 9 ++ cranelift/interpreter/src/step.rs | 5 +- cranelift/interpreter/src/value.rs | 22 +---- cranelift/jit/Cargo.toml | 20 +++-- cranelift/jit/src/backend.rs | 90 +++++++++++++++---- cranelift/jit/src/compiled_blob.rs | 15 ++-- cranelift/jit/src/lib.rs | 13 ++- cranelift/jit/src/memory/arena.rs | 21 +++-- cranelift/jit/src/memory/mod.rs | 20 +++-- cranelift/jit/src/memory/system.rs | 28 +++--- cranelift/jit/src/memory/vec.rs | 79 ++++++++++++++++ cranelift/module/Cargo.toml | 7 +- cranelift/module/src/lib.rs | 2 +- cranelift/module/src/module.rs | 27 +++++- cranelift/native/Cargo.toml | 1 - cranelift/native/src/lib.rs | 21 ++++- cranelift/object/Cargo.toml | 16 ++-- cranelift/object/src/backend.rs | 14 ++- cranelift/object/src/lib.rs | 8 ++ cranelift/object/src/unwind.rs | 2 + cranelift/reader/Cargo.toml | 10 ++- cranelift/reader/src/error.rs | 4 +- cranelift/reader/src/isaspec.rs | 3 + cranelift/reader/src/lexer.rs | 2 +- cranelift/reader/src/lib.rs | 13 +++ cranelift/reader/src/parser.rs | 12 +-- cranelift/reader/src/run_command.rs | 13 ++- cranelift/reader/src/sourcemap.rs | 21 +++-- cranelift/reader/src/testcommand.rs | 5 +- cranelift/reader/src/testfile.rs | 2 + cranelift/umbrella/Cargo.toml | 9 +- crates/cranelift/Cargo.toml | 18 +++- crates/cranelift/src/alias_region_key.rs | 3 +- crates/cranelift/src/builder.rs | 14 ++- crates/cranelift/src/compiled_function.rs | 5 +- crates/cranelift/src/compiler.rs | 35 ++++++-- crates/cranelift/src/compiler/component.rs | 2 + crates/cranelift/src/debug.rs | 1 + .../src/debug/transform/address_transform.rs | 2 + crates/cranelift/src/debug/transform/attr.rs | 1 + .../transform/debug_transform_logging.rs | 2 + .../src/debug/transform/expression.rs | 2 + .../src/debug/transform/line_program.rs | 1 + .../src/debug/transform/range_info_builder.rs | 1 + .../cranelift/src/debug/transform/simulate.rs | 22 +++-- crates/cranelift/src/debug/transform/unit.rs | 2 + crates/cranelift/src/debug/transform/utils.rs | 1 + crates/cranelift/src/debug/write_debuginfo.rs | 1 + crates/cranelift/src/func_environ.rs | 19 ++-- .../cranelift/src/func_environ/gc/disabled.rs | 1 + .../cranelift/src/func_environ/gc/enabled.rs | 3 + .../stack_switching/instructions.rs | 6 +- crates/cranelift/src/isa_builder.rs | 1 + crates/cranelift/src/lib.rs | 14 ++- crates/cranelift/src/obj.rs | 5 +- .../src/translate/code_translator.rs | 4 +- .../src/translate/func_translator.rs | 1 + crates/cranelift/src/translate/stack.rs | 1 + .../src/translate/translation_utils.rs | 4 +- crates/cranelift/src/trap.rs | 2 + crates/wasmtime/Cargo.toml | 3 +- 75 files changed, 567 insertions(+), 215 deletions(-) create mode 100644 cranelift/jit/src/memory/vec.rs diff --git a/.gitignore b/.gitignore index d0136b3dcb42..06634f8a4b72 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,4 @@ testcase*.json perf.data* miri-wast/ report/ +target-*/ \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 67aa5f5a3c71..f1a71d63534f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -895,6 +895,7 @@ dependencies = [ "cranelift-entity", "cranelift-frontend", "cranelift-reader", + "hashbrown 0.17.0", "libm", "log", "smallvec 1.15.1", @@ -921,6 +922,7 @@ dependencies = [ "cranelift-frontend", "cranelift-module", "cranelift-native", + "hashbrown 0.17.0", "libc", "log", "memmap2", @@ -963,6 +965,7 @@ dependencies = [ "cranelift-frontend", "cranelift-module", "gimli 0.33.0", + "hashbrown 0.17.0", "log", "object 0.39.0", "target-lexicon", @@ -974,6 +977,8 @@ version = "0.133.0" dependencies = [ "anyhow", "cranelift-codegen", + "hashbrown 0.17.0", + "log", "smallvec 1.15.1", "target-lexicon", ] @@ -2466,9 +2471,9 @@ dependencies = [ [[package]] name = "memmap2" -version = "0.2.3" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" +checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" dependencies = [ "libc", ] @@ -3594,6 +3599,12 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +[[package]] +name = "spin" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1527984ca054dfca79333baec451042863f485fbee01b7bf6d911de915cac865" + [[package]] name = "stable_deref_trait" version = "1.2.0" @@ -4619,7 +4630,7 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1fda10642ea9ba8141d50976b2b3a02d30511baa4b938383b9fa823b35d4138" dependencies = [ - "spin", + "spin 0.9.8", "wasmi_collections", "wasmi_core", "wasmi_ir", @@ -5101,11 +5112,13 @@ dependencies = [ "cranelift-frontend", "cranelift-native", "gimli 0.33.0", + "hashbrown 0.17.0", "itertools 0.14.0", "log", "object 0.39.0", "pulley-interpreter", "smallvec 1.15.1", + "spin 0.12.0", "target-lexicon", "thiserror 2.0.17", "wasmparser 0.251.0", diff --git a/Cargo.toml b/Cargo.toml index 50b4f3575a48..4ea8ee51adb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -131,7 +131,7 @@ object = { workspace = true, features = ['std'] } wasmtime-test-macros = { path = "crates/test-macros" } pulley-interpreter = { workspace = true, features = ["disas"] } wasm-encoder = { workspace = true } -cranelift-native = { workspace = true } +cranelift-native = { workspace = true, features = ["std"] } futures = { workspace = true } rand = { workspace = true } @@ -289,7 +289,7 @@ wasmtime-core = { path = "crates/core", version = "=46.0.0", package = 'wasmtime wasmtime-wmemcheck = { path = "crates/wmemcheck", version = "=46.0.0", package = 'wasmtime-internal-wmemcheck' } wasmtime-c-api-macros = { path = "crates/c-api-macros", version = "=46.0.0", package = 'wasmtime-internal-c-api-macros' } wasmtime-cache = { path = "crates/cache", version = "=46.0.0", package = 'wasmtime-internal-cache' } -wasmtime-cranelift = { path = "crates/cranelift", version = "=46.0.0", package = 'wasmtime-internal-cranelift' } +wasmtime-cranelift = { path = "crates/cranelift", version = "=46.0.0", package = 'wasmtime-internal-cranelift', default-features = false } wasmtime-winch = { path = "crates/winch", version = "=46.0.0", package = 'wasmtime-internal-winch' } wasmtime-explorer = { path = "crates/explorer", version = "=46.0.0", package = 'wasmtime-internal-explorer' } wasmtime-fiber = { path = "crates/fiber", version = "=46.0.0", package = 'wasmtime-internal-fiber' } @@ -316,21 +316,21 @@ pulley-macros = { path = 'pulley/macros', version = "=46.0.0" } # Cranelift crates in this workspace cranelift-assembler-x64 = { path = "cranelift/assembler-x64", version = "0.133.0" } cranelift-codegen = { path = "cranelift/codegen", version = "0.133.0", default-features = false, features = ["unwind"] } -cranelift-frontend = { path = "cranelift/frontend", version = "0.133.0" } +cranelift-frontend = { path = "cranelift/frontend", version = "0.133.0", default-features = false } cranelift-entity = { path = "cranelift/entity", version = "0.133.0" } -cranelift-native = { path = "cranelift/native", version = "0.133.0" } -cranelift-module = { path = "cranelift/module", version = "0.133.0" } -cranelift-interpreter = { path = "cranelift/interpreter", version = "0.133.0" } -cranelift-reader = { path = "cranelift/reader", version = "0.133.0" } +cranelift-native = { path = "cranelift/native", version = "0.133.0", default-features = false } +cranelift-module = { path = "cranelift/module", version = "0.133.0", default-features = false } +cranelift-interpreter = { path = "cranelift/interpreter", version = "0.133.0", default-features = false } +cranelift-reader = { path = "cranelift/reader", version = "0.133.0", default-features = false } cranelift-filetests = { path = "cranelift/filetests" } -cranelift-object = { path = "cranelift/object", version = "0.133.0" } -cranelift-jit = { path = "cranelift/jit", version = "0.133.0" } +cranelift-object = { path = "cranelift/object", version = "0.133.0", default-features = false } +cranelift-jit = { path = "cranelift/jit", version = "0.133.0", default-features = false } cranelift-fuzzgen = { path = "cranelift/fuzzgen" } cranelift-bforest = { path = "cranelift/bforest", version = "0.133.0" } cranelift-bitset = { path = "cranelift/bitset", version = "0.133.0" } cranelift-control = { path = "cranelift/control", version = "0.133.0", default-features = false } cranelift-srcgen = { path = "cranelift/srcgen", version = "0.133.0" } -cranelift = { path = "cranelift/umbrella", version = "0.133.0" } +cranelift = { path = "cranelift/umbrella", version = "0.133.0", default-features = false } # Winch crates in this workspace. winch-codegen = { path = "winch/codegen", version = "=46.0.0" } @@ -346,7 +346,7 @@ component-async-tests = { path = "crates/misc/component-async-tests" } # Bytecode Alliance maintained dependencies: # --------------------------- -regalloc2 = "0.15.1" +regalloc2 = { version = "0.15.1", default-features = false } wasip1 = { version = "1.0.0", default-features = false } # cap-std family: @@ -404,7 +404,7 @@ capstone = { version = "0.14.0", default-features = false, features = ['full', ' smallvec = { version = "1.15.1", features = ["union"] } tracing = { version = "0.1.41", default-features = false } bitflags = "2.9.4" -thiserror = "2.0.17" +thiserror = { version = "2.0.17", default-features = false } async-trait = "0.1.89" heck = "0.5" similar = "2.7.0" @@ -467,6 +467,7 @@ pin-project-lite = "0.2.14" sha2 = { version = "0.10.2", default-features = false } gdbstub = "0.7.10" gdbstub_arch = "0.3.3" +spin = { version = "0.12.0", default-features = false, features = ["mutex", "spin_mutex"] } # ============================================================================= # @@ -684,7 +685,7 @@ harness = false name = "thread_eager_init" harness = false -[[bench]] +[[bench]] name = "trap" harness = false diff --git a/cranelift/Cargo.toml b/cranelift/Cargo.toml index 055c979837e2..29d260d6a569 100644 --- a/cranelift/Cargo.toml +++ b/cranelift/Cargo.toml @@ -28,7 +28,7 @@ cranelift-entity = { workspace = true } cranelift-interpreter = { workspace = true } cranelift-reader = { workspace = true } cranelift-frontend = { workspace = true } -cranelift-native = { workspace = true } +cranelift-native = { workspace = true, features = ["std"] } cranelift-filetests = { workspace = true } cranelift-module = { workspace = true } cranelift-object = { workspace = true } diff --git a/cranelift/codegen/Cargo.toml b/cranelift/codegen/Cargo.toml index cefcc0eb7f00..dd293a2e121f 100644 --- a/cranelift/codegen/Cargo.toml +++ b/cranelift/codegen/Cargo.toml @@ -66,13 +66,7 @@ default = ["std", "unwind", "host-arch", "timing"] # The "std" feature enables use of libstd. The "core" feature enables use # of some minimal std-like replacement libraries. At least one of these two # features need to be enabled. -std = ["serde?/std", "rustc-hash/std", "gimli/std", "cranelift-control/fuzz"] - -# The "core" feature used to enable a hashmap workaround, but is now -# deprecated (we (i) always use hashbrown, and (ii) don't support a -# no_std build anymore). The feature remains for backward -# compatibility as a no-op. -core = [] +std = ["serde?/std", "rustc-hash/std", "gimli/std", "cranelift-control/fuzz", "regalloc2/std"] # Enable the `to_capstone` method on TargetIsa, for constructing a Capstone # context, and the `disassemble` method on `MachBufferFinalized`. diff --git a/cranelift/codegen/src/lib.rs b/cranelift/codegen/src/lib.rs index cbf47a02fa9a..c45cbb934d2f 100644 --- a/cranelift/codegen/src/lib.rs +++ b/cranelift/codegen/src/lib.rs @@ -2,7 +2,7 @@ #![deny(missing_docs)] // Display feature requirements in the documentation when building on docs.rs #![cfg_attr(docsrs, feature(doc_cfg))] -#![no_std] +#![cfg_attr(not(test), no_std)] // Various bits and pieces of this crate might only be used for one platform or // another, but it's not really too useful to learn about that all the time. On // CI we build at least one version of this crate with `--features all-arch` diff --git a/cranelift/filetests/Cargo.toml b/cranelift/filetests/Cargo.toml index 92118fd4de1b..db621f7eedae 100644 --- a/cranelift/filetests/Cargo.toml +++ b/cranelift/filetests/Cargo.toml @@ -17,7 +17,7 @@ workspace = true cranelift-codegen = { workspace = true, features = ["disas", "timing"] } cranelift-frontend = { workspace = true } cranelift-interpreter = { workspace = true } -cranelift-native = { workspace = true } +cranelift-native = { workspace = true, features = ["std"] } cranelift-reader = { workspace = true } cranelift-jit = { workspace = true, features = ["wasmtime-unwinder"] } cranelift-module = { workspace = true } diff --git a/cranelift/frontend/Cargo.toml b/cranelift/frontend/Cargo.toml index f0a9f028e543..091107715296 100644 --- a/cranelift/frontend/Cargo.toml +++ b/cranelift/frontend/Cargo.toml @@ -29,4 +29,3 @@ cranelift-codegen = { workspace = true, features = ['x86'] } [features] default = ["std"] std = ["cranelift-codegen/std"] -core = ["cranelift-codegen/core"] diff --git a/cranelift/frontend/src/lib.rs b/cranelift/frontend/src/lib.rs index 6dfaa30ee741..42e2d681f2c2 100644 --- a/cranelift/frontend/src/lib.rs +++ b/cranelift/frontend/src/lib.rs @@ -152,7 +152,7 @@ //! ``` #![deny(missing_docs)] -#![no_std] +#![cfg_attr(not(test), no_std)] extern crate alloc; diff --git a/cranelift/fuzzgen/Cargo.toml b/cranelift/fuzzgen/Cargo.toml index fb323ad31d31..67bf01345e8e 100644 --- a/cranelift/fuzzgen/Cargo.toml +++ b/cranelift/fuzzgen/Cargo.toml @@ -15,7 +15,7 @@ workspace = true [dependencies] cranelift = { workspace = true } -cranelift-native = { workspace = true } +cranelift-native = { workspace = true, features = ["std"] } anyhow = { workspace = true, features = ['std'] } arbitrary = { workspace = true } diff --git a/cranelift/interpreter/Cargo.toml b/cranelift/interpreter/Cargo.toml index 19403254bdf8..4a23c7b59c34 100644 --- a/cranelift/interpreter/Cargo.toml +++ b/cranelift/interpreter/Cargo.toml @@ -17,13 +17,16 @@ workspace = true [dependencies] cranelift-codegen = { workspace = true } cranelift-entity = { workspace = true } +hashbrown = { workspace = true } +libm = { workspace = true } log = { workspace = true } smallvec = { workspace = true } thiserror = { workspace = true } -[target.x86_64-pc-windows-gnu.dependencies] -libm = { workspace = true } - [dev-dependencies] cranelift-frontend = { workspace = true } cranelift-reader = { workspace = true } + +[features] +default = ["std"] +std = ["cranelift-codegen/std", "thiserror/std"] diff --git a/cranelift/interpreter/src/environment.rs b/cranelift/interpreter/src/environment.rs index 79da5a39613e..80d2e19c541d 100644 --- a/cranelift/interpreter/src/environment.rs +++ b/cranelift/interpreter/src/environment.rs @@ -1,6 +1,11 @@ //! Implements the function environment (e.g. a name-to-function mapping) for interpretation. use cranelift_codegen::ir::{FuncRef, Function}; use cranelift_entity::{PrimaryMap, entity_impl}; +use std::string::{String, ToString}; + +#[cfg(not(feature = "std"))] +use hashbrown::HashMap; +#[cfg(feature = "std")] use std::collections::HashMap; /// A function store contains all of the functions that are accessible to an interpreter. diff --git a/cranelift/interpreter/src/frame.rs b/cranelift/interpreter/src/frame.rs index d24be376bc7f..750ed74ecfd1 100644 --- a/cranelift/interpreter/src/frame.rs +++ b/cranelift/interpreter/src/frame.rs @@ -1,4 +1,5 @@ //! Implements a call frame (activation record) for the Cranelift interpreter. +use std::vec::Vec; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{Function, Value as ValueRef, types}; @@ -69,7 +70,7 @@ impl<'a> Frame<'a> { pub fn set(&mut self, name: ValueRef, value: DataValue) -> Option { assert!(name.index() < self.registers.len()); trace!("Set {name} -> {value}"); - std::mem::replace(&mut self.registers[name.index()], Some(value)) + core::mem::replace(&mut self.registers[name.index()], Some(value)) } /// Assign to multiple SSA references; see `set`. @@ -88,10 +89,10 @@ impl<'a> Frame<'a> { trace!("Renaming {old_names:?} -> {new_names:?}"); assert_eq!(old_names.len(), new_names.len()); let new_registers = vec![None; self.registers.len()]; - let mut old_registers = std::mem::replace(&mut self.registers, new_registers); + let mut old_registers = core::mem::replace(&mut self.registers, new_registers); self.registers = vec![None; self.registers.len()]; for (&on, &nn) in old_names.iter().zip(new_names) { - let value = std::mem::replace(&mut old_registers[on.index()], None); + let value = core::mem::replace(&mut old_registers[on.index()], None); self.registers[nn.index()] = value; } } diff --git a/cranelift/interpreter/src/interpreter.rs b/cranelift/interpreter/src/interpreter.rs index 547e3e7dd899..745c0279fad6 100644 --- a/cranelift/interpreter/src/interpreter.rs +++ b/cranelift/interpreter/src/interpreter.rs @@ -9,6 +9,7 @@ use crate::instruction::DfgInstructionContext; use crate::state::{InterpreterFunctionRef, MemoryError, State}; use crate::step::{ControlFlow, CraneliftTrap, StepError, step}; use crate::value::{DataValueExt, ValueError}; +use core::iter; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::{ ArgumentPurpose, Block, Endianness, ExternalName, FuncRef, Function, GlobalValue, @@ -17,7 +18,8 @@ use cranelift_codegen::ir::{ use log::trace; use smallvec::SmallVec; use std::fmt::Debug; -use std::iter; +use std::string::{String, ToString}; +use std::vec::Vec; use thiserror::Error; /// The Cranelift interpreter; this contains some high-level functions to control the interpreter's diff --git a/cranelift/interpreter/src/lib.rs b/cranelift/interpreter/src/lib.rs index 9c9ab7833672..f2f0691c32c4 100644 --- a/cranelift/interpreter/src/lib.rs +++ b/cranelift/interpreter/src/lib.rs @@ -2,6 +2,15 @@ //! //! This module is a project for interpreting Cranelift IR. +#![cfg_attr(not(test), no_std)] + +#[cfg(not(feature = "std"))] +#[macro_use] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; + pub mod address; pub mod environment; pub mod frame; diff --git a/cranelift/interpreter/src/step.rs b/cranelift/interpreter/src/step.rs index 280922c3b4fe..271af3047a85 100644 --- a/cranelift/interpreter/src/step.rs +++ b/cranelift/interpreter/src/step.rs @@ -5,6 +5,7 @@ use crate::frame::Frame; use crate::instruction::InstructionContext; use crate::state::{InterpreterFunctionRef, MemoryError, State}; use crate::value::{DataValueExt, ValueConversionKind, ValueError, ValueResult}; +use core::ops::RangeFrom; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; use cranelift_codegen::ir::{ @@ -13,8 +14,10 @@ use cranelift_codegen::ir::{ }; use log::trace; use smallvec::{SmallVec, smallvec}; +use std::borrow::ToOwned; use std::fmt::Debug; -use std::ops::RangeFrom; +use std::string::String; +use std::vec::Vec; use thiserror::Error; /// Ensures that all types in args are the same as expected by the signature diff --git a/cranelift/interpreter/src/value.rs b/cranelift/interpreter/src/value.rs index a6987e24d98a..5b3c918d9203 100644 --- a/cranelift/interpreter/src/value.rs +++ b/cranelift/interpreter/src/value.rs @@ -105,7 +105,7 @@ pub enum ValueError { #[error("unable to convert value into type {0}")] InvalidValue(Type), #[error("unable to convert to primitive integer")] - InvalidInteger(#[from] std::num::TryFromIntError), + InvalidInteger(#[from] core::num::TryFromIntError), #[error("unable to cast data value")] InvalidDataValueCast(#[from] DataValueCastFailure), #[error("performed a division by zero")] @@ -628,31 +628,11 @@ impl DataValueExt for DataValue { fn fma(self, b: Self, c: Self) -> ValueResult { match (self, b, c) { (DataValue::F32(a), DataValue::F32(b), DataValue::F32(c)) => { - // The `fma` function for `x86_64-pc-windows-gnu` is incorrect. Use `libm`'s instead. - // See: https://github.com/bytecodealliance/wasmtime/issues/4512 - #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "gnu"))] let res = libm::fmaf(a.as_f32(), b.as_f32(), c.as_f32()); - - #[cfg(not(all( - target_arch = "x86_64", - target_os = "windows", - target_env = "gnu" - )))] - let res = a.as_f32().mul_add(b.as_f32(), c.as_f32()); - Ok(DataValue::F32(res.into())) } (DataValue::F64(a), DataValue::F64(b), DataValue::F64(c)) => { - #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "gnu"))] let res = libm::fma(a.as_f64(), b.as_f64(), c.as_f64()); - - #[cfg(not(all( - target_arch = "x86_64", - target_os = "windows", - target_env = "gnu" - )))] - let res = a.as_f64().mul_add(b.as_f64(), c.as_f64()); - Ok(DataValue::F64(res.into())) } (a, _b, _c) => Err(ValueError::InvalidType(ValueTypeClass::Float, a.ty())), diff --git a/cranelift/jit/Cargo.toml b/cranelift/jit/Cargo.toml index 0cc5afb70b64..487687790a23 100644 --- a/cranelift/jit/Cargo.toml +++ b/cranelift/jit/Cargo.toml @@ -14,19 +14,20 @@ rust-version.workspace = true workspace = true [dependencies] +anyhow = { workspace = true } +cranelift-codegen = { workspace = true } +cranelift-control = { workspace = true } +cranelift-entity = { workspace = true } cranelift-module = { workspace = true } cranelift-native = { workspace = true } -cranelift-codegen = { workspace = true, features = ["std"] } -cranelift-entity = { workspace = true } -cranelift-control = { workspace = true } -wasmtime-unwinder = { workspace = true, optional = true, features = ["cranelift"] } -anyhow = { workspace = true } -region = "3.0.2" +hashbrown = { workspace = true } libc = { workspace = true } -target-lexicon = { workspace = true } -memmap2 = "0.2.1" log = { workspace = true } +memmap2 = "0.9.10" +region = "3.0.2" +target-lexicon = { workspace = true } wasmtime-jit-icache-coherence = { workspace = true } +wasmtime-unwinder = { workspace = true, optional = true, features = ["cranelift"] } [target.'cfg(windows)'.dependencies.windows-sys] workspace = true @@ -37,7 +38,8 @@ features = [ ] [features] -default = [] +default = ["std"] +std = ["cranelift-codegen/std", "cranelift-module/std", "cranelift-native/std"] wasmtime-unwinder = ["dep:wasmtime-unwinder"] diff --git a/cranelift/jit/src/backend.rs b/cranelift/jit/src/backend.rs index cbed2c3217bf..ddbf687355eb 100644 --- a/cranelift/jit/src/backend.rs +++ b/cranelift/jit/src/backend.rs @@ -1,9 +1,12 @@ //! Defines `JITModule`. +#[cfg(not(feature = "std"))] +use crate::memory::VecMemoryProvider; use crate::{ compiled_blob::CompiledBlob, - memory::{BranchProtection, JITMemoryKind, JITMemoryProvider, SystemMemoryProvider}, + memory::{BranchProtection, JITMemoryKind, JITMemoryProvider}, }; +use core::cell::RefCell; use cranelift_codegen::binemit::Reloc; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; use cranelift_codegen::settings::Configurable; @@ -15,12 +18,21 @@ use cranelift_module::{ ModuleReloc, ModuleRelocTarget, ModuleResult, }; use log::info; -use std::cell::RefCell; -use std::collections::HashMap; -use std::ffi::CString; -use std::io::Write; +use std::borrow::ToOwned; +use std::boxed::Box; +use std::string::String; +use std::vec::Vec; use target_lexicon::PointerWidth; +#[cfg(not(feature = "std"))] +use hashbrown::{HashMap, hash_map::Entry}; +#[cfg(feature = "std")] +use std::collections::{HashMap, hash_map::Entry}; +#[cfg(feature = "std")] +use std::ffi::CString; +#[cfg(feature = "std")] +use std::io::Write as _; + const WRITABLE_DATA_ALIGNMENT: u64 = 0x8; const READONLY_DATA_ALIGNMENT: u64 = 0x1; @@ -88,7 +100,16 @@ impl JITBuilder { libcall_names: Box String + Send + Sync>, ) -> Self { let symbols = HashMap::new(); - let lookup_symbols = vec![Box::new(lookup_with_dlsym) as Box<_>]; + let lookup_symbols: Vec Option<*const u8> + Send>> = { + #[cfg(feature = "std")] + { + std::vec![Box::new(lookup_with_dlsym) as Box<_>] + } + #[cfg(not(feature = "std"))] + { + std::vec::Vec::new() + } + }; Self { isa, symbols, @@ -195,8 +216,8 @@ impl JITModule { fn lookup_symbol(&self, name: &str) -> Option<*const u8> { match self.symbols.borrow_mut().entry(name.to_owned()) { - std::collections::hash_map::Entry::Occupied(occ) => Some(occ.get().0), - std::collections::hash_map::Entry::Vacant(vac) => { + Entry::Occupied(occ) => Some(occ.get().0), + Entry::Vacant(vac) => { let ptr = self .lookup_symbols .iter() @@ -273,6 +294,22 @@ impl JITModule { .ptr() } + /// Returns the compiled bytes of a finalized function as a byte slice. + /// + /// The slice remains valid until either [`JITModule::free_memory`] is called or in the future + /// some way of deallocating this individual function is used. + pub fn get_finalized_function_bytes(&self, func_id: FuncId) -> &[u8] { + let info = &self.compiled_functions[func_id]; + assert!( + !self.functions_to_finalize.iter().any(|x| *x == func_id), + "function not yet finalized" + ); + let compiled = info + .as_ref() + .expect("function must be compiled before it can be finalized"); + unsafe { core::slice::from_raw_parts(compiled.ptr(), compiled.size()) } + } + /// Returns the address and size of a finalized data object. /// /// The pointer remains valid until either [`JITModule::free_memory`] is called or in the future @@ -290,6 +327,7 @@ impl JITModule { (compiled.ptr(), compiled.size()) } + #[cfg(feature = "std")] fn record_function_for_perf(&self, ptr: *const u8, size: usize, name: &str) { // The Linux perf tool supports JIT code via a /tmp/perf-$PID.map file, // which contains memory regions and their associated names. If we @@ -316,7 +354,7 @@ impl JITModule { /// /// Returns ModuleError in case of allocation or syscall failure pub fn finalize_definitions(&mut self) -> ModuleResult<()> { - for func in std::mem::take(&mut self.functions_to_finalize) { + for func in core::mem::take(&mut self.functions_to_finalize) { let decl = self.declarations.get_function_decl(func); assert!(decl.linkage.is_definable()); let func = self.compiled_functions[func] @@ -325,7 +363,7 @@ impl JITModule { func.perform_relocations(|name| self.get_address(name)); } - for data in std::mem::take(&mut self.data_objects_to_finalize) { + for data in core::mem::take(&mut self.data_objects_to_finalize) { let decl = self.declarations.get_data_decl(data); assert!(decl.linkage.is_definable()); let data = self.compiled_data_objects[data] @@ -355,9 +393,16 @@ impl JITModule { "cranelift-jit needs is_pic=false" ); - let memory = builder - .memory - .unwrap_or_else(|| Box::new(SystemMemoryProvider::new())); + let memory = builder.memory.unwrap_or_else(|| { + #[cfg(feature = "std")] + { + Box::new(crate::memory::SystemMemoryProvider::new()) + } + #[cfg(not(feature = "std"))] + { + Box::new(VecMemoryProvider::new()) + } + }); Self { isa: builder.isa, symbols: RefCell::new(builder.symbols), @@ -517,6 +562,7 @@ impl Module for JITModule { JITMemoryKind::Executable, )?); let (ptr, size) = (blob.ptr(), blob.size()); + #[cfg(feature = "std")] self.record_function_for_perf(ptr, size, &decl.linkage_name(id)); let range_start = ptr.addr(); @@ -563,8 +609,16 @@ impl Module for JITModule { None, JITMemoryKind::Executable, )?); - let (ptr, size) = (blob.ptr(), blob.size()); - self.record_function_for_perf(ptr, size, &decl.linkage_name(id)); + + #[cfg(feature = "std")] + { + let ptr = blob.ptr(); + let size = blob.size(); + self.record_function_for_perf(ptr, size, &decl.linkage_name(id)); + } + + #[cfg(not(feature = "std"))] + let _ = &blob; self.functions_to_finalize.push(id); @@ -656,7 +710,7 @@ impl Module for JITModule { } } -#[cfg(not(windows))] +#[cfg(all(feature = "std", not(windows)))] fn lookup_with_dlsym(name: &str) -> Option<*const u8> { let c_str = CString::new(name).unwrap(); let c_str_ptr = c_str.as_ptr(); @@ -668,7 +722,7 @@ fn lookup_with_dlsym(name: &str) -> Option<*const u8> { } } -#[cfg(windows)] +#[cfg(all(feature = "std", windows))] fn lookup_with_dlsym(name: &str) -> Option<*const u8> { use std::os::windows::io::RawHandle; use std::ptr; @@ -682,9 +736,7 @@ fn lookup_with_dlsym(name: &str) -> Option<*const u8> { unsafe { let handles = [ - // try to find the searched symbol in the currently running executable ptr::null_mut(), - // try to find the searched symbol in local c runtime LibraryLoader::GetModuleHandleA(UCRTBASE.as_ptr()) as RawHandle, ]; diff --git a/cranelift/jit/src/compiled_blob.rs b/cranelift/jit/src/compiled_blob.rs index 81e1bc707d84..fd7fe28fd912 100644 --- a/cranelift/jit/src/compiled_blob.rs +++ b/cranelift/jit/src/compiled_blob.rs @@ -1,7 +1,8 @@ -use std::ptr; +use core::ptr; +use std::vec::Vec; use cranelift_codegen::binemit::Reloc; -use cranelift_module::{ModuleError, ModuleReloc, ModuleRelocTarget, ModuleResult}; +use cranelift_module::{ModuleReloc, ModuleRelocTarget, ModuleResult}; use crate::JITMemoryProvider; use crate::memory::JITMemoryKind; @@ -46,9 +47,7 @@ impl CompiledBlob { } } - let ptr = memory - .allocate(data.len() + veneer_count * VENEER_SIZE, align, kind) - .map_err(|e| ModuleError::Allocation { err: e })?; + let ptr = memory.allocate(data.len() + veneer_count * VENEER_SIZE, align, kind)?; unsafe { ptr::copy_nonoverlapping(data.as_ptr(), ptr, data.len()); @@ -72,9 +71,7 @@ impl CompiledBlob { #[cfg(feature = "wasmtime-unwinder")] wasmtime_exception_data: Option>, kind: JITMemoryKind, ) -> ModuleResult { - let ptr = memory - .allocate(size, align, kind) - .map_err(|e| ModuleError::Allocation { err: e })?; + let ptr = memory.allocate(size, align, kind)?; unsafe { ptr::write_bytes(ptr, 0, size) }; @@ -105,7 +102,7 @@ impl CompiledBlob { &self, get_address: impl Fn(&ModuleRelocTarget) -> *const u8, ) { - use std::ptr::write_unaligned; + use core::ptr::write_unaligned; let mut next_veneer_idx = 0; diff --git a/cranelift/jit/src/lib.rs b/cranelift/jit/src/lib.rs index 177aa600853c..9acd51c3bec0 100644 --- a/cranelift/jit/src/lib.rs +++ b/cranelift/jit/src/lib.rs @@ -5,15 +5,22 @@ #![deny(missing_docs, unreachable_pub)] #![expect(unsafe_op_in_unsafe_fn, reason = "crate isn't migrated yet")] +#![cfg_attr(not(test), no_std)] + +#[cfg(not(feature = "std"))] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; mod backend; mod compiled_blob; mod memory; pub use crate::backend::{JITBuilder, JITModule}; -pub use crate::memory::{ - ArenaMemoryProvider, BranchProtection, JITMemoryProvider, SystemMemoryProvider, -}; +#[cfg(feature = "std")] +pub use crate::memory::{ArenaMemoryProvider, SystemMemoryProvider}; +pub use crate::memory::{BranchProtection, JITMemoryProvider, VecMemoryProvider}; /// Version number of this crate. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/cranelift/jit/src/memory/arena.rs b/cranelift/jit/src/memory/arena.rs index 00fdbbc88c68..7ec36a083945 100644 --- a/cranelift/jit/src/memory/arena.rs +++ b/cranelift/jit/src/memory/arena.rs @@ -1,8 +1,8 @@ -use std::io; -use std::mem::ManuallyDrop; -use std::ptr; +use core::mem::ManuallyDrop; +use core::ptr; +use std::vec::Vec; -use cranelift_module::ModuleResult; +use cranelift_module::{ModuleError, ModuleResult}; use super::{BranchProtection, JITMemoryKind, JITMemoryProvider}; @@ -128,7 +128,7 @@ impl ArenaMemoryProvider { size: usize, align: u64, protection: region::Protection, - ) -> io::Result<*mut u8> { + ) -> ModuleResult<*mut u8> { let align = usize::try_from(align).expect("alignment too big"); assert!( align <= region::page::size(), @@ -170,14 +170,13 @@ impl ArenaMemoryProvider { &mut self, size: usize, target_prot: region::Protection, - ) -> Result<(), io::Error> { + ) -> ModuleResult<()> { let size = align_up(size, region::page::size()); let ptr = unsafe { self.ptr.add(self.position) }; if self.position + size > self.size { - return Err(io::Error::new( - io::ErrorKind::Other, - "pre-allocated jit memory region exhausted", - )); + return Err(ModuleError::Backend(anyhow::anyhow!( + "pre-allocated jit memory region exhausted" + ))); } self.position += size; self.segments.push(Segment::new(ptr, size, target_prot)); @@ -221,7 +220,7 @@ impl Drop for ArenaMemoryProvider { } impl JITMemoryProvider for ArenaMemoryProvider { - fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> io::Result<*mut u8> { + fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> ModuleResult<*mut u8> { self.allocate_inner( size, align, diff --git a/cranelift/jit/src/memory/mod.rs b/cranelift/jit/src/memory/mod.rs index 7a9e8b77eb47..081aa3d64766 100644 --- a/cranelift/jit/src/memory/mod.rs +++ b/cranelift/jit/src/memory/mod.rs @@ -1,11 +1,16 @@ -use cranelift_module::{ModuleError, ModuleResult}; -use std::io; +use cranelift_module::ModuleResult; +#[cfg(feature = "std")] mod arena; +#[cfg(feature = "std")] mod system; +mod vec; +#[cfg(feature = "std")] pub use arena::ArenaMemoryProvider; +#[cfg(feature = "std")] pub use system::SystemMemoryProvider; +pub use vec::VecMemoryProvider; /// Type of branch protection to apply to executable memory. #[derive(Clone, Copy, Debug, PartialEq)] @@ -16,6 +21,7 @@ pub enum BranchProtection { BTI, } +/// The kind of memory allocation for JIT code and data. pub enum JITMemoryKind { /// Allocate memory that will be executable once finalized. Executable, @@ -27,11 +33,12 @@ pub enum JITMemoryKind { /// A provider of memory for the JIT. pub trait JITMemoryProvider { - /// Allocate memory - fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> io::Result<*mut u8>; + /// Allocate memory of the given size and alignment. + fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> ModuleResult<*mut u8>; /// Free the memory region. unsafe fn free_memory(&mut self); + /// Finalize the memory region and apply memory protections. fn finalize(&mut self, branch_protection: BranchProtection) -> ModuleResult<()>; } @@ -42,11 +49,14 @@ pub trait JITMemoryProvider { /// but *doesn't* flush the pipeline. Callers have to ensure that /// [`wasmtime_jit_icache_coherence::pipeline_flush_mt`] is called before the /// mappings are used. +#[cfg(feature = "std")] pub(crate) fn set_readable_and_executable( ptr: *mut u8, len: usize, branch_protection: BranchProtection, ) -> ModuleResult<()> { + use cranelift_module::ModuleError; + // Clear all the newly allocated code from cache if the processor requires it // // Do this before marking the memory as R+X, technically we should be able to do it after @@ -73,7 +83,7 @@ pub(crate) fn set_readable_and_executable( unsafe { if libc::mprotect(ptr as *mut libc::c_void, len, prot) < 0 { return Err(ModuleError::Backend( - anyhow::Error::new(io::Error::last_os_error()) + anyhow::Error::new(std::io::Error::last_os_error()) .context("unable to make memory readable+executable"), )); } diff --git a/cranelift/jit/src/memory/system.rs b/cranelift/jit/src/memory/system.rs index e6c5a4d2c3c1..7dd69652c264 100644 --- a/cranelift/jit/src/memory/system.rs +++ b/cranelift/jit/src/memory/system.rs @@ -1,6 +1,6 @@ -use std::io; use std::mem; use std::ptr; +use std::vec::Vec; use cranelift_module::{ModuleError, ModuleResult}; use memmap2::MmapMut; @@ -26,17 +26,19 @@ impl PtrLen { /// Create a new `PtrLen` pointing to at least `size` bytes of memory, /// suitably sized and aligned for memory protection. - fn with_size(size: usize) -> io::Result { + fn with_size(size: usize) -> ModuleResult { let alloc_size = region::page::ceil(size as *const ()) as usize; - MmapMut::map_anon(alloc_size).map(|mut mmap| { - // The order here is important; we assign the pointer first to get - // around compile time borrow errors. - Self { - ptr: mmap.as_mut_ptr(), - map: Some(mmap), - len: alloc_size, - } - }) + MmapMut::map_anon(alloc_size) + .map(|mut mmap| { + // The order here is important; we assign the pointer first to get + // around compile time borrow errors. + Self { + ptr: mmap.as_mut_ptr(), + map: Some(mmap), + len: alloc_size, + } + }) + .map_err(|err| ModuleError::Allocation { err }) } } @@ -69,7 +71,7 @@ impl Memory { self.position = 0; } - pub(crate) fn allocate(&mut self, size: usize, align: u64) -> io::Result<*mut u8> { + pub(crate) fn allocate(&mut self, size: usize, align: u64) -> ModuleResult<*mut u8> { let align = usize::try_from(align).expect("alignment too big"); if self.position % align != 0 { self.position += align - self.position % align; @@ -187,7 +189,7 @@ impl JITMemoryProvider for SystemMemoryProvider { self.code.set_readable_and_executable(branch_protection) } - fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> io::Result<*mut u8> { + fn allocate(&mut self, size: usize, align: u64, kind: JITMemoryKind) -> ModuleResult<*mut u8> { match kind { JITMemoryKind::Executable => self.code.allocate(size, align), JITMemoryKind::Writable => self.writable.allocate(size, align), diff --git a/cranelift/jit/src/memory/vec.rs b/cranelift/jit/src/memory/vec.rs new file mode 100644 index 000000000000..8fae87eca8c0 --- /dev/null +++ b/cranelift/jit/src/memory/vec.rs @@ -0,0 +1,79 @@ +use core::alloc::Layout; +use std::alloc::{alloc, dealloc}; +use std::vec::Vec; + +use cranelift_module::{ModuleError, ModuleResult}; + +use super::{BranchProtection, JITMemoryKind, JITMemoryProvider}; + +/// A memory provider that stores allocations in heap-allocated `Vec`s +/// without applying any memory protections. +/// +/// This is useful for dumping compiled code (e.g. for shellcode generation) +/// where the code will not be executed in-process. Memory is leaked by +/// default to keep returned pointers valid; call +/// [`JITMemoryProvider::free_memory`] to explicitly deallocate. +pub struct VecMemoryProvider { + allocations: Vec, +} + +struct Allocation { + ptr: *mut u8, + layout: Layout, +} + +unsafe impl Send for VecMemoryProvider {} + +impl VecMemoryProvider { + /// Create a new `VecMemoryProvider`. + pub fn new() -> Self { + Self { + allocations: Vec::new(), + } + } +} + +#[derive(Debug)] +struct AllocFailed; + +impl core::fmt::Display for AllocFailed { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.write_str("memory allocation failed") + } +} + +impl core::error::Error for AllocFailed {} + +impl JITMemoryProvider for VecMemoryProvider { + fn allocate(&mut self, size: usize, align: u64, _kind: JITMemoryKind) -> ModuleResult<*mut u8> { + let align = usize::try_from(align).expect("alignment too big").max(1); + let size = size.max(1); + let layout = Layout::from_size_align(size, align).map_err(ModuleError::allocation)?; + + let ptr = unsafe { alloc(layout) }; + if ptr.is_null() { + return Err(ModuleError::allocation(AllocFailed)); + } + + self.allocations.push(Allocation { ptr, layout }); + Ok(ptr) + } + + unsafe fn free_memory(&mut self) { + for alloc in self.allocations.drain(..) { + unsafe { dealloc(alloc.ptr, alloc.layout) }; + } + } + + fn finalize(&mut self, _branch_protection: BranchProtection) -> ModuleResult<()> { + Ok(()) + } +} + +impl Drop for VecMemoryProvider { + fn drop(&mut self) { + // Intentionally leak memory to keep function pointers valid, + // matching the behavior of SystemMemoryProvider and ArenaMemoryProvider. + // Call `free_memory()` to explicitly deallocate. + } +} diff --git a/cranelift/module/Cargo.toml b/cranelift/module/Cargo.toml index 398513b4c6d7..df64e98e4bc3 100644 --- a/cranelift/module/Cargo.toml +++ b/cranelift/module/Cargo.toml @@ -17,15 +17,14 @@ workspace = true [dependencies] cranelift-codegen = { workspace = true } cranelift-control = { workspace = true } -hashbrown = { workspace = true, optional = true } -anyhow = { workspace = true, features = ['std'] } +hashbrown = { workspace = true } +anyhow = { workspace = true } serde = { workspace = true, optional = true } serde_derive = { workspace = true, optional = true } [features] default = ["std"] -std = ["cranelift-codegen/std"] -core = ["hashbrown", "cranelift-codegen/core"] +std = ["cranelift-codegen/std", "anyhow/std"] # For dependent crates that want to serialize some parts of cranelift enable-serde = ["serde", "serde_derive", "cranelift-codegen/enable-serde"] diff --git a/cranelift/module/src/lib.rs b/cranelift/module/src/lib.rs index bb1e3994bb78..91121aa315e5 100644 --- a/cranelift/module/src/lib.rs +++ b/cranelift/module/src/lib.rs @@ -1,7 +1,7 @@ //! Top-level lib.rs for `cranelift_module`. #![deny(missing_docs)] -#![no_std] +#![cfg_attr(not(test), no_std)] #[cfg(not(feature = "std"))] #[macro_use] diff --git a/cranelift/module/src/module.rs b/cranelift/module/src/module.rs index 526f998561a8..e3c168d4f5a9 100644 --- a/cranelift/module/src/module.rs +++ b/cranelift/module/src/module.rs @@ -292,7 +292,11 @@ pub enum ModuleError { /// Memory allocation failure from a backend Allocation { /// Io error the allocation failed with + #[cfg(feature = "std")] err: std::io::Error, + /// Error the allocation failed with + #[cfg(not(feature = "std"))] + err: Box, }, /// Wraps a generic error from a backend @@ -308,10 +312,22 @@ impl<'a> From> for ModuleError { } } +impl ModuleError { + /// Constructs a [`ModuleError::Allocation`] from an arbitrary allocation + /// failure, internalizing the std/no_std representation of the payload. + pub fn allocation(err: impl core::error::Error + Send + Sync + 'static) -> Self { + #[cfg(feature = "std")] + let err = std::io::Error::other(err); + #[cfg(not(feature = "std"))] + let err: Box = Box::new(err); + Self::Allocation { err } + } +} + // This is manually implementing Error and Display instead of using thiserror to reduce the amount // of dependencies used by Cranelift. -impl std::error::Error for ModuleError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { +impl core::error::Error for ModuleError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { match self { Self::Undeclared { .. } | Self::IncompatibleDeclaration { .. } @@ -319,7 +335,10 @@ impl std::error::Error for ModuleError { | Self::DuplicateDefinition { .. } | Self::InvalidImportDefinition { .. } => None, Self::Compilation(source) => Some(source), + #[cfg(feature = "std")] Self::Allocation { err: source } => Some(source), + #[cfg(not(feature = "std"))] + Self::Allocation { err: source } => Some(&**source), Self::Backend(source) => Some(&**source), Self::Flag(source) => Some(source), } @@ -362,13 +381,13 @@ impl std::fmt::Display for ModuleError { } } -impl std::convert::From for ModuleError { +impl core::convert::From for ModuleError { fn from(source: CodegenError) -> Self { Self::Compilation { 0: source } } } -impl std::convert::From for ModuleError { +impl core::convert::From for ModuleError { fn from(source: SetError) -> Self { Self::Flag { 0: source } } diff --git a/cranelift/native/Cargo.toml b/cranelift/native/Cargo.toml index 7b2c03642b12..ec586bd03778 100644 --- a/cranelift/native/Cargo.toml +++ b/cranelift/native/Cargo.toml @@ -21,4 +21,3 @@ libc = { workspace = true } [features] default = ["std"] std = ["cranelift-codegen/std"] -core = ["cranelift-codegen/core"] diff --git a/cranelift/native/src/lib.rs b/cranelift/native/src/lib.rs index 495913c2e17b..e141cb6af4f0 100644 --- a/cranelift/native/src/lib.rs +++ b/cranelift/native/src/lib.rs @@ -2,6 +2,13 @@ //! Cranelift to generate code to run on the same machine. #![deny(missing_docs)] +#![no_std] + +#[cfg(not(feature = "std"))] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; use cranelift_codegen::isa; use cranelift_codegen::settings::Configurable; @@ -43,7 +50,7 @@ pub fn builder_with_options(infer_native_flags: bool) -> Result Result<(), &'static str> { - #[cfg(target_arch = "x86_64")] + #[cfg(all(target_arch = "x86_64", feature = "std"))] { if !std::is_x86_feature_detected!("sse2") { return Err("x86 support requires SSE2"); @@ -102,7 +109,7 @@ pub fn infer_native_flags(isa_builder: &mut dyn Configurable) -> Result<(), &'st } } - #[cfg(target_arch = "aarch64")] + #[cfg(all(target_arch = "aarch64", feature = "std"))] { if std::arch::is_aarch64_feature_detected!("lse") { isa_builder.enable("has_lse").unwrap(); @@ -124,6 +131,16 @@ pub fn infer_native_flags(isa_builder: &mut dyn Configurable) -> Result<(), &'st } } + // When the `std` feature is disabled on aarch64, still enable the + // compile-time known Apple Silicon flags. + #[cfg(all(target_arch = "aarch64", not(feature = "std")))] + { + if cfg!(target_os = "macos") { + isa_builder.enable("sign_return_address").unwrap(); + isa_builder.enable("sign_return_address_with_bkey").unwrap(); + } + } + // `is_s390x_feature_detected` is nightly only for now, so use the // STORE FACILITY LIST EXTENDED instruction as a temporary measure. #[cfg(target_arch = "s390x")] diff --git a/cranelift/object/Cargo.toml b/cranelift/object/Cargo.toml index f635bb309aee..5b77679ef572 100644 --- a/cranelift/object/Cargo.toml +++ b/cranelift/object/Cargo.toml @@ -14,17 +14,19 @@ rust-version.workspace = true workspace = true [dependencies] -cranelift-module = { workspace = true } -cranelift-codegen = { workspace = true, features = ["std"] } -cranelift-control = { workspace = true } -object = { workspace = true, features = ["write", "std"] } -target-lexicon = { workspace = true } anyhow = { workspace = true } -log = { workspace = true } +cranelift-codegen = { workspace = true } +cranelift-control = { workspace = true } +cranelift-module = { workspace = true } gimli = { workspace = true, features = ["write"], optional = true } +hashbrown = { workspace = true } +log = { workspace = true } +object = { workspace = true, features = ["write"] } +target-lexicon = { workspace = true } [features] -default = ["unwind"] +default = ["std", "unwind"] +std = ["cranelift-codegen/std", "cranelift-module/std", "object/std", "target-lexicon/std", "anyhow/std"] # Enables `.eh_frame` section emission via `ObjectBuilder::unwind_info`. unwind = ["dep:gimli", "cranelift-codegen/unwind"] diff --git a/cranelift/object/src/backend.rs b/cranelift/object/src/backend.rs index 4d6789a7ad91..40243853dfab 100644 --- a/cranelift/object/src/backend.rs +++ b/cranelift/object/src/backend.rs @@ -1,6 +1,7 @@ //! Defines `ObjectModule`. use anyhow::anyhow; +use core::mem; use cranelift_codegen::binemit::{Addend, CodeOffset, Reloc}; use cranelift_codegen::entity::SecondaryMap; use cranelift_codegen::ir; @@ -18,11 +19,16 @@ use object::{ RelocationEncoding, RelocationFlags, RelocationKind, SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope, elf, }; -use std::collections::HashMap; -use std::collections::hash_map::Entry; -use std::mem; +use std::boxed::Box; +use std::string::String; +use std::vec::Vec; use target_lexicon::{PointerWidth, Triple}; +#[cfg(not(feature = "std"))] +use hashbrown::{HashMap, hash_map::Entry}; +#[cfg(feature = "std")] +use std::collections::{HashMap, hash_map::Entry}; + /// A builder for `ObjectModule`. pub struct ObjectBuilder { isa: OwnedTargetIsa, @@ -611,7 +617,7 @@ impl Module for ObjectModule { } } - let align = std::cmp::max(align.unwrap_or(1), self.isa.symbol_alignment()); + let align = core::cmp::max(align.unwrap_or(1), self.isa.symbol_alignment()); let offset = match *init { Init::Uninitialized => { panic!("data is not initialized yet"); diff --git a/cranelift/object/src/lib.rs b/cranelift/object/src/lib.rs index 736fa46a3b0a..766b681ae9a8 100644 --- a/cranelift/object/src/lib.rs +++ b/cranelift/object/src/lib.rs @@ -3,6 +3,14 @@ //! This re-exports `object` so you don't have to explicitly keep the versions in sync. #![deny(missing_docs)] +#![cfg_attr(not(test), no_std)] + +#[cfg(not(feature = "std"))] +#[macro_use] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; mod backend; #[cfg(feature = "unwind")] diff --git a/cranelift/object/src/unwind.rs b/cranelift/object/src/unwind.rs index 3b7c176bdea4..e22f1afc2510 100644 --- a/cranelift/object/src/unwind.rs +++ b/cranelift/object/src/unwind.rs @@ -8,6 +8,8 @@ //! //! [`ObjectModule`]: crate::ObjectModule +use std::vec::Vec; + use anyhow::{Result, anyhow}; use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::isa::unwind::UnwindInfo; diff --git a/cranelift/reader/Cargo.toml b/cranelift/reader/Cargo.toml index c699f5fa0db3..8086eed5aa9e 100644 --- a/cranelift/reader/Cargo.toml +++ b/cranelift/reader/Cargo.toml @@ -14,11 +14,17 @@ rust-version.workspace = true workspace = true [dependencies] -anyhow = { workspace = true, features = ['std'] } +anyhow = { workspace = true } cranelift-codegen = { workspace = true } +hashbrown = { workspace = true } +log = { workspace = true } smallvec = { workspace = true } -target-lexicon = { workspace = true, features = ['std'] } +target-lexicon = { workspace = true } [dev-dependencies] # Some tests require that the x86_64 target parses for the target specification. cranelift-codegen = { workspace = true, features = ['x86'] } + +[features] +default = ["std"] +std = ["anyhow/std", "target-lexicon/std", "cranelift-codegen/std"] diff --git a/cranelift/reader/src/error.rs b/cranelift/reader/src/error.rs index c8bcb5145fe1..00d068e987a8 100644 --- a/cranelift/reader/src/error.rs +++ b/cranelift/reader/src/error.rs @@ -2,7 +2,7 @@ #![macro_use] -use std::fmt; +use std::{fmt, string::String}; /// The location of a `Token` or `Error`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -33,7 +33,7 @@ impl fmt::Display for ParseError { } } -impl std::error::Error for ParseError {} +impl core::error::Error for ParseError {} /// Result of a parser operation. The `ParseError` variant includes a location. pub type ParseResult = Result; diff --git a/cranelift/reader/src/isaspec.rs b/cranelift/reader/src/isaspec.rs index 4fe7d27ffb9d..4c91c17e7415 100644 --- a/cranelift/reader/src/isaspec.rs +++ b/cranelift/reader/src/isaspec.rs @@ -6,6 +6,9 @@ //! If a test case file contains `isa` commands, the tests will only be run against the specified //! ISAs. If the file contains no `isa` commands, the tests will be run against all supported ISAs. +use std::string::{String, ToString}; +use std::vec::Vec; + use crate::error::{Location, ParseError}; use crate::testcommand::TestOption; use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa}; diff --git a/cranelift/reader/src/lexer.rs b/cranelift/reader/src/lexer.rs index 2e00b86c2a80..c4e511116008 100644 --- a/cranelift/reader/src/lexer.rs +++ b/cranelift/reader/src/lexer.rs @@ -1,10 +1,10 @@ //! Lexical analysis for .clif files. use crate::error::Location; +use core::u16; use cranelift_codegen::ir::types; use cranelift_codegen::ir::{Block, Value}; use std::str::CharIndices; -use std::u16; /// A Token returned from the `Lexer`. /// diff --git a/cranelift/reader/src/lib.rs b/cranelift/reader/src/lib.rs index 5d7bca306a06..fe2b2d1785be 100644 --- a/cranelift/reader/src/lib.rs +++ b/cranelift/reader/src/lib.rs @@ -4,6 +4,14 @@ //! testing Cranelift, but is not essential for a JIT compiler. #![deny(missing_docs)] +#![cfg_attr(not(test), no_std)] + +#[cfg(not(feature = "std"))] +#[macro_use] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; pub use crate::error::{Location, ParseError, ParseResult}; pub use crate::isaspec::{IsaSpec, ParseOptionError, parse_option, parse_options}; @@ -26,6 +34,8 @@ use anyhow::{Error, Result}; use cranelift_codegen::isa::{self, OwnedTargetIsa}; use cranelift_codegen::settings::{self, FlagsOrIsa}; use std::str::FromStr; +use std::string::String; +use std::vec::Vec; use target_lexicon::Triple; /// Like `FlagsOrIsa`, but holds ownership. @@ -70,7 +80,10 @@ pub fn parse_sets_and_triple(flag_set: &[String], flag_triple: &str) -> Result triple, + #[cfg(feature = "std")] Err(parse_error) => return Err(Error::from(parse_error)), + #[cfg(not(feature = "std"))] + Err(parse_error) => return Err(Error::msg(parse_error)), }; let mut isa_builder = isa::lookup(triple).map_err(|err| match err { diff --git a/cranelift/reader/src/parser.rs b/cranelift/reader/src/parser.rs index 610a153b2a37..60709396dbfc 100644 --- a/cranelift/reader/src/parser.rs +++ b/cranelift/reader/src/parser.rs @@ -7,6 +7,8 @@ use crate::run_command::{Comparison, Invocation, RunCommand}; use crate::sourcemap::SourceMap; use crate::testcommand::TestCommand; use crate::testfile::{Comment, Details, Feature, TestFile}; +use core::mem; +use core::{u16, u32}; use cranelift_codegen::data_value::DataValue; use cranelift_codegen::entity::{EntityRef, PrimaryMap}; use cranelift_codegen::ir::entities::{AnyEntity, DynamicType}; @@ -15,21 +17,21 @@ use cranelift_codegen::ir::immediates::{ }; use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs}; use cranelift_codegen::ir::{self, StackSlotKey, UserExternalNameRef}; -use cranelift_codegen::ir::{DebugTag, types::*}; - use cranelift_codegen::ir::{ AbiParam, ArgumentExtension, ArgumentPurpose, Block, BlockArg, Constant, ConstantData, DynamicStackSlot, DynamicStackSlotData, DynamicTypeData, ExtFuncData, ExternalName, FuncRef, Function, GlobalValue, GlobalValueData, JumpTableData, MemFlagsData, MemFlagsSet, Opcode, SigRef, Signature, StackSlot, StackSlotData, StackSlotKind, UserFuncName, Value, types, }; +use cranelift_codegen::ir::{DebugTag, types::*}; use cranelift_codegen::isa::{self, CallConv}; use cranelift_codegen::packed_option::ReservedValue; use cranelift_codegen::{settings, settings::Configurable, timing}; use smallvec::SmallVec; -use std::mem; +use std::borrow::ToOwned; use std::str::FromStr; -use std::{u16, u32}; +use std::string::{String, ToString}; +use std::vec::Vec; use target_lexicon::Triple; macro_rules! match_imm { @@ -1255,7 +1257,7 @@ impl<'a> Parser<'a> { // Claim all the declared user-defined function names. for (user_func_ref, user_external_name) in - std::mem::take(&mut self.predeclared_external_names) + core::mem::take(&mut self.predeclared_external_names) { let actual_ref = ctx .function diff --git a/cranelift/reader/src/run_command.rs b/cranelift/reader/src/run_command.rs index f11d0b24845e..4c8a9631ab3e 100644 --- a/cranelift/reader/src/run_command.rs +++ b/cranelift/reader/src/run_command.rs @@ -7,7 +7,11 @@ //! - `; run: %fn(42, 4.2) == false`: this syntax specifies the parameters and return values. use cranelift_codegen::data_value::{self, DataValue, DisplayDataValues}; -use std::fmt::{self, Display, Formatter}; +use std::{ + fmt::{self, Display, Formatter}, + string::{String, ToString}, + vec::Vec, +}; /// A run command appearing in a test file. /// @@ -35,7 +39,12 @@ impl RunCommand { match self { RunCommand::Print(invoke) => { let actual = invoke_fn(&invoke.func, &invoke.args)?; - println!("{} -> {}", invoke, DisplayDataValues(&actual)) + + #[cfg(feature = "std")] + println!("{} -> {}", invoke, DisplayDataValues(&actual)); + + #[cfg(not(feature = "std"))] + log::info!("{} -> {}", invoke, DisplayDataValues(&actual)); } RunCommand::Run(invoke, compare, expected) => { let actual = invoke_fn(&invoke.func, &invoke.args)?; diff --git a/cranelift/reader/src/sourcemap.rs b/cranelift/reader/src/sourcemap.rs index 38c578c40135..c3497bed2091 100644 --- a/cranelift/reader/src/sourcemap.rs +++ b/cranelift/reader/src/sourcemap.rs @@ -12,6 +12,9 @@ use cranelift_codegen::ir::entities::{AnyEntity, DynamicType}; use cranelift_codegen::ir::{ Block, Constant, DynamicStackSlot, FuncRef, GlobalValue, JumpTable, SigRef, StackSlot, Value, }; +#[cfg(not(feature = "std"))] +use hashbrown::HashMap; +#[cfg(feature = "std")] use std::collections::HashMap; /// Mapping from entity names to source locations. @@ -25,47 +28,47 @@ pub struct SourceMap { impl SourceMap { /// Look up a value entity. pub fn contains_value(&self, v: Value) -> bool { - self.locations.contains_key(&v.into()) + self.locations.contains_key(&AnyEntity::from(v)) } /// Look up a block entity. pub fn contains_block(&self, block: Block) -> bool { - self.locations.contains_key(&block.into()) + self.locations.contains_key(&AnyEntity::from(block)) } /// Look up a stack slot entity. pub fn contains_ss(&self, ss: StackSlot) -> bool { - self.locations.contains_key(&ss.into()) + self.locations.contains_key(&AnyEntity::from(ss)) } /// Look up a dynamic stack slot entity. pub fn contains_dss(&self, dss: DynamicStackSlot) -> bool { - self.locations.contains_key(&dss.into()) + self.locations.contains_key(&AnyEntity::from(dss)) } /// Look up a global value entity. pub fn contains_gv(&self, gv: GlobalValue) -> bool { - self.locations.contains_key(&gv.into()) + self.locations.contains_key(&AnyEntity::from(gv)) } /// Look up a signature entity. pub fn contains_sig(&self, sig: SigRef) -> bool { - self.locations.contains_key(&sig.into()) + self.locations.contains_key(&AnyEntity::from(sig)) } /// Look up a function entity. pub fn contains_fn(&self, fn_: FuncRef) -> bool { - self.locations.contains_key(&fn_.into()) + self.locations.contains_key(&AnyEntity::from(fn_)) } /// Look up a jump table entity. pub fn contains_jt(&self, jt: JumpTable) -> bool { - self.locations.contains_key(&jt.into()) + self.locations.contains_key(&AnyEntity::from(jt)) } /// Look up a constant entity. pub fn contains_constant(&self, c: Constant) -> bool { - self.locations.contains_key(&c.into()) + self.locations.contains_key(&AnyEntity::from(c)) } /// Look up an entity by source name. diff --git a/cranelift/reader/src/testcommand.rs b/cranelift/reader/src/testcommand.rs index 1ed598b042d0..6d82f8b58c31 100644 --- a/cranelift/reader/src/testcommand.rs +++ b/cranelift/reader/src/testcommand.rs @@ -12,7 +12,10 @@ //! The parser does not understand the test commands or which options are valid. It simply parses //! the general format into a `TestCommand` data structure. -use std::fmt::{self, Display, Formatter}; +use std::{ + fmt::{self, Display, Formatter}, + vec::Vec, +}; /// A command appearing in a test file. #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/cranelift/reader/src/testfile.rs b/cranelift/reader/src/testfile.rs index 339030716461..071e511d32f0 100644 --- a/cranelift/reader/src/testfile.rs +++ b/cranelift/reader/src/testfile.rs @@ -4,6 +4,8 @@ //! file-based test case. //! +use std::vec::Vec; + use crate::error::Location; use crate::isaspec::IsaSpec; use crate::sourcemap::SourceMap; diff --git a/cranelift/umbrella/Cargo.toml b/cranelift/umbrella/Cargo.toml index 79ae56d0bc16..6e8c8d173cf3 100644 --- a/cranelift/umbrella/Cargo.toml +++ b/cranelift/umbrella/Cargo.toml @@ -32,10 +32,9 @@ object = ["dep:cranelift-object"] std = [ "cranelift-codegen/std", "cranelift-frontend?/std", + "cranelift-interpreter?/std", + "cranelift-jit?/std", "cranelift-module?/std", -] -core = [ - "cranelift-codegen/core", - "cranelift-frontend?/core", - "cranelift-module?/core", + "cranelift-native?/std", + "cranelift-object?/std", ] diff --git a/crates/cranelift/Cargo.toml b/crates/cranelift/Cargo.toml index 0aadcedf2326..6d47edbd6ba3 100644 --- a/crates/cranelift/Cargo.toml +++ b/crates/cranelift/Cargo.toml @@ -24,8 +24,8 @@ cranelift-native = { workspace = true } cranelift-control = { workspace = true } wasmparser = { workspace = true } target-lexicon = { workspace = true } -gimli = { workspace = true, features = ['std'] } -object = { workspace = true, features = ['write', 'std'] } +gimli = { workspace = true } +object = { workspace = true, features = ['write'] } smallvec = { workspace = true } thiserror = { workspace = true } cfg-if = { workspace = true } @@ -34,8 +34,22 @@ itertools = { workspace = true } pulley-interpreter = { workspace = true, optional = true } wasmtime-core = { workspace = true } wasmtime-unwinder = { workspace = true, features = ["cranelift"] } +spin = { workspace = true } +hashbrown = { workspace = true, features = ["default-hasher"] } [features] +default = ["std"] +std = [ + "wasmtime-environ/std", + "cranelift-codegen/std", + "cranelift-frontend/std", + "cranelift-native/std", + "gimli/std", + "object/std", + "thiserror/std", + "wasmtime-core/std", + "pulley-interpreter?/std", +] all-arch = ["cranelift-codegen/all-arch"] host-arch = ["cranelift-codegen/host-arch"] pulley = ["cranelift-codegen/pulley", "dep:pulley-interpreter"] diff --git a/crates/cranelift/src/alias_region_key.rs b/crates/cranelift/src/alias_region_key.rs index 00fd51ebc18e..846369045324 100644 --- a/crates/cranelift/src/alias_region_key.rs +++ b/crates/cranelift/src/alias_region_key.rs @@ -1,5 +1,6 @@ use core::fmt; use cranelift_codegen::ir; +use std::format; use wasmtime_environ::{ DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, StaticModuleIndex, }; @@ -11,7 +12,7 @@ use wasmtime_environ::{ /// /// The key encodes into a single `u32` with the following layout: /// `[ kind: 4 bits | data: 28 bits ]` -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) enum AliasRegionKey { /// A `VMContext` field access. VMContext { diff --git a/crates/cranelift/src/builder.rs b/crates/cranelift/src/builder.rs index ca3358caea63..8b41d7dbdf65 100644 --- a/crates/cranelift/src/builder.rs +++ b/crates/cranelift/src/builder.rs @@ -4,13 +4,16 @@ //! well as providing a function to return the default configuration to build. use crate::isa_builder::IsaBuilder; +use core::fmt; use cranelift_codegen::{ CodegenResult, isa::{self, OwnedTargetIsa}, }; -use std::fmt; +use std::boxed::Box; +#[cfg(feature = "std")] use std::path; use std::sync::Arc; +use std::vec::Vec; use target_lexicon::Triple; use wasmtime_environ::error::Result; use wasmtime_environ::{CacheStore, CompilerBuilder, Setting, Tunables}; @@ -21,6 +24,7 @@ struct Builder { emit_debug_checks: bool, linkopts: LinkOptions, cache_store: Option>, + #[cfg(feature = "std")] clif_dir: Option, wmemcheck: bool, } @@ -44,6 +48,7 @@ pub fn builder(triple: Option) -> Result> { inner: IsaBuilder::new(triple, |triple| isa::lookup(triple).map_err(|e| e.into()))?, linkopts: LinkOptions::default(), cache_store: None, + #[cfg(feature = "std")] clif_dir: None, wmemcheck: false, emit_debug_checks: false, @@ -68,6 +73,7 @@ impl CompilerBuilder for Builder { self.inner.triple() } + #[cfg(feature = "std")] fn clif_dir(&mut self, path: &path::Path) -> Result<()> { self.clif_dir = Some(path.to_path_buf()); Ok(()) @@ -127,6 +133,7 @@ impl CompilerBuilder for Builder { self.cache_store.clone(), self.emit_debug_checks, self.linkopts.clone(), + #[cfg(feature = "std")] self.clif_dir.clone(), self.wmemcheck, ))) @@ -152,7 +159,10 @@ impl CompilerBuilder for Builder { impl fmt::Debug for Builder { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Builder") - .field("shared_flags", &self.inner.shared_flags().to_string()) + .field( + "shared_flags", + &std::format!("{}", self.inner.shared_flags()), + ) .finish() } } diff --git a/crates/cranelift/src/compiled_function.rs b/crates/cranelift/src/compiled_function.rs index 8641bb7feced..b0d8f060db6c 100644 --- a/crates/cranelift/src/compiled_function.rs +++ b/crates/cranelift/src/compiled_function.rs @@ -1,4 +1,7 @@ -use std::ops::Range; +use core::ops::Range; +use std::boxed::Box; +use std::vec; +use std::vec::Vec; use crate::{Relocation, mach_reloc_to_reloc, mach_trap_to_trap}; use cranelift_codegen::{ diff --git a/crates/cranelift/src/compiler.rs b/crates/cranelift/src/compiler.rs index 5cb1f76eca64..b646a3799d3f 100644 --- a/crates/cranelift/src/compiler.rs +++ b/crates/cranelift/src/compiler.rs @@ -1,4 +1,5 @@ use crate::TRAP_INTERNAL_ASSERT; +#[cfg(feature = "std")] use crate::debug::DwarfSectionRelocTarget; use crate::func_environ::FuncEnvironment; use crate::translate::FuncTranslator; @@ -22,16 +23,22 @@ use cranelift_codegen::{ }; use cranelift_entity::PrimaryMap; use cranelift_frontend::FunctionBuilder; +use hashbrown::HashMap; use object::write::{Object, StandardSegment, SymbolId}; use object::{RelocationEncoding, RelocationFlags, RelocationKind, SectionKind}; +#[cfg(not(feature = "std"))] +use spin::Mutex; use std::any::Any; use std::borrow::Cow; use std::cmp; -use std::collections::HashMap; use std::mem; use std::ops::Range; +#[cfg(feature = "std")] use std::path; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +#[cfg(feature = "std")] +use std::sync::Mutex; +use std::vec::Vec; use wasmparser::{FuncValidatorAllocations, FunctionBody}; use wasmtime_environ::error::{Context as _, Result}; use wasmtime_environ::obj::{ELF_WASMTIME_EXCEPTIONS, ELF_WASMTIME_FRAMES}; @@ -86,6 +93,7 @@ pub struct Compiler { emit_debug_checks: bool, linkopts: LinkOptions, cache_store: Option>, + #[cfg(feature = "std")] clif_dir: Option, #[cfg(feature = "wmemcheck")] pub(crate) wmemcheck: bool, @@ -99,7 +107,7 @@ impl Drop for Compiler { let mut num_hits = 0; let mut num_cached = 0; - for ctx in self.contexts.lock().unwrap().iter() { + for ctx in self.lock_contexts().iter() { if let Some(ref cache_ctx) = ctx.incremental_cache_ctx { num_hits += cache_ctx.num_hits; num_cached += cache_ctx.num_cached; @@ -126,7 +134,7 @@ impl Compiler { cache_store: Option>, emit_debug_checks: bool, linkopts: LinkOptions, - clif_dir: Option, + #[cfg(feature = "std")] clif_dir: Option, wmemcheck: bool, ) -> Compiler { let _ = wmemcheck; @@ -137,12 +145,23 @@ impl Compiler { emit_debug_checks, linkopts, cache_store, + #[cfg(feature = "std")] clif_dir, #[cfg(feature = "wmemcheck")] wmemcheck, } } + #[cfg(feature = "std")] + fn lock_contexts(&self) -> std::sync::MutexGuard<'_, Vec> { + self.contexts.lock().unwrap() + } + + #[cfg(not(feature = "std"))] + fn lock_contexts(&self) -> spin::MutexGuard> { + self.contexts.lock() + } + /// Perform an indirect call from Cranelift-generated code to native code in /// Wasmtime itself. /// @@ -440,7 +459,7 @@ fn box_dyn_any_compiler_context(ctx: Option) -> Box Box { log::trace!( "making Box of {}", - std::any::type_name_of_val(&x) + core::any::type_name_of_val(&x) ); let b = Box::new(x); let r: &(dyn Any + Sync + Send) = &*b; @@ -861,6 +880,7 @@ impl wasmtime_environ::Compiler for Compiler { self } + #[cfg(feature = "std")] fn append_dwarf<'a>( &self, obj: &mut Object<'_>, @@ -1276,7 +1296,7 @@ impl Compiler { } fn function_compiler(&self) -> FunctionCompiler<'_> { - let saved_context = self.contexts.lock().unwrap().pop(); + let saved_context = self.lock_contexts().pop(); FunctionCompiler { compiler: self, cx: saved_context @@ -1593,6 +1613,7 @@ impl FunctionCompiler<'_> { let compilation_result = compile_maybe_cached(context, isa, self.cx.incremental_cache_ctx.as_mut()); + #[cfg(feature = "std")] if let Some(path) = &self.compiler.clif_dir { use std::io::Write; @@ -1672,7 +1693,7 @@ impl FunctionCompiler<'_> { } } - self.compiler.contexts.lock().unwrap().push(self.cx); + self.compiler.lock_contexts().push(self.cx); Ok(compiled_function) } diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rs index 588fafa6d282..eb3298584a51 100644 --- a/crates/cranelift/src/compiler/component.rs +++ b/crates/cranelift/src/compiler/component.rs @@ -9,6 +9,8 @@ use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::{self, InstBuilder, MemFlagsData, Value}; use cranelift_codegen::isa::{CallConv, TargetIsa}; use cranelift_frontend::FunctionBuilder; +use std::vec; +use std::vec::Vec; use wasmtime_environ::error::{Result, bail}; use wasmtime_environ::{ Abi, BuiltinFunctionIndex, CompiledFunctionBody, EntityRef, FuncKey, HostCall, PanicOnOom as _, diff --git a/crates/cranelift/src/debug.rs b/crates/cranelift/src/debug.rs index aadc36682893..2c37aad3822f 100644 --- a/crates/cranelift/src/debug.rs +++ b/crates/cranelift/src/debug.rs @@ -14,6 +14,7 @@ use core::fmt; use cranelift_codegen::isa::TargetIsa; use object::write::SymbolId; use std::collections::HashMap; +use std::vec::Vec; use wasmtime_environ::{ DefinedFuncIndex, DefinedMemoryIndex, EntityRef, MemoryIndex, ModuleTranslation, OwnedMemoryIndex, PrimaryMap, PtrSize, StaticModuleIndex, Tunables, VMOffsets, diff --git a/crates/cranelift/src/debug/transform/address_transform.rs b/crates/cranelift/src/debug/transform/address_transform.rs index 7de691c7f415..7324e04d225d 100644 --- a/crates/cranelift/src/debug/transform/address_transform.rs +++ b/crates/cranelift/src/debug/transform/address_transform.rs @@ -1,7 +1,9 @@ use crate::FunctionAddressMap; use crate::debug::Compilation; use gimli::write; +use std::boxed::Box; use std::collections::BTreeMap; +use std::vec::Vec; use wasmtime_environ::{DefinedFuncIndex, FilePos, PrimaryMap, StaticModuleIndex}; pub type GeneratedAddress = usize; diff --git a/crates/cranelift/src/debug/transform/attr.rs b/crates/cranelift/src/debug/transform/attr.rs index 6b2cceefb653..8e6b0c22071e 100644 --- a/crates/cranelift/src/debug/transform/attr.rs +++ b/crates/cranelift/src/debug/transform/attr.rs @@ -8,6 +8,7 @@ use super::range_info_builder::RangeInfoBuilder; use super::unit::InheritedAttr; use cranelift_codegen::isa::TargetIsa; use gimli::{AttributeValue, UnitOffset, write}; +use std::vec::Vec; use wasmtime_environ::error::Error; #[derive(Debug)] diff --git a/crates/cranelift/src/debug/transform/debug_transform_logging.rs b/crates/cranelift/src/debug/transform/debug_transform_logging.rs index 47033cdde8f9..db3a5d25d08b 100644 --- a/crates/cranelift/src/debug/transform/debug_transform_logging.rs +++ b/crates/cranelift/src/debug/transform/debug_transform_logging.rs @@ -2,6 +2,8 @@ use crate::{debug::Reader, translate::get_vmctx_value_label}; use core::fmt; use cranelift_codegen::{LabelValueLoc, ValueLabelsRanges, ir::ValueLabel, isa::TargetIsa}; use gimli::{AttributeValue, LittleEndian, UnitRef, write}; +use std::string::String; +use std::vec::Vec; macro_rules! dbi_log_enabled { () => { diff --git a/crates/cranelift/src/debug/transform/expression.rs b/crates/cranelift/src/debug/transform/expression.rs index 45ed49bc9d26..5cad6060c5f0 100644 --- a/crates/cranelift/src/debug/transform/expression.rs +++ b/crates/cranelift/src/debug/transform/expression.rs @@ -12,10 +12,12 @@ use cranelift_codegen::ir::ValueLabel; use cranelift_codegen::isa::TargetIsa; use gimli::{Expression, Operation, Reader, ReaderOffset, write}; use itertools::Itertools; +use std::boxed::Box; use std::cmp::PartialEq; use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::rc::Rc; +use std::vec::Vec; use wasmtime_environ::error::{Context, Error, Result}; #[derive(Debug)] diff --git a/crates/cranelift/src/debug/transform/line_program.rs b/crates/cranelift/src/debug/transform/line_program.rs index 10106123ac20..cfa9b9959596 100644 --- a/crates/cranelift/src/debug/transform/line_program.rs +++ b/crates/cranelift/src/debug/transform/line_program.rs @@ -1,6 +1,7 @@ use super::address_transform::AddressTransform; use crate::debug::Reader; use gimli::write; +use std::vec::Vec; use wasmtime_environ::error::Error; pub(crate) fn clone_line_program( diff --git a/crates/cranelift/src/debug/transform/range_info_builder.rs b/crates/cranelift/src/debug/transform/range_info_builder.rs index 2799123bf5cd..6a531e8f0973 100644 --- a/crates/cranelift/src/debug/transform/range_info_builder.rs +++ b/crates/cranelift/src/debug/transform/range_info_builder.rs @@ -1,6 +1,7 @@ use super::address_transform::AddressTransform; use crate::debug::Reader; use gimli::{AttributeValue, RangeListsOffset, UnitRef, write}; +use std::vec::Vec; use wasmtime_environ::DefinedFuncIndex; use wasmtime_environ::error::Error; diff --git a/crates/cranelift/src/debug/transform/simulate.rs b/crates/cranelift/src/debug/transform/simulate.rs index 24f6d6c7c8a0..b3e12f1cf24d 100644 --- a/crates/cranelift/src/debug/transform/simulate.rs +++ b/crates/cranelift/src/debug/transform/simulate.rs @@ -6,9 +6,13 @@ use crate::translate::get_vmctx_value_label; use cranelift_codegen::isa::TargetIsa; use gimli::LineEncoding; use gimli::write; +use std::borrow::ToOwned; use std::collections::{HashMap, HashSet}; -use std::path::PathBuf; +use std::path::Path; +use std::string::String; +use std::string::ToString; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::vec::Vec; use wasmtime_environ::error::{Context, Error}; use wasmtime_environ::{ DebugInfoData, EntityRef, FunctionMetadata, PrimaryMap, StaticModuleIndex, WasmFileInfo, @@ -106,7 +110,7 @@ fn check_invalid_chars_in_name(s: &str) -> Option<&str> { if s.contains('\x00') { None } else { Some(s) } } -fn autogenerate_dwarf_wasm_path(di: &DebugInfoData) -> PathBuf { +fn autogenerate_dwarf_wasm_path(di: &DebugInfoData) -> String { static NEXT_ID: AtomicUsize = AtomicUsize::new(0); let module_name = di .name_section @@ -114,8 +118,7 @@ fn autogenerate_dwarf_wasm_path(di: &DebugInfoData) -> PathBuf { .and_then(check_invalid_chars_in_name) .map(|s| s.to_string()) .unwrap_or_else(|| format!(".wasm", NEXT_ID.fetch_add(1, SeqCst))); - let path = format!("//{module_name}"); - PathBuf::from(path) + format!("//{module_name}") } struct WasmTypesDieRefs { @@ -278,10 +281,12 @@ fn generate_vars( Ok(()) } -fn check_invalid_chars_in_path(path: PathBuf) -> Option { - path.clone() - .to_str() - .and_then(move |s| if s.contains('\x00') { None } else { Some(path) }) +fn check_invalid_chars_in_path(path: String) -> Option { + if path.contains('\x00') { + None + } else { + Some(path) + } } /// Generate "simulated" native DWARF for functions lacking WASM-level DWARF. @@ -307,6 +312,7 @@ pub fn generate_simulated_dwarf( }; let (unit, root_id, file_id) = { + let path = Path::new(&path); let comp_dir_id = out_strings.add(assert_dwarf_str!( path.parent() .context("path dir")? diff --git a/crates/cranelift/src/debug/transform/unit.rs b/crates/cranelift/src/debug/transform/unit.rs index 726478ce7cb3..cb980d49e4f7 100644 --- a/crates/cranelift/src/debug/transform/unit.rs +++ b/crates/cranelift/src/debug/transform/unit.rs @@ -15,6 +15,8 @@ use cranelift_codegen::isa::TargetIsa; use gimli::AttributeValue; use gimli::write; use std::collections::HashSet; +use std::string::String; +use std::vec::Vec; use wasmtime_environ::StaticModuleIndex; use wasmtime_environ::error::{Context, Error}; use wasmtime_versioned_export_macros::versioned_stringify_ident; diff --git a/crates/cranelift/src/debug/transform/utils.rs b/crates/cranelift/src/debug/transform/utils.rs index 6741bef4ab54..79b2a5c970c0 100644 --- a/crates/cranelift/src/debug/transform/utils.rs +++ b/crates/cranelift/src/debug/transform/utils.rs @@ -4,6 +4,7 @@ use super::address_transform::AddressTransform; use super::expression::{CompiledExpression, FunctionFrameInfo}; use cranelift_codegen::isa::TargetIsa; use gimli::{AttributeValue, UnitRef, write}; +use std::vec::Vec; use wasmtime_environ::error::Error; pub(crate) fn append_vmctx_info( diff --git a/crates/cranelift/src/debug/write_debuginfo.rs b/crates/cranelift/src/debug/write_debuginfo.rs index 2123f5c159ef..a94a54751093 100644 --- a/crates/cranelift/src/debug/write_debuginfo.rs +++ b/crates/cranelift/src/debug/write_debuginfo.rs @@ -9,6 +9,7 @@ use gimli::write::{ Address, Dwarf, EndianVec, FrameTable, Result as WriteResult, Sections, Writer, }; use gimli::{RunTimeEndian, SectionId}; +use std::vec::Vec; use wasmtime_environ::error::Result as EnvResult; pub struct DwarfSection { diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs index c0f2759c77a7..bf63593349f3 100644 --- a/crates/cranelift/src/func_environ.rs +++ b/crates/cranelift/src/func_environ.rs @@ -12,6 +12,8 @@ use crate::{ BuiltinFunctionSignatures, TRAP_ARRAY_OUT_OF_BOUNDS, TRAP_GC_HEAP_CORRUPT, TRAP_TABLE_OUT_OF_BOUNDS, }; +use core::iter::Peekable; +use core::mem; use cranelift_codegen::cursor::FuncCursor; use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, V128Imm}; @@ -25,9 +27,11 @@ use cranelift_entity::packed_option::{PackedOption, ReservedValue}; use cranelift_entity::{EntityRef, PrimaryMap, SecondaryMap}; use cranelift_frontend::Variable; use cranelift_frontend::{FuncInstBuilder, FunctionBuilder}; +use hashbrown::HashMap; use smallvec::{SmallVec, smallvec}; -use std::iter::Peekable; -use std::mem; +use std::string::ToString; +use std::vec; +use std::vec::Vec; use wasmparser::{ BranchHint, FuncValidator, Operator, SectionLimitedIntoIter, WasmFeatures, WasmModuleResources, }; @@ -154,10 +158,7 @@ pub struct FuncEnvironment<'module_environment> { pub(crate) stacks: FuncTranslationStacks, #[cfg(feature = "gc")] - ty_to_gc_layout: std::collections::HashMap< - wasmtime_environ::ModuleInternedTypeIndex, - wasmtime_environ::GcLayout, - >, + ty_to_gc_layout: HashMap, #[cfg(feature = "gc")] gc_heap: Option, @@ -247,7 +248,7 @@ pub struct FuncEnvironment<'module_environment> { func_body_offset: usize, /// Cached alias regions for alias analysis. - alias_regions: std::collections::HashMap, + alias_regions: HashMap, } impl<'module_environment> FuncEnvironment<'module_environment> { @@ -286,7 +287,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> { stacks: FuncTranslationStacks::new(), #[cfg(feature = "gc")] - ty_to_gc_layout: std::collections::HashMap::new(), + ty_to_gc_layout: HashMap::new(), #[cfg(feature = "gc")] gc_heap: None, #[cfg(feature = "gc")] @@ -322,7 +323,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> { branch_hints, func_body_offset, - alias_regions: std::collections::HashMap::new(), + alias_regions: HashMap::new(), } } diff --git a/crates/cranelift/src/func_environ/gc/disabled.rs b/crates/cranelift/src/func_environ/gc/disabled.rs index e659ff6f748b..ed444624899d 100644 --- a/crates/cranelift/src/func_environ/gc/disabled.rs +++ b/crates/cranelift/src/func_environ/gc/disabled.rs @@ -5,6 +5,7 @@ use crate::func_environ::{CheckedEntity, Extension, FuncEnvironment}; use cranelift_codegen::ir; use cranelift_frontend::FunctionBuilder; use smallvec::SmallVec; +use std::boxed::Box; use wasmtime_environ::{ GcArrayLayout, ModuleInternedTypeIndex, TagIndex, TypeIndex, WasmRefType, WasmResult, WasmStorageType, wasm_unsupported, diff --git a/crates/cranelift/src/func_environ/gc/enabled.rs b/crates/cranelift/src/func_environ/gc/enabled.rs index 68a6cc33a0b0..823a17a42a86 100644 --- a/crates/cranelift/src/func_environ/gc/enabled.rs +++ b/crates/cranelift/src/func_environ/gc/enabled.rs @@ -15,6 +15,9 @@ use cranelift_codegen::{ use cranelift_entity::packed_option::ReservedValue; use cranelift_frontend::FunctionBuilder; use smallvec::{SmallVec, smallvec}; +use std::boxed::Box; +use std::string::ToString; +use std::vec; use wasmtime_environ::{ Collector, GcArrayLayout, GcLayout, GcStructLayout, I31_DISCRIMINANT, ModuleInternedTypeIndex, PtrSize, TagIndex, TypeIndex, VMGcKind, WasmCompositeInnerType, WasmHeapTopType, WasmHeapType, diff --git a/crates/cranelift/src/func_environ/stack_switching/instructions.rs b/crates/cranelift/src/func_environ/stack_switching/instructions.rs index 5da5c88623e8..c4800acbb705 100644 --- a/crates/cranelift/src/func_environ/stack_switching/instructions.rs +++ b/crates/cranelift/src/func_environ/stack_switching/instructions.rs @@ -1,5 +1,7 @@ use cranelift_codegen::ir::BlockArg; use itertools::{Either, Itertools}; +use std::vec; +use std::vec::Vec; use crate::trap::TranslateTrap; use cranelift_codegen::ir::condcodes::*; @@ -30,6 +32,8 @@ pub(crate) mod stack_switching_helpers { use cranelift_codegen::ir::types::*; use cranelift_codegen::ir::{StackSlot, StackSlotKind::*}; use cranelift_frontend::FunctionBuilder; + use std::vec; + use std::vec::Vec; use wasmtime_environ::PtrSize; /// Provides information about the layout of a type when it is used as an @@ -1632,7 +1636,7 @@ pub(crate) fn translate_suspend<'a>( // 2. Afterwards, the tag return values let values = active_contref.values(env, builder); let required_capacity = - u32::try_from(std::cmp::max(suspend_args.len(), tag_return_types.len())) + u32::try_from(core::cmp::max(suspend_args.len(), tag_return_types.len())) .expect("Number of stack switching payloads should fit in u32"); if required_capacity > 0 { diff --git a/crates/cranelift/src/isa_builder.rs b/crates/cranelift/src/isa_builder.rs index b8d280e363f1..44da9bbc7f75 100644 --- a/crates/cranelift/src/isa_builder.rs +++ b/crates/cranelift/src/isa_builder.rs @@ -1,5 +1,6 @@ use cranelift_codegen::isa::IsaBuilder as Builder; use cranelift_codegen::settings::{self, Configurable, Flags, SetError}; +use std::vec::Vec; use target_lexicon::Triple; use wasmtime_environ::error::Result; use wasmtime_environ::{Setting, SettingKind}; diff --git a/crates/cranelift/src/lib.rs b/crates/cranelift/src/lib.rs index ee88cfd32c55..7231c196ec21 100644 --- a/crates/cranelift/src/lib.rs +++ b/crates/cranelift/src/lib.rs @@ -10,10 +10,19 @@ //! > Wasmtime repository to start a discussion about doing so, but otherwise //! > be aware that your usage of this crate is not supported. -// See documentation in crates/wasmtime/src/runtime.rs for why this is -// selectively enabled here. +#![cfg_attr(not(test), no_std)] #![warn(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +#[cfg(not(feature = "std"))] +#[macro_use] +extern crate alloc as std; +#[cfg(feature = "std")] +#[macro_use] +extern crate std; + +use std::vec; +use std::vec::Vec; + use cranelift_codegen::{ FinalizedMachReloc, FinalizedRelocTarget, MachTrap, binemit, cursor::FuncCursor, @@ -41,6 +50,7 @@ mod alias_region_key; mod bounds_checks; mod builder; mod compiler; +#[cfg(feature = "std")] mod debug; mod func_environ; mod translate; diff --git a/crates/cranelift/src/obj.rs b/crates/cranelift/src/obj.rs index 64104c072cbe..ddb76c7a65f3 100644 --- a/crates/cranelift/src/obj.rs +++ b/crates/cranelift/src/obj.rs @@ -14,6 +14,7 @@ //! names have format "_trampoline_N", where N is `SignatureIndex`. use crate::CompiledFunction; +use core::ops::Range; use cranelift_codegen::TextSectionBuilder; use cranelift_codegen::isa::unwind::{UnwindInfo, systemv}; use cranelift_control::ControlPlane; @@ -21,7 +22,9 @@ use gimli::RunTimeEndian; use gimli::write::{Address, EhFrame, EndianVec, FrameTable, Writer}; use object::write::{Object, SectionId, StandardSegment, Symbol, SymbolId, SymbolSection}; use object::{Architecture, SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope}; -use std::ops::Range; +use std::boxed::Box; +use std::vec; +use std::vec::Vec; use wasmtime_environ::error::Result; use wasmtime_environ::{Compiler, TripleExt}; use wasmtime_environ::{FuncKey, obj}; diff --git a/crates/cranelift/src/translate/code_translator.rs b/crates/cranelift/src/translate/code_translator.rs index e150263136c7..0315338f7ce6 100644 --- a/crates/cranelift/src/translate/code_translator.rs +++ b/crates/cranelift/src/translate/code_translator.rs @@ -89,9 +89,11 @@ use cranelift_codegen::ir::{ use cranelift_codegen::ir::{BlockArg, types::*}; use cranelift_codegen::packed_option::ReservedValue; use cranelift_frontend::{FunctionBuilder, Variable}; +use hashbrown::{HashMap, hash_map}; use itertools::Itertools; use smallvec::{SmallVec, ToSmallVec}; -use std::collections::{HashMap, hash_map}; +use std::string::ToString; +use std::vec; use std::vec::Vec; use wasmparser::{FuncValidator, MemArg, Operator, WasmModuleResources}; use wasmtime_environ::{ diff --git a/crates/cranelift/src/translate/func_translator.rs b/crates/cranelift/src/translate/func_translator.rs index 80323def5c14..8072c183536a 100644 --- a/crates/cranelift/src/translate/func_translator.rs +++ b/crates/cranelift/src/translate/func_translator.rs @@ -12,6 +12,7 @@ use cranelift_codegen::entity::EntityRef; use cranelift_codegen::ir::{self, Block, InstBuilder, ValueLabel}; use cranelift_codegen::timing; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; +use std::{vec, vec::Vec}; use wasmparser::{BinaryReader, FuncValidator, FunctionBody, OperatorsReader, WasmModuleResources}; use wasmtime_environ::{TypeConvert, WasmResult}; diff --git a/crates/cranelift/src/translate/stack.rs b/crates/cranelift/src/translate/stack.rs index 95250df682f7..1d0d81ca27e2 100644 --- a/crates/cranelift/src/translate/stack.rs +++ b/crates/cranelift/src/translate/stack.rs @@ -6,6 +6,7 @@ use cranelift_codegen::ir::{self, Block, ExceptionTag, Inst, Value}; use cranelift_frontend::FunctionBuilder; +use std::vec; use std::vec::Vec; use wasmtime_environ::FrameStackShape; diff --git a/crates/cranelift/src/translate/translation_utils.rs b/crates/cranelift/src/translate/translation_utils.rs index d7595911bab9..68afc28e3061 100644 --- a/crates/cranelift/src/translate/translation_utils.rs +++ b/crates/cranelift/src/translate/translation_utils.rs @@ -19,11 +19,11 @@ where { return Ok(match ty { wasmparser::BlockType::Empty => ( - itertools::Either::Left(std::iter::empty()), + itertools::Either::Left(core::iter::empty()), itertools::Either::Left(None.into_iter()), ), wasmparser::BlockType::Type(ty) => ( - itertools::Either::Left(std::iter::empty()), + itertools::Either::Left(core::iter::empty()), itertools::Either::Left(Some(ty).into_iter()), ), wasmparser::BlockType::FuncType(ty_index) => { diff --git a/crates/cranelift/src/trap.rs b/crates/cranelift/src/trap.rs index 158f3239e73b..a6ce42336bcb 100644 --- a/crates/cranelift/src/trap.rs +++ b/crates/cranelift/src/trap.rs @@ -5,6 +5,8 @@ use cranelift_codegen::ir::condcodes::IntCC; use cranelift_codegen::ir::types::I8; use cranelift_codegen::ir::{self, InstBuilder}; use cranelift_frontend::FunctionBuilder; +use std::vec; +use std::vec::Vec; use wasmtime_environ::{BuiltinFunctionIndex, TripleExt}; /// Helper trait to share translation of traps between core functions and diff --git a/crates/wasmtime/Cargo.toml b/crates/wasmtime/Cargo.toml index b56304c22997..1a5700c92cfb 100644 --- a/crates/wasmtime/Cargo.toml +++ b/crates/wasmtime/Cargo.toml @@ -168,7 +168,7 @@ backtrace = ["std", "wasmtime-environ/backtrace"] # with the Cranelift compiler. Cranelift is the default compilation backend of # Wasmtime. If disabled then WebAssembly modules can only be created from # precompiled WebAssembly modules. -cranelift = ["dep:wasmtime-cranelift", "std", "wasmtime-unwinder/cranelift"] +cranelift = ["dep:wasmtime-cranelift", "wasmtime-unwinder/cranelift"] # Enables support for Winch, the WebAssembly baseline compiler. The Winch compiler # strategy in `Config` will be available. It is currently in active development @@ -362,6 +362,7 @@ std = [ "wasmtime-jit-icache-coherence", "wasmtime-jit-debug?/std", "futures?/std", + "wasmtime-cranelift?/std", ] # Enables support for the `Store::call_hook` API which enables injecting custom