From c810eff81c86c627cdecaaa269616a25f925925b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 2 May 2024 16:29:55 -0700 Subject: [PATCH] Migrate the `wasmtime-environ` crate to `no_std` (#8528) * Migrate the `wasmtime-environ` crate to `no_std` This commit migrates the `wasmtime-environ` crate to by default being tagged with `#![no_std]`. Only the `component-model` and `gc` features are able to be built without `std`, all other features will implicitly activate the `std` feature as they currently require it one way or another. CI is updated to build `wasmtime-environ` with these two features active on a no_std platform. This additionally, for the workspace, disables the `std` feature for the `target-lexicon`, `indexmap`, `object`, and `gimli` dependencies. For object/gimli all other crates in the workspace now enable the `std` feature, but for `wasmtime-environ` this activation is omitted. The `thiserror` dependency was dropped from `wasmtime-environ` and additionally `hashbrown` was added for explicit usage of maps. * Always enable `std` for environ for now prtest:full * Add some more std features --- .github/workflows/main.yml | 5 +- Cargo.lock | 1 - Cargo.toml | 10 +-- cranelift/codegen/Cargo.toml | 2 +- cranelift/filetests/Cargo.toml | 2 +- cranelift/object/Cargo.toml | 2 +- cranelift/reader/Cargo.toml | 2 +- crates/cranelift/Cargo.toml | 4 +- crates/environ/Cargo.toml | 30 +++++--- crates/environ/src/compile/address_map.rs | 1 + crates/environ/src/compile/mod.rs | 37 ++++++++-- .../environ/src/compile/module_artifacts.rs | 1 + crates/environ/src/compile/module_environ.rs | 1 + crates/environ/src/compile/trap_encoding.rs | 1 + crates/environ/src/component/compiler.rs | 1 + crates/environ/src/component/dfg.rs | 1 + crates/environ/src/component/info.rs | 2 +- crates/environ/src/component/translate.rs | 1 + crates/environ/src/component/types.rs | 10 +-- crates/environ/src/component/types_builder.rs | 2 +- .../src/component/types_builder/resources.rs | 1 + crates/environ/src/demangling.rs | 6 +- crates/environ/src/fact.rs | 1 + crates/environ/src/fact/core_types.rs | 1 + crates/environ/src/fact/signature.rs | 1 + crates/environ/src/fact/trampoline.rs | 1 + crates/environ/src/fact/transcode.rs | 1 + crates/environ/src/fact/traps.rs | 1 + crates/environ/src/lib.rs | 73 +++++++++++++++++++ crates/environ/src/module.rs | 10 +-- crates/environ/src/module_artifacts.rs | 7 +- crates/environ/src/module_types.rs | 2 +- crates/environ/src/scopevec.rs | 6 +- crates/environ/src/stack_map.rs | 1 + crates/environ/src/trap_encoding.rs | 3 +- crates/environ/src/vmoffsets.rs | 6 +- crates/explorer/Cargo.toml | 2 +- .../Cargo.toml | 2 +- crates/wasmtime/Cargo.toml | 6 +- .../src/runtime/component/instance.rs | 2 +- crates/winch/Cargo.toml | 4 +- examples/min-platform/Cargo.toml | 2 +- 42 files changed, 188 insertions(+), 67 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c9ecf71e96..98cd8b8bce 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -366,16 +366,13 @@ jobs: - run: cargo check -p wasmtime-jit-icache-coherence env: CARGO_BUILD_TARGET: x86_64-unknown-none - - run: cargo check -p wasmtime-component-util - env: - CARGO_BUILD_TARGET: x86_64-unknown-none - run: cargo check -p wasmtime-asm-macros env: CARGO_BUILD_TARGET: x86_64-unknown-none - run: cargo check -p wasmtime-slab env: CARGO_BUILD_TARGET: x86_64-unknown-none - - run: cargo check -p wasmtime-types + - run: cargo check -p wasmtime-environ --features gc,component-model env: CARGO_BUILD_TARGET: x86_64-unknown-none diff --git a/Cargo.lock b/Cargo.lock index ed49de52d9..4cd3570af4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3664,7 +3664,6 @@ dependencies = [ "serde", "serde_derive", "target-lexicon", - "thiserror", "wasm-encoder 0.206.0", "wasmparser 0.206.0", "wasmprinter", diff --git a/Cargo.toml b/Cargo.toml index 0b74728b56..bed1553dd6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,7 +96,7 @@ toml = { workspace = true } similar = { workspace = true } libtest-mimic = "0.7.0" capstone = { workspace = true } -object = { workspace = true } +object = { workspace = true, features = ['std'] } [target.'cfg(windows)'.dev-dependencies] windows-sys = { workspace = true, features = ["Win32_System_Memory"] } @@ -215,7 +215,7 @@ byte-array-literals = { path = "crates/wasi-preview1-component-adapter/byte-arra regalloc2 = "0.9.3" # cap-std family: -target-lexicon = { version = "0.12.13", default-features = false, features = ["std"] } +target-lexicon = "0.12.13" cap-std = "3.0.0" cap-rand = { version = "3.0.0", features = ["small_rng"] } cap-fs-ext = "3.0.0" @@ -244,8 +244,8 @@ wit-component = "0.206.0" # Non-Bytecode Alliance maintained dependencies: # -------------------------- cc = "1.0" -object = { version = "0.33", default-features = false, features = ['read_core', 'elf', 'std'] } -gimli = { version = "0.28.0", default-features = false, features = ['read', 'std'] } +object = { version = "0.33", default-features = false, features = ['read_core', 'elf'] } +gimli = { version = "0.28.0", default-features = false, features = ['read'] } anyhow = { version = "1.0.22", default-features = false } windows-sys = "0.52.0" env_logger = "0.10" @@ -288,7 +288,7 @@ http-body = "1.0.0" http-body-util = "0.1.0" bytes = "1.4" futures = { version = "0.3.27", default-features = false } -indexmap = "2.0.0" +indexmap = { version = "2.0.0", default-features = false } pretty_env_logger = "0.5.0" syn = "2.0.25" test-log = { version = "0.2", default-features = false, features = ["trace"] } diff --git a/cranelift/codegen/Cargo.toml b/cranelift/codegen/Cargo.toml index 3860dc9116..75e00d2add 100644 --- a/cranelift/codegen/Cargo.toml +++ b/cranelift/codegen/Cargo.toml @@ -29,7 +29,7 @@ log = { workspace = true } serde = { workspace = true, optional = true } serde_derive = { workspace = true, optional = true } postcard = { workspace = true, optional = true } -gimli = { workspace = true, features = ["write"], optional = true } +gimli = { workspace = true, features = ["write", "std"], optional = true } smallvec = { workspace = true } regalloc2 = { workspace = true, features = ["checker", "trace-log"] } souper-ir = { version = "2.1.0", optional = true } diff --git a/cranelift/filetests/Cargo.toml b/cranelift/filetests/Cargo.toml index bcf7acab14..502b5ec782 100644 --- a/cranelift/filetests/Cargo.toml +++ b/cranelift/filetests/Cargo.toml @@ -23,7 +23,7 @@ cranelift-module = { workspace = true } cranelift-control = { workspace = true } file-per-thread-logger = { workspace = true } filecheck = { workspace = true } -gimli = { workspace = true } +gimli = { workspace = true, features = ['std'] } log = { workspace = true } num_cpus = "1.8.0" target-lexicon = { workspace = true } diff --git a/cranelift/object/Cargo.toml b/cranelift/object/Cargo.toml index b7d9fa73db..85914f74ad 100644 --- a/cranelift/object/Cargo.toml +++ b/cranelift/object/Cargo.toml @@ -16,7 +16,7 @@ workspace = true cranelift-module = { workspace = true } cranelift-codegen = { workspace = true, features = ["std"] } cranelift-control = { workspace = true } -object = { workspace = true, features = ["write"] } +object = { workspace = true, features = ["write", "std"] } target-lexicon = { workspace = true } anyhow = { workspace = true } log = { workspace = true } diff --git a/cranelift/reader/Cargo.toml b/cranelift/reader/Cargo.toml index a1df505233..6f5de4b0e3 100644 --- a/cranelift/reader/Cargo.toml +++ b/cranelift/reader/Cargo.toml @@ -16,4 +16,4 @@ workspace = true anyhow = { workspace = true, features = ['std'] } cranelift-codegen = { workspace = true } smallvec = { workspace = true } -target-lexicon = { workspace = true } +target-lexicon = { workspace = true, features = ['std'] } diff --git a/crates/cranelift/Cargo.toml b/crates/cranelift/Cargo.toml index 2d3eac7c8b..aef6eb5380 100644 --- a/crates/cranelift/Cargo.toml +++ b/crates/cranelift/Cargo.toml @@ -25,8 +25,8 @@ cranelift-native = { workspace = true } cranelift-control = { workspace = true } wasmparser = { workspace = true } target-lexicon = { workspace = true } -gimli = { workspace = true } -object = { workspace = true, features = ['write'] } +gimli = { workspace = true, features = ['std'] } +object = { workspace = true, features = ['write', 'std'] } thiserror = { workspace = true } cfg-if = { workspace = true } wasmtime-versioned-export-macros = { workspace = true } diff --git a/crates/environ/Cargo.toml b/crates/environ/Cargo.toml index a9d714c37f..a098e59c84 100644 --- a/crates/environ/Cargo.toml +++ b/crates/environ/Cargo.toml @@ -14,14 +14,13 @@ edition.workspace = true workspace = true [dependencies] -anyhow = { workspace = true, features = ['std'] } +anyhow = { workspace = true } postcard = { workspace = true } cpp_demangle = { version = "0.4.3", optional = true } cranelift-entity = { workspace = true } -wasmtime-types = { workspace = true, features = ['std'] } +wasmtime-types = { workspace = true } wasmparser = { workspace = true } indexmap = { workspace = true, features = ["serde"] } -thiserror = { workspace = true } serde = { workspace = true } serde_derive = { workspace = true } log = { workspace = true } @@ -40,16 +39,25 @@ wat = { workspace = true } [[example]] name = "factc" -required-features = ['component-model'] +required-features = ['component-model', 'compile'] [features] -component-model = [ +component-model = ["dep:wasmtime-component-util"] +demangle = ['std', 'dep:rustc-demangle', 'dep:cpp_demangle'] +gc = [] +compile = [ + 'gimli/write', + 'object/write_core', + 'std', "dep:wasm-encoder", "dep:wasmprinter", - "dep:wasmtime-component-util", ] -demangle = ['dep:rustc-demangle', 'dep:cpp_demangle'] -gc = [] -compile = ['gimli/write', 'object/write_core'] -threads = [] -wmemcheck = [] +threads = ['std'] +wmemcheck = ['std'] +std = [ + 'wasmtime-types/std', + 'anyhow/std', + 'object/std', + 'wasmparser/std', + 'indexmap/std', +] diff --git a/crates/environ/src/compile/address_map.rs b/crates/environ/src/compile/address_map.rs index 614ccc3cbc..0eb64b91d5 100644 --- a/crates/environ/src/compile/address_map.rs +++ b/crates/environ/src/compile/address_map.rs @@ -1,6 +1,7 @@ //! Data structures to provide transformation of the source use crate::obj::ELF_WASMTIME_ADDRMAP; +use crate::prelude::*; use crate::InstructionAddressMap; use object::write::{Object, StandardSegment}; use object::{LittleEndian, SectionKind, U32Bytes}; diff --git a/crates/environ/src/compile/mod.rs b/crates/environ/src/compile/mod.rs index c8b1343cec..7205a86aae 100644 --- a/crates/environ/src/compile/mod.rs +++ b/crates/environ/src/compile/mod.rs @@ -1,6 +1,7 @@ //! A `Compilation` contains the compiled function bodies for a WebAssembly //! module. +use crate::prelude::*; use crate::{obj, Tunables}; use crate::{ BuiltinFunctionIndex, DefinedFuncIndex, FlagValue, FuncIndex, FunctionLoc, ObjectKind, @@ -14,7 +15,6 @@ use std::borrow::Cow; use std::fmt; use std::path; use std::sync::Arc; -use thiserror::Error; mod address_map; mod module_artifacts; @@ -29,21 +29,46 @@ pub use self::module_types::*; pub use self::trap_encoding::*; /// An error while compiling WebAssembly to machine code. -#[derive(Error, Debug)] +#[derive(Debug)] pub enum CompileError { /// A wasm translation error occured. - #[error("WebAssembly translation error")] - Wasm(#[from] WasmError), + Wasm(WasmError), /// A compilation error occured. - #[error("Compilation error: {0}")] Codegen(String), /// A compilation error occured. - #[error("Debug info is not supported with this configuration")] DebugInfoNotSupported, } +impl fmt::Display for CompileError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CompileError::Wasm(_) => write!(f, "WebAssembly translation error"), + CompileError::Codegen(s) => write!(f, "Compilation error: {s}"), + CompileError::DebugInfoNotSupported => { + write!(f, "Debug info is not supported with this configuration") + } + } + } +} + +impl From for CompileError { + fn from(err: WasmError) -> CompileError { + CompileError::Wasm(err) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for CompileError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + CompileError::Wasm(e) => Some(e), + _ => None, + } + } +} + /// What relocations can be applied against. /// /// Each wasm function may refer to various other `RelocationTarget` entries. diff --git a/crates/environ/src/compile/module_artifacts.rs b/crates/environ/src/compile/module_artifacts.rs index 79b6f4c779..fd74053237 100644 --- a/crates/environ/src/compile/module_artifacts.rs +++ b/crates/environ/src/compile/module_artifacts.rs @@ -1,6 +1,7 @@ //! Definitions of runtime structures and metadata which are serialized into ELF //! with `postcard` as part of a module's compilation process. +use crate::prelude::*; use crate::{ obj, CompiledFunctionInfo, CompiledModuleInfo, DebugInfoData, DefinedFuncIndex, FunctionLoc, FunctionName, MemoryInitialization, Metadata, ModuleTranslation, PrimaryMap, Tunables, diff --git a/crates/environ/src/compile/module_environ.rs b/crates/environ/src/compile/module_environ.rs index 29f8411935..518e02c701 100644 --- a/crates/environ/src/compile/module_environ.rs +++ b/crates/environ/src/compile/module_environ.rs @@ -2,6 +2,7 @@ use crate::module::{ FuncRefIndex, Initializer, MemoryInitialization, MemoryInitializer, MemoryPlan, Module, TablePlan, TableSegment, TableSegmentElements, }; +use crate::prelude::*; use crate::{ DataIndex, DefinedFuncIndex, ElemIndex, EntityIndex, EntityType, FuncIndex, GlobalIndex, InitMemory, MemoryIndex, ModuleTypesBuilder, PrimaryMap, StaticMemoryInitializer, TableIndex, diff --git a/crates/environ/src/compile/trap_encoding.rs b/crates/environ/src/compile/trap_encoding.rs index 7f38523f17..73fa6994cc 100644 --- a/crates/environ/src/compile/trap_encoding.rs +++ b/crates/environ/src/compile/trap_encoding.rs @@ -1,4 +1,5 @@ use crate::obj::ELF_WASMTIME_TRAPS; +use crate::prelude::*; use crate::TrapInformation; use object::write::{Object, StandardSegment}; use object::{LittleEndian, SectionKind, U32Bytes}; diff --git a/crates/environ/src/component/compiler.rs b/crates/environ/src/component/compiler.rs index ee0fe41a6e..aec715c9d1 100644 --- a/crates/environ/src/component/compiler.rs +++ b/crates/environ/src/component/compiler.rs @@ -1,4 +1,5 @@ use crate::component::{AllCallFunc, ComponentTranslation, ComponentTypesBuilder, TrampolineIndex}; +use crate::prelude::*; use anyhow::Result; use std::any::Any; diff --git a/crates/environ/src/component/dfg.rs b/crates/environ/src/component/dfg.rs index 81031ad09f..2e8d638da4 100644 --- a/crates/environ/src/component/dfg.rs +++ b/crates/environ/src/component/dfg.rs @@ -28,6 +28,7 @@ //! fused adapters, what arguments make their way to core wasm modules, etc. use crate::component::*; +use crate::prelude::*; use crate::{EntityIndex, EntityRef, PrimaryMap, WasmValType}; use indexmap::IndexMap; use std::collections::HashMap; diff --git a/crates/environ/src/component/info.rs b/crates/environ/src/component/info.rs index 4c9abeb722..2e2cb6c2ff 100644 --- a/crates/environ/src/component/info.rs +++ b/crates/environ/src/component/info.rs @@ -47,8 +47,8 @@ // requirements of embeddings change over time. use crate::component::*; +use crate::prelude::*; use crate::{EntityIndex, PrimaryMap, WasmValType}; -use indexmap::IndexMap; use serde_derive::{Deserialize, Serialize}; use wasmtime_types::ModuleInternedTypeIndex; diff --git a/crates/environ/src/component/translate.rs b/crates/environ/src/component/translate.rs index a80266f44e..0937dc9aaa 100644 --- a/crates/environ/src/component/translate.rs +++ b/crates/environ/src/component/translate.rs @@ -1,4 +1,5 @@ use crate::component::*; +use crate::prelude::*; use crate::Module; use crate::ScopeVec; use crate::{ diff --git a/crates/environ/src/component/types.rs b/crates/environ/src/component/types.rs index 5b4b1b2843..7847bacf36 100644 --- a/crates/environ/src/component/types.rs +++ b/crates/environ/src/component/types.rs @@ -1,9 +1,9 @@ use crate::component::{MAX_FLAT_PARAMS, MAX_FLAT_RESULTS}; +use crate::prelude::*; use crate::{EntityType, ModuleTypes, PrimaryMap}; -use indexmap::{IndexMap, IndexSet}; +use core::hash::{Hash, Hasher}; +use core::ops::Index; use serde_derive::{Deserialize, Serialize}; -use std::hash::{Hash, Hasher}; -use std::ops::Index; use wasmparser::types; use wasmtime_component_util::{DiscriminantSize, FlagsSize}; use wasmtime_types::ModuleInternedTypeIndex; @@ -285,7 +285,7 @@ impl ComponentTypes { macro_rules! impl_index { ($(impl Index<$ty:ident> for ComponentTypes { $output:ident => $field:ident })*) => ($( - impl std::ops::Index<$ty> for ComponentTypes { + impl core::ops::Index<$ty> for ComponentTypes { type Output = $output; #[inline] fn index(&self, idx: $ty) -> &$output { @@ -294,7 +294,7 @@ macro_rules! impl_index { } #[cfg(feature = "compile")] - impl std::ops::Index<$ty> for super::ComponentTypesBuilder { + impl core::ops::Index<$ty> for super::ComponentTypesBuilder { type Output = $output; #[inline] fn index(&self, idx: $ty) -> &$output { diff --git a/crates/environ/src/component/types_builder.rs b/crates/environ/src/component/types_builder.rs index 8922330618..ad91d4be74 100644 --- a/crates/environ/src/component/types_builder.rs +++ b/crates/environ/src/component/types_builder.rs @@ -1,11 +1,11 @@ use crate::component::*; +use crate::prelude::*; use crate::{ CompiledModuleInfo, EntityType, Module, ModuleTypes, ModuleTypesBuilder, PrimaryMap, TypeConvert, WasmHeapType, WasmValType, }; use anyhow::{bail, Result}; use cranelift_entity::EntityRef; -use indexmap::{IndexMap, IndexSet}; use std::collections::HashMap; use std::hash::Hash; use std::ops::Index; diff --git a/crates/environ/src/component/types_builder/resources.rs b/crates/environ/src/component/types_builder/resources.rs index 93df0ca2d3..834b884afa 100644 --- a/crates/environ/src/component/types_builder/resources.rs +++ b/crates/environ/src/component/types_builder/resources.rs @@ -71,6 +71,7 @@ use crate::component::{ ComponentTypes, ResourceIndex, RuntimeComponentInstanceIndex, TypeResourceTable, TypeResourceTableIndex, }; +use crate::prelude::*; use std::collections::HashMap; use wasmparser::types; diff --git a/crates/environ/src/demangling.rs b/crates/environ/src/demangling.rs index d8116aa967..8f5da1db2b 100644 --- a/crates/environ/src/demangling.rs +++ b/crates/environ/src/demangling.rs @@ -3,7 +3,7 @@ /// Demangles a single function name into a user-readable form. /// /// Currently supported: Rust/C/C++ function names. -pub fn demangle_function_name(writer: &mut impl std::fmt::Write, name: &str) -> std::fmt::Result { +pub fn demangle_function_name(writer: &mut impl core::fmt::Write, name: &str) -> core::fmt::Result { #[cfg(feature = "demangle")] if let Ok(demangled) = rustc_demangle::try_demangle(name) { return write!(writer, "{}", demangled); @@ -17,10 +17,10 @@ pub fn demangle_function_name(writer: &mut impl std::fmt::Write, name: &str) -> /// Demangles a function name if it's provided, or returns a unified representation based on the /// function index otherwise. pub fn demangle_function_name_or_index( - writer: &mut impl std::fmt::Write, + writer: &mut impl core::fmt::Write, name: Option<&str>, func_id: usize, -) -> std::fmt::Result { +) -> core::fmt::Result { match name { Some(name) => demangle_function_name(writer, name), None => write!(writer, "", func_id), diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rs index 38f7dc184a..8a024a75b4 100644 --- a/crates/environ/src/fact.rs +++ b/crates/environ/src/fact.rs @@ -24,6 +24,7 @@ use crate::component::{ StringEncoding, Transcode, TypeFuncIndex, }; use crate::fact::transcode::Transcoder; +use crate::prelude::*; use crate::{EntityRef, FuncIndex, GlobalIndex, MemoryIndex, PrimaryMap}; use std::borrow::Cow; use std::collections::HashMap; diff --git a/crates/environ/src/fact/core_types.rs b/crates/environ/src/fact/core_types.rs index b7699ad23c..31c2f7eb72 100644 --- a/crates/environ/src/fact/core_types.rs +++ b/crates/environ/src/fact/core_types.rs @@ -1,3 +1,4 @@ +use crate::prelude::*; use std::collections::HashMap; use wasm_encoder::{TypeSection, ValType}; diff --git a/crates/environ/src/fact/signature.rs b/crates/environ/src/fact/signature.rs index 37531dc8df..0bb9805a9f 100644 --- a/crates/environ/src/fact/signature.rs +++ b/crates/environ/src/fact/signature.rs @@ -2,6 +2,7 @@ use crate::component::{ComponentTypesBuilder, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS}; use crate::fact::{AdapterOptions, Context, Options}; +use crate::prelude::*; use wasm_encoder::ValType; /// Metadata about a core wasm signature which is created for a component model diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rs index a71ffacb1e..ed05b98a8f 100644 --- a/crates/environ/src/fact/trampoline.rs +++ b/crates/environ/src/fact/trampoline.rs @@ -28,6 +28,7 @@ use crate::fact::{ AdapterData, Body, Context, Function, FunctionId, Helper, HelperLocation, HelperType, Module, Options, }; +use crate::prelude::*; use crate::{FuncIndex, GlobalIndex}; use std::collections::HashMap; use std::mem; diff --git a/crates/environ/src/fact/transcode.rs b/crates/environ/src/fact/transcode.rs index e41b45c1ec..53ce6901f3 100644 --- a/crates/environ/src/fact/transcode.rs +++ b/crates/environ/src/fact/transcode.rs @@ -1,5 +1,6 @@ use crate::component::Transcode; use crate::fact::core_types::CoreTypes; +use crate::prelude::*; use crate::MemoryIndex; use wasm_encoder::{EntityType, ValType}; diff --git a/crates/environ/src/fact/traps.rs b/crates/environ/src/fact/traps.rs index e68bccfc13..8cd330f65b 100644 --- a/crates/environ/src/fact/traps.rs +++ b/crates/environ/src/fact/traps.rs @@ -18,6 +18,7 @@ //! This information is currently encoded as a custom section in the wasm //! module. +use crate::prelude::*; use std::collections::HashMap; use std::fmt; use wasm_encoder::Encode; diff --git a/crates/environ/src/lib.rs b/crates/environ/src/lib.rs index aa9334e20f..70bf77b7b3 100644 --- a/crates/environ/src/lib.rs +++ b/crates/environ/src/lib.rs @@ -5,6 +5,79 @@ #![deny(missing_docs)] #![warn(clippy::cast_sign_loss)] +#![no_std] + +#[cfg(feature = "std")] +#[macro_use] +extern crate std; +extern crate alloc; + +/// Rust module prelude for Wasmtime crates. +/// +/// Wasmtime crates that use `no_std` use `core::prelude::*` by default which +/// does not include `alloc`-related functionality such as `String` and `Vec`. +/// To have similar ergonomics to `std` and additionally group up some common +/// functionality this module is intended to be imported at the top of all +/// modules with: +/// +/// ```rust,ignore +/// use crate::*; +/// ``` +/// +/// Externally for crates that depend on `wasmtime-environ` they should have +/// this in the root of the crate: +/// +/// ```rust,ignore +/// use wasmtime_environ::prelude; +/// ``` +/// +/// and then `use crate::*` works as usual. +pub mod prelude { + pub use crate::Err2Anyhow; + pub use alloc::borrow::ToOwned; + pub use alloc::boxed::Box; + pub use alloc::format; + pub use alloc::string::{String, ToString}; + pub use alloc::vec; + pub use alloc::vec::Vec; + pub use wasmparser::map::{IndexMap, IndexSet}; +} + +/// Convenience trait for converting `Result` into `anyhow::Result` +/// +/// Typically this is automatically done with the `?` operator in Rust and +/// by default this trait isn't necessary. With the `anyhow` crate's `std` +/// feature disabled, however, the `?` operator won't work because the `Error` +/// trait is not defined. This trait helps to bridge this gap. +/// +/// This does the same thing as `?` when the `std` feature is enabled, and when +/// `std` is disabled it'll use different trait bounds to create an +/// `anyhow::Error`. +/// +/// This trait is not suitable as a public interface because features change +/// what implements the trait. It's good enough for a wasmtime internal +/// implementation detail, however. +pub trait Err2Anyhow { + /// Convert `self` to `anyhow::Result`. + fn err2anyhow(self) -> anyhow::Result; +} + +#[cfg(feature = "std")] +impl> Err2Anyhow for Result { + fn err2anyhow(self) -> anyhow::Result { + self.map_err(|e| e.into()) + } +} + +#[cfg(not(feature = "std"))] +impl Err2Anyhow for Result +where + E: core::fmt::Display + core::fmt::Debug + Send + Sync + 'static, +{ + fn err2anyhow(self) -> anyhow::Result { + self.map_err(anyhow::Error::msg) + } +} mod address_map; mod builtin; diff --git a/crates/environ/src/module.rs b/crates/environ/src/module.rs index b60cc97751..e25b481a1b 100644 --- a/crates/environ/src/module.rs +++ b/crates/environ/src/module.rs @@ -1,11 +1,11 @@ //! Data structures for representing decoded wasm modules. +use crate::prelude::*; use crate::{PrimaryMap, Tunables, WASM_PAGE_SIZE}; +use alloc::collections::BTreeMap; +use core::ops::Range; use cranelift_entity::{packed_option::ReservedValue, EntityRef}; -use indexmap::IndexMap; use serde_derive::{Deserialize, Serialize}; -use std::collections::BTreeMap; -use std::ops::Range; use wasmtime_types::*; /// Implementation styles for WebAssembly linear memory. @@ -36,10 +36,10 @@ impl MemoryStyle { } else { crate::WASM32_MAX_PAGES }; - let maximum = std::cmp::min( + let maximum = core::cmp::min( memory.maximum.unwrap_or(absolute_max_pages), if tunables.static_memory_bound_is_maximum { - std::cmp::min(tunables.static_memory_bound, absolute_max_pages) + core::cmp::min(tunables.static_memory_bound, absolute_max_pages) } else { absolute_max_pages }, diff --git a/crates/environ/src/module_artifacts.rs b/crates/environ/src/module_artifacts.rs index b35479b10e..09a3695d4b 100644 --- a/crates/environ/src/module_artifacts.rs +++ b/crates/environ/src/module_artifacts.rs @@ -1,11 +1,12 @@ //! Definitions of runtime structures and metadata which are serialized into ELF //! with `bincode` as part of a module's compilation process. +use crate::prelude::*; use crate::{DefinedFuncIndex, FilePos, FuncIndex, Module, PrimaryMap, StackMap}; +use core::fmt; +use core::ops::Range; +use core::str; use serde_derive::{Deserialize, Serialize}; -use std::fmt; -use std::ops::Range; -use std::str; use wasmtime_types::ModuleInternedTypeIndex; /// Secondary in-memory results of function compilation. diff --git a/crates/environ/src/module_types.rs b/crates/environ/src/module_types.rs index 72768d0f1d..13f1736bc7 100644 --- a/crates/environ/src/module_types.rs +++ b/crates/environ/src/module_types.rs @@ -1,6 +1,6 @@ use crate::PrimaryMap; +use core::ops::{Index, Range}; use serde_derive::{Deserialize, Serialize}; -use std::ops::{Index, Range}; use wasmtime_types::{ModuleInternedRecGroupIndex, ModuleInternedTypeIndex, WasmSubType}; /// All types used in a core wasm module. diff --git a/crates/environ/src/scopevec.rs b/crates/environ/src/scopevec.rs index ea95aaf68a..da779b9f51 100644 --- a/crates/environ/src/scopevec.rs +++ b/crates/environ/src/scopevec.rs @@ -1,4 +1,5 @@ -use std::cell::RefCell; +use crate::prelude::*; +use core::cell::RefCell; /// Small data structure to help extend the lifetime of a slice to a higher /// scope. @@ -54,13 +55,14 @@ impl ScopeVec { // // This all means that it should be safe to return a mutable slice of // all of `data` after the data has been pushed onto our internal list. - unsafe { std::slice::from_raw_parts_mut(ptr, len) } + unsafe { core::slice::from_raw_parts_mut(ptr, len) } } } #[cfg(test)] mod tests { use super::ScopeVec; + use crate::prelude::*; #[test] fn smoke() { diff --git a/crates/environ/src/stack_map.rs b/crates/environ/src/stack_map.rs index a6cbc5a837..428dc39936 100644 --- a/crates/environ/src/stack_map.rs +++ b/crates/environ/src/stack_map.rs @@ -1,3 +1,4 @@ +use crate::prelude::*; use serde_derive::{Deserialize, Serialize}; /// A map for determining where live GC references live in a stack frame. diff --git a/crates/environ/src/trap_encoding.rs b/crates/environ/src/trap_encoding.rs index 74b5b4402e..4ea826db1b 100644 --- a/crates/environ/src/trap_encoding.rs +++ b/crates/environ/src/trap_encoding.rs @@ -1,5 +1,5 @@ +use core::fmt; use object::{Bytes, LittleEndian, U32Bytes}; -use std::fmt; /// Information about trap. #[derive(Debug, PartialEq, Eq, Clone)] @@ -149,6 +149,7 @@ impl fmt::Display for Trap { } } +#[cfg(feature = "std")] impl std::error::Error for Trap {} /// Decodes the provided trap information section and attempts to find the trap diff --git a/crates/environ/src/vmoffsets.rs b/crates/environ/src/vmoffsets.rs index 166de6503d..46851d3a72 100644 --- a/crates/environ/src/vmoffsets.rs +++ b/crates/environ/src/vmoffsets.rs @@ -108,7 +108,7 @@ pub trait PtrSize { /// The offset of the `VMContext::runtime_limits` field fn vmcontext_runtime_limits(&self) -> u8 { u8::try_from(align( - u32::try_from(std::mem::size_of::()).unwrap(), + u32::try_from(core::mem::size_of::()).unwrap(), u32::from(self.size()), )) .unwrap() @@ -230,7 +230,7 @@ pub trait PtrSize { /// Return the offset of `VMNativeCallHostFuncContext::func_ref`. fn vmnative_call_host_func_context_func_ref(&self) -> u8 { u8::try_from(align( - u32::try_from(std::mem::size_of::()).unwrap(), + u32::try_from(core::mem::size_of::()).unwrap(), u32::from(self.size()), )) .unwrap() @@ -260,7 +260,7 @@ pub struct HostPtr; impl PtrSize for HostPtr { #[inline] fn size(&self) -> u8 { - std::mem::size_of::() as u8 + core::mem::size_of::() as u8 } } diff --git a/crates/explorer/Cargo.toml b/crates/explorer/Cargo.toml index dcda32acc2..7a0a80f074 100644 --- a/crates/explorer/Cargo.toml +++ b/crates/explorer/Cargo.toml @@ -17,6 +17,6 @@ capstone = { workspace = true } serde = { workspace = true } serde_derive = { workspace = true } serde_json = { workspace = true } -target-lexicon = { workspace = true } +target-lexicon = { workspace = true, features = ['std'] } wasmprinter = { workspace = true } wasmtime = { workspace = true, features = ["cranelift", "runtime"] } diff --git a/crates/wasi-preview1-component-adapter/Cargo.toml b/crates/wasi-preview1-component-adapter/Cargo.toml index cae715a7d0..6a6a2206fa 100644 --- a/crates/wasi-preview1-component-adapter/Cargo.toml +++ b/crates/wasi-preview1-component-adapter/Cargo.toml @@ -15,7 +15,7 @@ byte-array-literals = { workspace = true } [build-dependencies] wasm-encoder = { workspace = true } -object = { workspace = true, default-features = false, features = ["archive"] } +object = { workspace = true, default-features = false, features = ["archive", "std"] } [lib] test = false diff --git a/crates/wasmtime/Cargo.toml b/crates/wasmtime/Cargo.toml index 7705496229..7f14f346e8 100644 --- a/crates/wasmtime/Cargo.toml +++ b/crates/wasmtime/Cargo.toml @@ -21,7 +21,7 @@ features = ["component-model"] [dependencies] wasmtime-asm-macros = { workspace = true, optional = true } -wasmtime-environ = { workspace = true } +wasmtime-environ = { workspace = true, features = ['std'] } wasmtime-jit-debug = { workspace = true, features = ["gdb_jit_int", "perf_jitdump"], optional = true } wasmtime-jit-icache-coherence = { workspace = true, optional = true } wasmtime-cache = { workspace = true, optional = true } @@ -50,12 +50,12 @@ indexmap = { workspace = true } paste = "1.0.3" once_cell = { workspace = true } rayon = { version = "1.0", optional = true } -object = { workspace = true } +object = { workspace = true, features = ['std'] } async-trait = { workspace = true, optional = true } encoding_rs = { version = "0.8.31", optional = true } bumpalo = "3.11.0" fxprof-processed-profile = { version = "0.6.0", optional = true } -gimli = { workspace = true } +gimli = { workspace = true, features = ['std'] } # Support address-to-file/line information in traps when wasm files have DWARF # debugging information. addr2line = { version = "0.21.0", default-features = false, optional = true } diff --git a/crates/wasmtime/src/runtime/component/instance.rs b/crates/wasmtime/src/runtime/component/instance.rs index 6ecb9c6783..2138b4d797 100644 --- a/crates/wasmtime/src/runtime/component/instance.rs +++ b/crates/wasmtime/src/runtime/component/instance.rs @@ -8,10 +8,10 @@ use crate::runtime::vm::VMFuncRef; use crate::store::{StoreOpaque, Stored}; use crate::{AsContextMut, Module, StoreContextMut}; use anyhow::{anyhow, Context, Result}; -use indexmap::IndexMap; use std::marker; use std::ptr::NonNull; use std::sync::Arc; +use wasmtime_environ::prelude::IndexMap; use wasmtime_environ::{component::*, EngineOrModuleTypeIndex}; use wasmtime_environ::{EntityIndex, EntityType, Global, PrimaryMap, WasmValType}; diff --git a/crates/winch/Cargo.toml b/crates/winch/Cargo.toml index e5d5999ec1..7d2d67abfd 100644 --- a/crates/winch/Cargo.toml +++ b/crates/winch/Cargo.toml @@ -15,11 +15,11 @@ winch-codegen = { workspace = true } target-lexicon = { workspace = true } wasmtime-environ = { workspace = true } anyhow = { workspace = true } -object = { workspace = true } +object = { workspace = true, features = ['std'] } cranelift-codegen = { workspace = true } wasmtime-cranelift = { workspace = true } wasmparser = { workspace = true } -gimli = { workspace = true } +gimli = { workspace = true, features = ['std'] } [features] component-model = [ diff --git a/examples/min-platform/Cargo.toml b/examples/min-platform/Cargo.toml index 76bbb2e47b..ca59d183e7 100644 --- a/examples/min-platform/Cargo.toml +++ b/examples/min-platform/Cargo.toml @@ -11,4 +11,4 @@ workspace = true [dependencies] anyhow = { workspace = true, features = ['std'] } libloading = "0.8" -object = { workspace = true } +object = { workspace = true, features = ['std'] }