Skip to main content

wasmtime_environ/compile/
mod.rs

1//! A `Compilation` contains the compiled function bodies for a WebAssembly
2//! module.
3
4use crate::error::Result;
5use crate::prelude::*;
6use crate::{
7    DefinedFuncIndex, FlagValue, FuncKey, FunctionLoc, ObjectKind, PrimaryMap, StaticModuleIndex,
8    TripleExt, Tunables, WasmError, obj,
9};
10use object::write::{Object, SymbolId};
11use object::{Architecture, BinaryFormat, FileFlags};
12use std::any::Any;
13use std::borrow::Cow;
14use std::fmt;
15use std::path;
16use std::sync::Arc;
17
18mod address_map;
19mod frame_table;
20mod module_artifacts;
21mod module_environ;
22mod module_types;
23mod stack_maps;
24mod trap_encoding;
25
26pub use self::address_map::*;
27pub use self::frame_table::*;
28pub use self::module_artifacts::*;
29pub use self::module_environ::*;
30pub use self::module_types::*;
31pub use self::stack_maps::*;
32pub use self::trap_encoding::*;
33
34/// An error while compiling WebAssembly to machine code.
35#[derive(Debug)]
36pub enum CompileError {
37    /// A wasm translation error occurred.
38    Wasm(WasmError),
39
40    /// A compilation error occurred.
41    Codegen(String),
42
43    /// A compilation error occurred.
44    DebugInfoNotSupported,
45}
46
47impl fmt::Display for CompileError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            CompileError::Wasm(_) => write!(f, "WebAssembly translation error"),
51            CompileError::Codegen(s) => write!(f, "Compilation error: {s}"),
52            CompileError::DebugInfoNotSupported => {
53                write!(f, "Debug info is not supported with this configuration")
54            }
55        }
56    }
57}
58
59impl From<WasmError> for CompileError {
60    fn from(err: WasmError) -> CompileError {
61        CompileError::Wasm(err)
62    }
63}
64
65impl core::error::Error for CompileError {
66    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
67        match self {
68            CompileError::Wasm(e) => Some(e),
69            _ => None,
70        }
71    }
72}
73
74/// The component a core module is being compiled as part of.
75///
76/// A newtype, rather than a bare `&Component`, so that the `Compiler` trait can
77/// name the parameter without depending on `cfg(feature = "component-model")`.
78#[cfg(feature = "component-model")]
79#[derive(Clone, Copy)]
80pub struct EnclosingComponent<'a>(pub &'a crate::component::Component);
81
82/// Stand-in for `EnclosingComponent` when components are disabled at compile
83/// time.
84#[cfg(not(feature = "component-model"))]
85#[derive(Clone, Copy)]
86pub enum EnclosingComponent<'a> {
87    #[doc(hidden)]
88    Never(core::convert::Infallible, core::marker::PhantomData<&'a ()>),
89}
90
91/// Implementation of an incremental compilation's key/value cache store.
92///
93/// In theory, this could just be Cranelift's `CacheKvStore` trait, but it is not as we want to
94/// make sure that wasmtime isn't too tied to Cranelift internals (and as a matter of fact, we
95/// can't depend on the Cranelift trait here).
96pub trait CacheStore: Send + Sync + std::fmt::Debug {
97    /// Try to retrieve an arbitrary cache key entry, and returns a reference to bytes that were
98    /// inserted via `Self::insert` before.
99    fn get(&self, key: &[u8]) -> Option<Cow<'_, [u8]>>;
100
101    /// Given an arbitrary key and bytes, stores them in the cache.
102    ///
103    /// Returns false when insertion in the cache failed.
104    fn insert(&self, key: &[u8], value: Vec<u8>) -> bool;
105}
106
107/// Abstract trait representing the ability to create a `Compiler` below.
108///
109/// This is used in Wasmtime to separate compiler implementations, currently
110/// mostly used to separate Cranelift from Wasmtime itself.
111pub trait CompilerBuilder: Send + Sync + fmt::Debug {
112    /// Sets the target of compilation to the target specified.
113    fn target(&mut self, target: target_lexicon::Triple) -> Result<()>;
114
115    /// Enables clif output in the directory specified.
116    fn clif_dir(&mut self, _path: &path::Path) -> Result<()> {
117        bail!("clif output not supported");
118    }
119
120    /// Returns the currently configured target triple that compilation will
121    /// produce artifacts for.
122    fn triple(&self) -> &target_lexicon::Triple;
123
124    /// Compiler-specific method to configure various settings in the compiler
125    /// itself.
126    ///
127    /// This is expected to be defined per-compiler. Compilers should return
128    /// errors for unknown names/values.
129    fn set(&mut self, name: &str, val: &str) -> Result<()>;
130
131    /// Compiler-specific method for configuring settings.
132    ///
133    /// Same as [`CompilerBuilder::set`] except for enabling boolean flags.
134    /// Currently cranelift uses this to sometimes enable a family of settings.
135    fn enable(&mut self, name: &str) -> Result<()>;
136
137    /// Returns a list of all possible settings that can be configured with
138    /// [`CompilerBuilder::set`] and [`CompilerBuilder::enable`].
139    fn settings(&self) -> Vec<Setting>;
140
141    /// Enables Cranelift's incremental compilation cache, using the given `CacheStore`
142    /// implementation.
143    ///
144    /// This will return an error if the compiler does not support incremental compilation.
145    fn enable_incremental_compilation(&mut self, cache_store: Arc<dyn CacheStore>) -> Result<()>;
146
147    /// Set the tunables for this compiler.
148    fn set_tunables(&mut self, tunables: Tunables) -> Result<()>;
149
150    /// Get the tunables used by this compiler.
151    fn tunables(&self) -> Option<&Tunables>;
152
153    /// Builds a new [`Compiler`] object from this configuration.
154    fn build(&self) -> Result<Box<dyn Compiler>>;
155
156    /// Enables or disables wmemcheck during runtime according to the wmemcheck CLI flag.
157    fn wmemcheck(&mut self, _enable: bool) {}
158}
159
160/// Description of compiler settings returned by [`CompilerBuilder::settings`].
161#[derive(Clone, Copy, Debug)]
162pub struct Setting {
163    /// The name of the setting.
164    pub name: &'static str,
165    /// The description of the setting.
166    pub description: &'static str,
167    /// The kind of the setting.
168    pub kind: SettingKind,
169    /// The supported values of the setting (for enum values).
170    pub values: Option<&'static [&'static str]>,
171}
172
173/// Different kinds of [`Setting`] values that can be configured in a
174/// [`CompilerBuilder`]
175#[derive(Clone, Copy, Debug)]
176pub enum SettingKind {
177    /// The setting is an enumeration, meaning it's one of a set of values.
178    Enum,
179    /// The setting is a number.
180    Num,
181    /// The setting is a boolean.
182    Bool,
183    /// The setting is a preset.
184    Preset,
185}
186
187/// The result of compiling a single function body.
188pub struct CompiledFunctionBody {
189    /// The code. This is whatever type the `Compiler` implementation wants it
190    /// to be, we just shepherd it around.
191    pub code: Box<dyn Any + Send + Sync>,
192    /// Whether the compiled function needs a GC heap to run; that is, whether
193    /// it reads a struct field, allocates, an array, or etc...
194    pub needs_gc_heap: bool,
195}
196
197/// An implementation of a compiler which can compile WebAssembly functions to
198/// machine code and perform other miscellaneous tasks needed by the JIT runtime.
199///
200/// The diagram below depicts typical usage of this trait:
201///
202/// ```text
203///                     +------+
204///                     | Wasm |
205///                     +------+
206///                        |
207///                        |
208///           Compiler::compile_function()
209///                        |
210///                        |
211///                        V
212///             +----------------------+
213///             | CompiledFunctionBody |
214///             +----------------------+
215///               |                  |
216///               |                  |
217///               |                When
218///               |       Compiler::inlining_compiler()
219///               |               is some
220///               |                  |
221///             When                 |
222/// Compiler::inlining_compiler()    |-----------------.
223///             is none              |                 |
224///               |                  |                 |
225///               |           Optionally call          |
226///               |        InliningCompiler::inline()  |
227///               |                  |                 |
228///               |                  |                 |
229///               |                  |-----------------'
230///               |                  |
231///               |                  |
232///               |                  V
233///               |     InliningCompiler::finish_compiling()
234///               |                  |
235///               |                  |
236///               |------------------'
237///               |
238///               |
239///   Compiler::append_code()
240///               |
241///               |
242///               V
243///           +--------+
244///           | Object |
245///           +--------+
246/// ```
247pub trait Compiler: Send + Sync {
248    /// Get this compiler's inliner.
249    ///
250    /// Consumers of this trait **must** check for when when this method returns
251    /// `Some(_)`, and **must** call `InliningCompiler::finish_compiling` on all
252    /// `CompiledFunctionBody`s produced by this compiler in that case before
253    /// passing the the compiled functions to `Compiler::append_code`, even if
254    /// the consumer does not actually intend to do any inlining. This allows
255    /// implementations of the trait to only translate to an internal
256    /// representation in `Compiler::compile_*` methods so that they can then
257    /// perform inlining afterwards if the consumer desires, and then finally
258    /// proceed with compilng that internal representation to native code in
259    /// `InliningCompiler::finish_compiling`.
260    fn inlining_compiler(&self) -> Option<&dyn InliningCompiler>;
261
262    /// Compiles the function `index` within `translation`.
263    ///
264    /// The body of the function is available in `data` and configuration
265    /// values are also passed in via `tunables`. Type information in
266    /// `translation` is all relative to `types`.
267    ///
268    /// `component` is the component this module is being compiled as part of,
269    /// if any. Fused adapters need it to compute offsets within the
270    /// `VMComponentContext` they will run against.
271    fn compile_function(
272        &self,
273        translation: &ModuleTranslation<'_>,
274        key: FuncKey,
275        data: FunctionBodyData<'_>,
276        types: &ModuleTypesBuilder,
277        component: Option<EnclosingComponent<'_>>,
278        symbol: &str,
279    ) -> Result<CompiledFunctionBody, CompileError>;
280
281    /// Compile a trampoline for an array-call host function caller calling the
282    /// `index`th Wasm function.
283    ///
284    /// The trampoline should save the necessary state to record the
285    /// host-to-Wasm transition (e.g. registers used for fast stack walking).
286    fn compile_trampoline(
287        &self,
288        translation: Option<&ModuleTranslation<'_>>,
289        key: FuncKey,
290        types: &ModuleTypesBuilder,
291        symbol: &str,
292    ) -> Result<CompiledFunctionBody, CompileError>;
293
294    /// Returns the list of relocations required for a function from one of the
295    /// previous `compile_*` functions above.
296    fn compiled_function_relocation_targets<'a>(
297        &'a self,
298        func: &'a dyn Any,
299    ) -> Box<dyn Iterator<Item = FuncKey> + 'a>;
300
301    /// Appends a list of compiled functions to an in-memory object.
302    ///
303    /// This function will receive the same `Box<dyn Any>` produced as part of
304    /// compilation from functions like `compile_function`,
305    /// `compile_host_to_wasm_trampoline`, and other component-related shims.
306    /// Internally this will take all of these functions and add information to
307    /// the object such as:
308    ///
309    /// * Compiled code in a `.text` section
310    /// * Unwind information in Wasmtime-specific sections
311    /// * Relocations, if necessary, for the text section
312    ///
313    /// Each function is accompanied with its desired symbol name and the return
314    /// value of this function is the symbol for each function as well as where
315    /// each function was placed within the object.
316    ///
317    /// The `resolve_reloc` argument is intended to resolving relocations
318    /// between function, chiefly resolving intra-module calls within one core
319    /// wasm module. The closure here takes two arguments:
320    ///
321    /// 1. First, the index within `funcs` that is being resolved,
322    ///
323    /// 2. and next the `RelocationTarget` which is the relocation target to
324    ///    resolve.
325    ///
326    /// The return value is an index within `funcs` that the relocation points
327    /// to.
328    fn append_code(
329        &self,
330        obj: &mut Object<'static>,
331        funcs: &[(String, FuncKey, Box<dyn Any + Send + Sync>)],
332        resolve_reloc: &dyn Fn(usize, FuncKey) -> usize,
333    ) -> Result<Vec<(Option<SymbolId>, FunctionLoc)>>;
334
335    /// Creates a new `Object` file which is used to build the results of a
336    /// compilation into.
337    ///
338    /// The returned object file will have an appropriate
339    /// architecture/endianness for `self.triple()`, but at this time it is
340    /// always an ELF file, regardless of target platform.
341    fn object(&self, kind: ObjectKind) -> Result<Object<'static>> {
342        use target_lexicon::Architecture::*;
343
344        let triple = self.triple();
345        let (arch, flags) = match triple.architecture {
346            X86_32(_) => (Architecture::I386, object::elf::FileFlags(0)),
347            X86_64 => (Architecture::X86_64, object::elf::FileFlags(0)),
348            Arm(_) => (Architecture::Arm, object::elf::FileFlags(0)),
349            Aarch64(_) => (Architecture::Aarch64, object::elf::FileFlags(0)),
350            S390x => (Architecture::S390x, object::elf::FileFlags(0)),
351            Riscv64(_) => (Architecture::Riscv64, object::elf::FileFlags(0)),
352            // XXX: the `object` crate won't successfully build an object
353            // with relocations and such if it doesn't know the
354            // architecture, so just pretend we are riscv64. Yolo!
355            //
356            // Also note that we add some flags to `e_flags` in the object file
357            // to indicate that it's pulley, not actually riscv64. This is used
358            // by `wasmtime objdump` for example.
359            Pulley32 | Pulley32be => (Architecture::Riscv64, obj::EF_WASMTIME_PULLEY32),
360            Pulley64 | Pulley64be => (Architecture::Riscv64, obj::EF_WASMTIME_PULLEY64),
361            architecture => {
362                bail!("target architecture {architecture:?} is unsupported");
363            }
364        };
365        let mut obj = Object::new(
366            BinaryFormat::Elf,
367            arch,
368            match triple.endianness().unwrap() {
369                target_lexicon::Endianness::Little => object::Endianness::Little,
370                target_lexicon::Endianness::Big => object::Endianness::Big,
371            },
372        );
373        obj.flags = FileFlags::Elf {
374            os_abi: obj::ELFOSABI_WASMTIME,
375            e_flags: flags
376                | match kind {
377                    ObjectKind::Module => obj::EF_WASMTIME_MODULE,
378                    ObjectKind::Component => obj::EF_WASMTIME_COMPONENT,
379                },
380            abi_version: 0,
381        };
382        Ok(obj)
383    }
384
385    /// Returns the target triple that this compiler is compiling for.
386    fn triple(&self) -> &target_lexicon::Triple;
387
388    /// Returns the alignment necessary to align values to the page size of the
389    /// compilation target. Note that this may be an upper-bound where the
390    /// alignment is larger than necessary for some platforms since it may
391    /// depend on the platform's runtime configuration.
392    fn page_size_align(&self) -> u64 {
393        // Conservatively assume the max-of-all-supported-hosts for pulley
394        // and round up to 64k.
395        if self.triple().is_pulley() {
396            return 0x10000;
397        }
398
399        use target_lexicon::*;
400        match (self.triple().operating_system, self.triple().architecture) {
401            (
402                OperatingSystem::MacOSX { .. }
403                | OperatingSystem::Darwin(_)
404                | OperatingSystem::IOS(_)
405                | OperatingSystem::TvOS(_),
406                Architecture::Aarch64(..),
407            ) => 0x4000,
408            // According to
409            // https://devblogs.microsoft.com/oldnewthing/20210510-00/?p=105200
410            // it seems like windows always use a 4k page size.
411            (OperatingSystem::Windows, Architecture::Aarch64(..)) => 0x1000,
412            // 64 KB is the maximal page size (i.e. memory translation granule size)
413            // supported by the architecture and is used on some platforms.
414            (_, Architecture::Aarch64(..)) => 0x10000,
415            _ => 0x1000,
416        }
417    }
418
419    /// Returns a list of configured settings for this compiler.
420    fn flags(&self) -> Vec<(&'static str, FlagValue<'static>)>;
421
422    /// Same as [`Compiler::flags`], but ISA-specific (a cranelift-ism)
423    fn isa_flags(&self) -> Vec<(&'static str, FlagValue<'static>)>;
424
425    /// Get a flag indicating whether branch protection is enabled.
426    fn is_branch_protection_enabled(&self) -> bool;
427
428    /// Returns whether this compiler can compile the WebAssembly `v128` type
429    /// for its target.
430    fn supports_wasm_simd(&self) -> bool {
431        true
432    }
433
434    /// Returns a suitable compiler usable for component-related compilations.
435    ///
436    /// Note that the `ComponentCompiler` trait can also be implemented for
437    /// `Self` in which case this function would simply return `self`.
438    #[cfg(feature = "component-model")]
439    fn component_compiler(&self) -> &dyn crate::component::ComponentCompiler;
440
441    /// Appends generated DWARF sections to the `obj` specified.
442    ///
443    /// The `translations` track all compiled functions and `get_func` can be
444    /// used to acquire the metadata for a particular function within a module.
445    fn append_dwarf<'a>(
446        &self,
447        obj: &mut Object<'_>,
448        translations: &'a PrimaryMap<StaticModuleIndex, ModuleTranslation<'a>>,
449        get_func: &'a dyn Fn(
450            StaticModuleIndex,
451            DefinedFuncIndex,
452        ) -> (Option<SymbolId>, &'a (dyn Any + Send + Sync)),
453        dwarf_package_bytes: Option<&'a [u8]>,
454        tunables: &'a Tunables,
455    ) -> Result<()>;
456
457    /// Creates a new System V Common Information Entry for the ISA.
458    ///
459    /// Returns `None` if the ISA does not support System V unwind information.
460    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
461        // By default, an ISA cannot create a System V CIE.
462        None
463    }
464
465    /// Invoked at the end of a module or component compilation and signals
466    /// that any transient caches across functions can now be dropped.
467    fn release_caches(&self);
468}
469
470/// Information about a call site, for use in inlining heuristics.
471#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
472pub struct CallSite {
473    /// Whether this call site is in cold code (e.g. a block that has been
474    /// hinted as unlikely to execute).
475    pub is_cold: bool,
476}
477
478/// An inlining compiler.
479pub trait InliningCompiler: Sync + Send {
480    /// Enumerate the function calls that the given `func` makes.
481    fn calls(&self, func: &CompiledFunctionBody, calls: &mut IndexSet<FuncKey>) -> Result<()>;
482
483    /// Get the abstract size of the given function, for the purposes of
484    /// inlining heuristics.
485    fn size(&self, func: &CompiledFunctionBody) -> u32;
486
487    /// Process this function for inlining.
488    ///
489    /// Implementations should call `get_callee` for each of their direct
490    /// function call sites, passing the callee and information about the call
491    /// site, and if `get_callee` returns `Some(_)`, they should inline the
492    /// given function body into that call site.
493    fn inline<'a>(
494        &self,
495        func: &mut CompiledFunctionBody,
496        get_callee: &'a mut dyn FnMut(FuncKey, CallSite) -> Option<&'a CompiledFunctionBody>,
497    ) -> Result<()>;
498
499    /// Finish compiling the given function.
500    ///
501    /// This method **must** be called before passing the
502    /// `CompiledFunctionBody`'s contents to `Compiler::append_code`, even if no
503    /// inlining was performed.
504    fn finish_compiling(
505        &self,
506        func: &mut CompiledFunctionBody,
507        input: Option<wasmparser::FunctionBody<'_>>,
508        symbol: &str,
509    ) -> Result<()>;
510}