wasmtime_environ/compile/mod.rs
1//! A `Compilation` contains the compiled function bodies for a WebAssembly
2//! module.
3
4use crate::prelude::*;
5use crate::{obj, Tunables};
6use crate::{
7 BuiltinFunctionIndex, DefinedFuncIndex, FlagValue, FuncIndex, FunctionLoc, ObjectKind,
8 PrimaryMap, StaticModuleIndex, TripleExt, WasmError, WasmFuncType,
9};
10use anyhow::Result;
11use object::write::{Object, SymbolId};
12use object::{Architecture, BinaryFormat, FileFlags};
13use std::any::Any;
14use std::borrow::Cow;
15use std::fmt;
16use std::path;
17use std::sync::Arc;
18
19mod address_map;
20mod module_artifacts;
21mod module_environ;
22mod module_types;
23mod stack_maps;
24mod trap_encoding;
25
26pub use self::address_map::*;
27pub use self::module_artifacts::*;
28pub use self::module_environ::*;
29pub use self::module_types::*;
30pub use self::stack_maps::*;
31pub use self::trap_encoding::*;
32
33/// An error while compiling WebAssembly to machine code.
34#[derive(Debug)]
35pub enum CompileError {
36 /// A wasm translation error occurred.
37 Wasm(WasmError),
38
39 /// A compilation error occurred.
40 Codegen(String),
41
42 /// A compilation error occurred.
43 DebugInfoNotSupported,
44}
45
46impl fmt::Display for CompileError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 CompileError::Wasm(_) => write!(f, "WebAssembly translation error"),
50 CompileError::Codegen(s) => write!(f, "Compilation error: {s}"),
51 CompileError::DebugInfoNotSupported => {
52 write!(f, "Debug info is not supported with this configuration")
53 }
54 }
55 }
56}
57
58impl From<WasmError> for CompileError {
59 fn from(err: WasmError) -> CompileError {
60 CompileError::Wasm(err)
61 }
62}
63
64impl core::error::Error for CompileError {
65 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
66 match self {
67 CompileError::Wasm(e) => Some(e),
68 _ => None,
69 }
70 }
71}
72
73/// What relocations can be applied against.
74///
75/// Each wasm function may refer to various other `RelocationTarget` entries.
76#[derive(Copy, Clone, Debug, PartialEq, Eq)]
77pub enum RelocationTarget {
78 /// This is a reference to another defined wasm function in the same module.
79 Wasm(FuncIndex),
80 /// This is a reference to a trampoline for a builtin function.
81 Builtin(BuiltinFunctionIndex),
82 /// A pulley->host call from the interpreter.
83 PulleyHostcall(u32),
84}
85
86/// Implementation of an incremental compilation's key/value cache store.
87///
88/// In theory, this could just be Cranelift's `CacheKvStore` trait, but it is not as we want to
89/// make sure that wasmtime isn't too tied to Cranelift internals (and as a matter of fact, we
90/// can't depend on the Cranelift trait here).
91pub trait CacheStore: Send + Sync + std::fmt::Debug {
92 /// Try to retrieve an arbitrary cache key entry, and returns a reference to bytes that were
93 /// inserted via `Self::insert` before.
94 fn get(&self, key: &[u8]) -> Option<Cow<[u8]>>;
95
96 /// Given an arbitrary key and bytes, stores them in the cache.
97 ///
98 /// Returns false when insertion in the cache failed.
99 fn insert(&self, key: &[u8], value: Vec<u8>) -> bool;
100}
101
102/// Abstract trait representing the ability to create a `Compiler` below.
103///
104/// This is used in Wasmtime to separate compiler implementations, currently
105/// mostly used to separate Cranelift from Wasmtime itself.
106pub trait CompilerBuilder: Send + Sync + fmt::Debug {
107 /// Sets the target of compilation to the target specified.
108 fn target(&mut self, target: target_lexicon::Triple) -> Result<()>;
109
110 /// Enables clif output in the directory specified.
111 fn clif_dir(&mut self, _path: &path::Path) -> Result<()> {
112 anyhow::bail!("clif output not supported");
113 }
114
115 /// Returns the currently configured target triple that compilation will
116 /// produce artifacts for.
117 fn triple(&self) -> &target_lexicon::Triple;
118
119 /// Compiler-specific method to configure various settings in the compiler
120 /// itself.
121 ///
122 /// This is expected to be defined per-compiler. Compilers should return
123 /// errors for unknown names/values.
124 fn set(&mut self, name: &str, val: &str) -> Result<()>;
125
126 /// Compiler-specific method for configuring settings.
127 ///
128 /// Same as [`CompilerBuilder::set`] except for enabling boolean flags.
129 /// Currently cranelift uses this to sometimes enable a family of settings.
130 fn enable(&mut self, name: &str) -> Result<()>;
131
132 /// Returns a list of all possible settings that can be configured with
133 /// [`CompilerBuilder::set`] and [`CompilerBuilder::enable`].
134 fn settings(&self) -> Vec<Setting>;
135
136 /// Enables Cranelift's incremental compilation cache, using the given `CacheStore`
137 /// implementation.
138 ///
139 /// This will return an error if the compiler does not support incremental compilation.
140 fn enable_incremental_compilation(&mut self, cache_store: Arc<dyn CacheStore>) -> Result<()>;
141
142 /// Set the tunables for this compiler.
143 fn set_tunables(&mut self, tunables: Tunables) -> Result<()>;
144
145 /// Builds a new [`Compiler`] object from this configuration.
146 fn build(&self) -> Result<Box<dyn Compiler>>;
147
148 /// Enables or disables wmemcheck during runtime according to the wmemcheck CLI flag.
149 fn wmemcheck(&mut self, _enable: bool) {}
150}
151
152/// Description of compiler settings returned by [`CompilerBuilder::settings`].
153#[derive(Clone, Copy, Debug)]
154pub struct Setting {
155 /// The name of the setting.
156 pub name: &'static str,
157 /// The description of the setting.
158 pub description: &'static str,
159 /// The kind of the setting.
160 pub kind: SettingKind,
161 /// The supported values of the setting (for enum values).
162 pub values: Option<&'static [&'static str]>,
163}
164
165/// Different kinds of [`Setting`] values that can be configured in a
166/// [`CompilerBuilder`]
167#[derive(Clone, Copy, Debug)]
168pub enum SettingKind {
169 /// The setting is an enumeration, meaning it's one of a set of values.
170 Enum,
171 /// The setting is a number.
172 Num,
173 /// The setting is a boolean.
174 Bool,
175 /// The setting is a preset.
176 Preset,
177}
178
179/// The result of compiling a single function body.
180pub struct CompiledFunctionBody {
181 /// The code. This is whatever type the `Compiler` implementation wants it
182 /// to be, we just shepherd it around.
183 pub code: Box<dyn Any + Send>,
184 /// Whether the compiled function needs a GC heap to run; that is, whether
185 /// it reads a struct field, allocates, an array, or etc...
186 pub needs_gc_heap: bool,
187}
188
189/// An implementation of a compiler which can compile WebAssembly functions to
190/// machine code and perform other miscellaneous tasks needed by the JIT runtime.
191pub trait Compiler: Send + Sync {
192 /// Compiles the function `index` within `translation`.
193 ///
194 /// The body of the function is available in `data` and configuration
195 /// values are also passed in via `tunables`. Type information in
196 /// `translation` is all relative to `types`.
197 fn compile_function(
198 &self,
199 translation: &ModuleTranslation<'_>,
200 index: DefinedFuncIndex,
201 data: FunctionBodyData<'_>,
202 types: &ModuleTypesBuilder,
203 ) -> Result<CompiledFunctionBody, CompileError>;
204
205 /// Compile a trampoline for an array-call host function caller calling the
206 /// `index`th Wasm function.
207 ///
208 /// The trampoline should save the necessary state to record the
209 /// host-to-Wasm transition (e.g. registers used for fast stack walking).
210 fn compile_array_to_wasm_trampoline(
211 &self,
212 translation: &ModuleTranslation<'_>,
213 types: &ModuleTypesBuilder,
214 index: DefinedFuncIndex,
215 ) -> Result<CompiledFunctionBody, CompileError>;
216
217 /// Compile a trampoline for a Wasm caller calling a array callee with the
218 /// given signature.
219 ///
220 /// The trampoline should save the necessary state to record the
221 /// Wasm-to-host transition (e.g. registers used for fast stack walking).
222 fn compile_wasm_to_array_trampoline(
223 &self,
224 wasm_func_ty: &WasmFuncType,
225 ) -> Result<CompiledFunctionBody, CompileError>;
226
227 /// Creates a trampoline that can be used to call Wasmtime's implementation
228 /// of the builtin function specified by `index`.
229 ///
230 /// The trampoline created can technically have any ABI but currently has
231 /// the native ABI. This will then perform all the necessary duties of an
232 /// exit trampoline from wasm and then perform the actual dispatch to the
233 /// builtin function. Builtin functions in Wasmtime are stored in an array
234 /// in all `VMContext` pointers, so the call to the host is an indirect
235 /// call.
236 fn compile_wasm_to_builtin(
237 &self,
238 index: BuiltinFunctionIndex,
239 ) -> Result<CompiledFunctionBody, CompileError>;
240
241 /// Returns the list of relocations required for a function from one of the
242 /// previous `compile_*` functions above.
243 fn compiled_function_relocation_targets<'a>(
244 &'a self,
245 func: &'a dyn Any,
246 ) -> Box<dyn Iterator<Item = RelocationTarget> + 'a>;
247
248 /// Appends a list of compiled functions to an in-memory object.
249 ///
250 /// This function will receive the same `Box<dyn Any>` produced as part of
251 /// compilation from functions like `compile_function`,
252 /// `compile_host_to_wasm_trampoline`, and other component-related shims.
253 /// Internally this will take all of these functions and add information to
254 /// the object such as:
255 ///
256 /// * Compiled code in a `.text` section
257 /// * Unwind information in Wasmtime-specific sections
258 /// * Relocations, if necessary, for the text section
259 ///
260 /// Each function is accompanied with its desired symbol name and the return
261 /// value of this function is the symbol for each function as well as where
262 /// each function was placed within the object.
263 ///
264 /// The `resolve_reloc` argument is intended to resolving relocations
265 /// between function, chiefly resolving intra-module calls within one core
266 /// wasm module. The closure here takes two arguments:
267 ///
268 /// 1. First, the index within `funcs` that is being resolved,
269 ///
270 /// 2. and next the `RelocationTarget` which is the relocation target to
271 /// resolve.
272 ///
273 /// The return value is an index within `funcs` that the relocation points
274 /// to.
275 fn append_code(
276 &self,
277 obj: &mut Object<'static>,
278 funcs: &[(String, Box<dyn Any + Send>)],
279 resolve_reloc: &dyn Fn(usize, RelocationTarget) -> usize,
280 ) -> Result<Vec<(SymbolId, FunctionLoc)>>;
281
282 /// Creates a new `Object` file which is used to build the results of a
283 /// compilation into.
284 ///
285 /// The returned object file will have an appropriate
286 /// architecture/endianness for `self.triple()`, but at this time it is
287 /// always an ELF file, regardless of target platform.
288 fn object(&self, kind: ObjectKind) -> Result<Object<'static>> {
289 use target_lexicon::Architecture::*;
290
291 let triple = self.triple();
292 let (arch, flags) = match triple.architecture {
293 X86_32(_) => (Architecture::I386, 0),
294 X86_64 => (Architecture::X86_64, 0),
295 Arm(_) => (Architecture::Arm, 0),
296 Aarch64(_) => (Architecture::Aarch64, 0),
297 S390x => (Architecture::S390x, 0),
298 Riscv64(_) => (Architecture::Riscv64, 0),
299 // XXX: the `object` crate won't successfully build an object
300 // with relocations and such if it doesn't know the
301 // architecture, so just pretend we are riscv64. Yolo!
302 //
303 // Also note that we add some flags to `e_flags` in the object file
304 // to indicate that it's pulley, not actually riscv64. This is used
305 // by `wasmtime objdump` for example.
306 Pulley32 | Pulley32be => (Architecture::Riscv64, obj::EF_WASMTIME_PULLEY32),
307 Pulley64 | Pulley64be => (Architecture::Riscv64, obj::EF_WASMTIME_PULLEY64),
308 architecture => {
309 anyhow::bail!("target architecture {:?} is unsupported", architecture,);
310 }
311 };
312 let mut obj = Object::new(
313 BinaryFormat::Elf,
314 arch,
315 match triple.endianness().unwrap() {
316 target_lexicon::Endianness::Little => object::Endianness::Little,
317 target_lexicon::Endianness::Big => object::Endianness::Big,
318 },
319 );
320 obj.flags = FileFlags::Elf {
321 os_abi: obj::ELFOSABI_WASMTIME,
322 e_flags: flags
323 | match kind {
324 ObjectKind::Module => obj::EF_WASMTIME_MODULE,
325 ObjectKind::Component => obj::EF_WASMTIME_COMPONENT,
326 },
327 abi_version: 0,
328 };
329 Ok(obj)
330 }
331
332 /// Returns the target triple that this compiler is compiling for.
333 fn triple(&self) -> &target_lexicon::Triple;
334
335 /// Returns the alignment necessary to align values to the page size of the
336 /// compilation target. Note that this may be an upper-bound where the
337 /// alignment is larger than necessary for some platforms since it may
338 /// depend on the platform's runtime configuration.
339 fn page_size_align(&self) -> u64 {
340 // Conservatively assume the max-of-all-supported-hosts for pulley
341 // and round up to 64k.
342 if self.triple().is_pulley() {
343 return 0x10000;
344 }
345
346 use target_lexicon::*;
347 match (self.triple().operating_system, self.triple().architecture) {
348 (
349 OperatingSystem::MacOSX { .. }
350 | OperatingSystem::Darwin(_)
351 | OperatingSystem::IOS(_)
352 | OperatingSystem::TvOS(_),
353 Architecture::Aarch64(..),
354 ) => 0x4000,
355 // 64 KB is the maximal page size (i.e. memory translation granule size)
356 // supported by the architecture and is used on some platforms.
357 (_, Architecture::Aarch64(..)) => 0x10000,
358 _ => 0x1000,
359 }
360 }
361
362 /// Returns a list of configured settings for this compiler.
363 fn flags(&self) -> Vec<(&'static str, FlagValue<'static>)>;
364
365 /// Same as [`Compiler::flags`], but ISA-specific (a cranelift-ism)
366 fn isa_flags(&self) -> Vec<(&'static str, FlagValue<'static>)>;
367
368 /// Get a flag indicating whether branch protection is enabled.
369 fn is_branch_protection_enabled(&self) -> bool;
370
371 /// Returns a suitable compiler usable for component-related compilations.
372 ///
373 /// Note that the `ComponentCompiler` trait can also be implemented for
374 /// `Self` in which case this function would simply return `self`.
375 #[cfg(feature = "component-model")]
376 fn component_compiler(&self) -> &dyn crate::component::ComponentCompiler;
377
378 /// Appends generated DWARF sections to the `obj` specified.
379 ///
380 /// The `translations` track all compiled functions and `get_func` can be
381 /// used to acquire the metadata for a particular function within a module.
382 fn append_dwarf<'a>(
383 &self,
384 obj: &mut Object<'_>,
385 translations: &'a PrimaryMap<StaticModuleIndex, ModuleTranslation<'a>>,
386 get_func: &'a dyn Fn(
387 StaticModuleIndex,
388 DefinedFuncIndex,
389 ) -> (SymbolId, &'a (dyn Any + Send)),
390 dwarf_package_bytes: Option<&'a [u8]>,
391 tunables: &'a Tunables,
392 ) -> Result<()>;
393
394 /// Creates a new System V Common Information Entry for the ISA.
395 ///
396 /// Returns `None` if the ISA does not support System V unwind information.
397 fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
398 // By default, an ISA cannot create a System V CIE.
399 None
400 }
401}