Skip to main content

wasmtime/engine/
serialization.rs

1//! This module implements serialization and deserialization of `Engine`
2//! configuration data which is embedded into compiled artifacts of Wasmtime.
3//!
4//! The data serialized here is used to double-check that when a module is
5//! loaded from one host onto another that it's compatible with the target host.
6//! Additionally though this data is the first data read from a precompiled
7//! artifact so it's "extra hardened" to provide reasonable-ish error messages
8//! for mismatching wasmtime versions. Once something successfully deserializes
9//! here it's assumed it's meant for this wasmtime so error messages are in
10//! general much worse afterwards.
11//!
12//! Wasmtime AOT artifacts are ELF files so the data for the engine here is
13//! stored into a section of the output file. The structure of this section is:
14//!
15//! 1. A version byte, currently `VERSION`.
16//! 2. A byte indicating how long the next field is.
17//! 3. A version string of the length of the previous byte value.
18//! 4. A `postcard`-encoded `Metadata` structure.
19//!
20//! This is hoped to help distinguish easily Wasmtime-based ELF files from
21//! other random ELF files, as well as provide better error messages for
22//! using wasmtime artifacts across versions.
23
24use crate::prelude::*;
25use crate::{Engine, ModuleVersionStrategy, Precompiled};
26use core::fmt;
27use core::str::FromStr;
28use object::endian::Endianness;
29#[cfg(any(feature = "cranelift", feature = "winch"))]
30use object::write::{Object, StandardSegment};
31use object::{
32    FileFlags, Object as _,
33    elf::FileHeader64,
34    read::elf::{ElfFile64, FileHeader, SectionHeader},
35};
36use serde_derive::{Deserialize, Serialize};
37use wasmtime_environ::{FlagValue, ObjectKind, OperatorCostStrategy, Tunables, obj};
38
39const VERSION: u8 = 0;
40
41/// Verifies that the serialized engine in `mmap` is compatible with the
42/// `engine` provided.
43///
44/// This function will verify that the `mmap` provided can be deserialized
45/// successfully and that the contents are all compatible with the `engine`
46/// provided here, notably compatible wasm features are enabled, compatible
47/// compiler options, etc. If a mismatch is found and the compilation metadata
48/// specified is incompatible then an error is returned.
49pub fn check_compatible(engine: &Engine, mmap: &[u8], expected: ObjectKind) -> Result<()> {
50    // Parse the input `mmap` as an ELF file and see if the header matches the
51    // Wasmtime-generated header. This includes a Wasmtime-specific `os_abi` and
52    // the `e_flags` field should indicate whether `expected` matches or not.
53    //
54    // Note that errors generated here could mean that a precompiled module was
55    // loaded as a component, or vice versa, both of which aren't supposed to
56    // work.
57    //
58    // Ideally we'd only `File::parse` once and avoid the linear
59    // `section_by_name` search here but the general serialization code isn't
60    // structured well enough to make this easy and additionally it's not really
61    // a perf issue right now so doing that is left for another day's
62    // refactoring.
63    let header = FileHeader64::<Endianness>::parse(mmap)
64        .map_err(obj::ObjectCrateErrorWrapper)
65        .context("failed to parse precompiled artifact as an ELF")?;
66    let endian = header
67        .endian()
68        .context("failed to parse header endianness")?;
69
70    let expected_e_flags = match expected {
71        ObjectKind::Module => obj::EF_WASMTIME_MODULE,
72        ObjectKind::Component => obj::EF_WASMTIME_COMPONENT,
73    };
74    ensure!(
75        header.e_flags(endian).contains(expected_e_flags),
76        "incompatible object file format"
77    );
78
79    let section_headers = header
80        .section_headers(endian, mmap)
81        .context("failed to parse section headers")?;
82    let strings = header
83        .section_strings(endian, mmap, section_headers)
84        .context("failed to parse strings table")?;
85    let sections = header
86        .sections(endian, mmap)
87        .context("failed to parse sections table")?;
88
89    let mut section_header = None;
90    for s in sections.iter() {
91        let name = s.name(endian, strings)?;
92        if name == obj::ELF_WASM_ENGINE.as_bytes() {
93            section_header = Some(s);
94        }
95    }
96    let Some(section_header) = section_header else {
97        bail!("failed to find section `{}`", obj::ELF_WASM_ENGINE)
98    };
99    let data = section_header
100        .data(endian, mmap)
101        .map_err(obj::ObjectCrateErrorWrapper)?;
102    let (first, data) = data
103        .split_first()
104        .ok_or_else(|| format_err!("invalid engine section"))?;
105    if *first != VERSION {
106        bail!("mismatched version in engine section");
107    }
108    let (len, data) = data
109        .split_first()
110        .ok_or_else(|| format_err!("invalid engine section"))?;
111    let len = usize::from(*len);
112    let (version, data) = if data.len() < len + 1 {
113        bail!("engine section too small")
114    } else {
115        data.split_at(len)
116    };
117
118    match &engine.config().module_version {
119        ModuleVersionStrategy::None => { /* ignore the version info, accept all */ }
120        _ => {
121            let version = core::str::from_utf8(&version)?;
122            if version != engine.config().module_version.as_str() {
123                bail!("Module was compiled with incompatible version '{version}'");
124            }
125        }
126    }
127    postcard::from_bytes::<Metadata<'_>>(data)?.check_compatible(engine)
128}
129
130#[cfg(any(feature = "cranelift", feature = "winch"))]
131pub fn append_compiler_info(engine: &Engine, obj: &mut Object<'_>, metadata: &Metadata<'_>) {
132    let section = obj.add_section(
133        obj.segment_name(StandardSegment::Data).to_vec(),
134        obj::ELF_WASM_ENGINE.as_bytes().to_vec(),
135        object::SectionKind::ReadOnlyData,
136    );
137    let mut data = Vec::new();
138    data.push(VERSION);
139    let version = engine.config().module_version.as_str();
140    // This precondition is checked in Config::module_version:
141    assert!(
142        version.len() < 256,
143        "package version must be less than 256 bytes"
144    );
145    data.push(version.len() as u8);
146    data.extend_from_slice(version.as_bytes());
147    data.extend(postcard::to_allocvec(metadata).unwrap());
148    obj.set_section_data(section, data, 1);
149}
150
151fn detect_precompiled<'data, R: object::ReadRef<'data>>(
152    obj: ElfFile64<'data, Endianness, R>,
153) -> Option<Precompiled> {
154    match obj.flags() {
155        FileFlags::Elf {
156            os_abi: obj::ELFOSABI_WASMTIME,
157            abi_version: 0,
158            e_flags,
159        } if e_flags.contains(obj::EF_WASMTIME_MODULE) => Some(Precompiled::Module),
160        FileFlags::Elf {
161            os_abi: obj::ELFOSABI_WASMTIME,
162            abi_version: 0,
163            e_flags,
164        } if e_flags.contains(obj::EF_WASMTIME_COMPONENT) => Some(Precompiled::Component),
165        _ => None,
166    }
167}
168
169pub fn detect_precompiled_bytes(bytes: &[u8]) -> Option<Precompiled> {
170    detect_precompiled(ElfFile64::parse(bytes).ok()?)
171}
172
173#[cfg(feature = "std")]
174pub fn detect_precompiled_file(path: impl AsRef<std::path::Path>) -> Result<Option<Precompiled>> {
175    let read_cache = object::ReadCache::new(std::fs::File::open(path)?);
176    let obj = ElfFile64::parse(&read_cache)?;
177    Ok(detect_precompiled(obj))
178}
179
180#[derive(Serialize, Deserialize)]
181pub struct Metadata<'a> {
182    target: TryString,
183    #[serde(borrow)]
184    shared_flags: TryVec<(&'a str, FlagValue<'a>)>,
185    #[serde(borrow)]
186    isa_flags: TryVec<(&'a str, FlagValue<'a>)>,
187    tunables: Tunables,
188    features: u64,
189}
190
191impl Metadata<'_> {
192    #[cfg(any(feature = "cranelift", feature = "winch"))]
193    pub fn new(engine: &Engine) -> Result<Metadata<'static>> {
194        let compiler = engine.try_compiler()?;
195        Ok(Metadata {
196            target: compiler.triple().to_string().into(),
197            shared_flags: compiler.flags().into(),
198            isa_flags: compiler.isa_flags().into(),
199            tunables: engine.tunables().clone(),
200            features: engine.features().bits(),
201        })
202    }
203
204    fn check_compatible(mut self, engine: &Engine) -> Result<()> {
205        self.check_triple(engine)?;
206        self.check_shared_flags(engine)?;
207        self.check_isa_flags(engine)?;
208        self.check_tunables(&engine.tunables())?;
209        self.check_features(&engine.features())?;
210        Ok(())
211    }
212
213    fn check_triple(&self, engine: &Engine) -> Result<()> {
214        let engine_target = engine.target();
215        let module_target =
216            target_lexicon::Triple::from_str(&self.target).map_err(|e| format_err!(e))?;
217
218        if module_target.architecture != engine_target.architecture {
219            bail!(
220                "Module was compiled for architecture '{}'",
221                module_target.architecture
222            );
223        }
224
225        if module_target.operating_system != engine_target.operating_system {
226            bail!(
227                "Module was compiled for operating system '{}'",
228                module_target.operating_system
229            );
230        }
231
232        Ok(())
233    }
234
235    fn check_shared_flags(&mut self, engine: &Engine) -> Result<()> {
236        for (name, val) in self.shared_flags.iter() {
237            engine
238                .check_compatible_with_shared_flag(name, val)
239                .map_err(|s| crate::Error::msg(s))
240                .context("compilation settings of module incompatible with native host")?;
241        }
242        Ok(())
243    }
244
245    fn check_isa_flags(&mut self, engine: &Engine) -> Result<()> {
246        for (name, val) in self.isa_flags.iter() {
247            engine
248                .check_compatible_with_isa_flag(name, val)
249                .map_err(|s| crate::Error::msg(s))
250                .context("compilation settings of module incompatible with native host")?;
251        }
252        Ok(())
253    }
254
255    fn check_int<T: Eq + fmt::Display>(found: T, expected: T, feature: &str) -> Result<()> {
256        if found == expected {
257            return Ok(());
258        }
259
260        bail!(
261            "Module was compiled with a {feature} of '{found}' but '{expected}' is expected for the host"
262        );
263    }
264
265    fn check_bool(found: bool, expected: bool, feature: impl fmt::Display) -> Result<()> {
266        if found == expected {
267            return Ok(());
268        }
269
270        bail!(
271            "Module was compiled {} {} but it {} enabled for the host",
272            if found { "with" } else { "without" },
273            feature,
274            if expected { "is" } else { "is not" }
275        );
276    }
277
278    fn check_cost(
279        consume_fuel: bool,
280        found: &OperatorCostStrategy,
281        expected: &OperatorCostStrategy,
282    ) -> Result<()> {
283        if !consume_fuel {
284            return Ok(());
285        }
286
287        if found != expected {
288            bail!("Module costs are incompatible");
289        }
290
291        Ok(())
292    }
293
294    fn check_tunables(&mut self, other: &Tunables) -> Result<()> {
295        let Tunables {
296            collector,
297            memory_reservation,
298            memory_guard_size,
299            debug_native,
300            debug_guest,
301            debug_symbols,
302            parse_wasm_debuginfo,
303            consume_fuel,
304            ref operator_cost,
305            epoch_interruption,
306            memory_may_move,
307            guard_before_linear_memory,
308            table_lazy_init,
309            relaxed_simd_deterministic,
310            winch_callable,
311            signals_based_traps,
312            memory_init_cow,
313            inlining,
314            inlining_small_callee_size,
315            inlining_sum_size_threshold,
316            concurrency_support,
317            recording,
318            asan_stack_switching,
319
320            // This doesn't affect compilation, it's just a runtime setting.
321            memory_reservation_for_growth: _,
322
323            // This does technically affect compilation but modules with/without
324            // trap information can be loaded into engines with the opposite
325            // setting just fine (it's just a section in the compiled file and
326            // whether it's present or not)
327            generate_address_map: _,
328
329            // Just a debugging aid, doesn't affect functionality at all.
330            debug_adapter_modules: _,
331
332            // This is a runtime GC debugging setting, doesn't affect compilation.
333            gc_zeal_alloc_counter: _,
334
335            gc_heap_reservation,
336            gc_heap_guard_size,
337            gc_heap_may_move,
338            gc_heap_initial_size,
339
340            // This doesn't affect compilation, it's just a runtime setting.
341            gc_heap_reservation_for_growth: _,
342
343            // No need to match whether or not this metadata is emitted, if it
344            // is or isn't then that's fine, the runtime handles it the same
345            // way.
346            metadata_for_internal_asserts: _,
347            metadata_for_gc_heap_corruption: _,
348
349            // Only affects cold-block layout; a compiled artifact loads into an
350            // engine configured either way.
351            branch_hinting: _,
352        } = self.tunables;
353
354        Self::check_collector(collector, other.collector)?;
355        Self::check_int(
356            memory_reservation,
357            other.memory_reservation,
358            "memory reservation",
359        )?;
360        Self::check_int(
361            memory_guard_size,
362            other.memory_guard_size,
363            "memory guard size",
364        )?;
365        Self::check_bool(
366            debug_native,
367            other.debug_native,
368            "native debug information support",
369        )?;
370        Self::check_bool(debug_guest, other.debug_guest, "guest debug")?;
371        Self::check_bool(debug_symbols, other.debug_symbols, "debug symbols")?;
372        Self::check_bool(
373            parse_wasm_debuginfo,
374            other.parse_wasm_debuginfo,
375            "WebAssembly backtrace support",
376        )?;
377        Self::check_bool(consume_fuel, other.consume_fuel, "fuel support")?;
378        Self::check_cost(consume_fuel, operator_cost, &other.operator_cost)?;
379        Self::check_bool(
380            epoch_interruption,
381            other.epoch_interruption,
382            "epoch interruption",
383        )?;
384        Self::check_bool(memory_may_move, other.memory_may_move, "memory may move")?;
385        Self::check_bool(
386            guard_before_linear_memory,
387            other.guard_before_linear_memory,
388            "guard before linear memory",
389        )?;
390        Self::check_bool(table_lazy_init, other.table_lazy_init, "table lazy init")?;
391        Self::check_bool(
392            relaxed_simd_deterministic,
393            other.relaxed_simd_deterministic,
394            "relaxed simd deterministic semantics",
395        )?;
396        Self::check_bool(
397            winch_callable,
398            other.winch_callable,
399            "Winch calling convention",
400        )?;
401        Self::check_bool(
402            signals_based_traps,
403            other.signals_based_traps,
404            "Signals-based traps",
405        )?;
406        Self::check_bool(
407            memory_init_cow,
408            other.memory_init_cow,
409            "memory initialization with CoW",
410        )?;
411        Self::check_int(
412            inlining_small_callee_size,
413            other.inlining_small_callee_size,
414            "function inlining small-callee size",
415        )?;
416        Self::check_int(
417            inlining_sum_size_threshold,
418            other.inlining_sum_size_threshold,
419            "function inlining sum-size threshold",
420        )?;
421        Self::check_bool(
422            concurrency_support,
423            other.concurrency_support,
424            "concurrency support",
425        )?;
426        Self::check_bool(recording, other.recording, "RR recording support")?;
427        Self::check_bool(
428            asan_stack_switching,
429            other.asan_stack_switching,
430            "AddressSanitizer stack-switching support",
431        )?;
432        Self::check_inlining(inlining, other.inlining)?;
433        Self::check_int(
434            gc_heap_reservation,
435            other.gc_heap_reservation,
436            "GC heap reservation",
437        )?;
438        Self::check_int(
439            gc_heap_guard_size,
440            other.gc_heap_guard_size,
441            "GC heap guard size",
442        )?;
443        Self::check_int(
444            gc_heap_initial_size,
445            other.gc_heap_initial_size,
446            "GC heap initial size",
447        )?;
448        Self::check_bool(gc_heap_may_move, other.gc_heap_may_move, "GC heap may move")?;
449
450        Ok(())
451    }
452
453    fn check_features(&mut self, other: &wasmparser::WasmFeatures) -> Result<()> {
454        let module_features = wasmparser::WasmFeatures::from_bits_truncate(self.features);
455        let missing_features = (*other & module_features) ^ module_features;
456        for (name, _) in missing_features.iter_names() {
457            let name = name.to_ascii_lowercase();
458            bail!(
459                "Module was compiled with support for WebAssembly feature \
460                `{name}` but it is not enabled for the host",
461            );
462        }
463        Ok(())
464    }
465
466    fn check_collector(
467        module: Option<wasmtime_environ::Collector>,
468        host: Option<wasmtime_environ::Collector>,
469    ) -> Result<()> {
470        match (module, host) {
471            // If the module doesn't require GC support it doesn't matter
472            // whether the host has GC support enabled or not.
473            (None, _) => Ok(()),
474            (Some(module), Some(host)) if module == host => Ok(()),
475
476            (Some(_), None) => {
477                bail!("module was compiled with GC however GC is disabled in the host")
478            }
479
480            (Some(module), Some(host)) => {
481                bail!(
482                    "module was compiled for the {module} collector but \
483                     the host is configured to use the {host} collector",
484                )
485            }
486        }
487    }
488
489    fn check_inlining(
490        module: wasmtime_environ::Inlining,
491        host: wasmtime_environ::Inlining,
492    ) -> Result<()> {
493        if module == host {
494            return Ok(());
495        }
496
497        let desc = |cfg| match cfg {
498            wasmtime_environ::Inlining::No => "without intra-module inlining",
499            wasmtime_environ::Inlining::Yes => "with intra-module inlining",
500            wasmtime_environ::Inlining::InterModuleAndIntraGc => {
501                "with intra-module inlining only when using GC"
502            }
503            wasmtime_environ::Inlining::Intrinsics => "with intrinsic inlining",
504            wasmtime_environ::Inlining::InterModule => "with inter-module inlining",
505        };
506
507        let module = desc(module);
508        let host = desc(host);
509
510        bail!("module was compiled {module} however the host is configured {host}")
511    }
512}
513
514#[cfg(test)]
515mod test {
516    use super::*;
517    use crate::{Cache, Config, Module, OptLevel};
518    use std::{
519        collections::hash_map::DefaultHasher,
520        hash::{Hash, Hasher},
521    };
522    use tempfile::TempDir;
523
524    #[test]
525    fn test_architecture_mismatch() -> Result<()> {
526        let engine = Engine::default();
527        let mut metadata = Metadata::new(&engine)?;
528        metadata.target = "unknown-generic-linux".to_string().into();
529
530        match metadata.check_compatible(&engine) {
531            Ok(_) => unreachable!(),
532            Err(e) => assert_eq!(
533                e.to_string(),
534                "Module was compiled for architecture 'unknown'",
535            ),
536        }
537
538        Ok(())
539    }
540
541    // Note that this test runs on a platform that is known to use Cranelift
542    #[test]
543    #[cfg(all(target_arch = "x86_64", not(miri)))]
544    fn test_os_mismatch() -> Result<()> {
545        let engine = Engine::default();
546        let mut metadata = Metadata::new(&engine)?;
547
548        metadata.target = format!(
549            "{}-generic-unknown",
550            target_lexicon::Triple::host().architecture
551        )
552        .into();
553
554        match metadata.check_compatible(&engine) {
555            Ok(_) => unreachable!(),
556            Err(e) => assert_eq!(
557                e.to_string(),
558                "Module was compiled for operating system 'unknown'",
559            ),
560        }
561
562        Ok(())
563    }
564
565    fn assert_contains(error: &Error, msg: &str) {
566        let msg = msg.trim();
567        if error.chain().any(|e| e.to_string().contains(msg)) {
568            return;
569        }
570
571        panic!("failed to find:\n\n'''{msg}\n'''\n\nwithin error message:\n\n'''{error:?}'''")
572    }
573
574    #[test]
575    fn test_cranelift_flags_mismatch() -> Result<()> {
576        let engine = Engine::default();
577        let mut metadata = Metadata::new(&engine)?;
578
579        metadata
580            .shared_flags
581            .push(("preserve_frame_pointers", FlagValue::Bool(false)))?;
582
583        match metadata.check_compatible(&engine) {
584            Ok(_) => unreachable!(),
585            Err(e) => {
586                assert_contains(
587                    &e,
588                    "compilation settings of module incompatible with native host",
589                );
590                assert_contains(
591                    &e,
592                    "setting \"preserve_frame_pointers\" is configured to Bool(false) which is not supported",
593                );
594            }
595        }
596
597        Ok(())
598    }
599
600    #[test]
601    fn test_isa_flags_mismatch() -> Result<()> {
602        let engine = Engine::default();
603        let mut metadata = Metadata::new(&engine)?;
604
605        metadata
606            .isa_flags
607            .push(("not_a_flag", FlagValue::Bool(true)))?;
608
609        match metadata.check_compatible(&engine) {
610            Ok(_) => unreachable!(),
611            Err(e) => {
612                assert_contains(
613                    &e,
614                    "compilation settings of module incompatible with native host",
615                );
616                assert_contains(
617                    &e,
618                    "don't know how to test for target-specific flag \"not_a_flag\" at runtime",
619                );
620            }
621        }
622
623        Ok(())
624    }
625
626    #[test]
627    #[cfg_attr(any(miri, not(has_native_signals)), ignore)]
628    #[cfg(target_pointer_width = "64")] // different defaults on 32-bit platforms
629    fn test_tunables_int_mismatch() -> Result<()> {
630        let engine = Engine::default();
631        let mut metadata = Metadata::new(&engine)?;
632
633        metadata.tunables.memory_guard_size = 0;
634
635        match metadata.check_compatible(&engine) {
636            Ok(_) => unreachable!(),
637            Err(e) => assert_eq!(
638                e.to_string(),
639                "Module was compiled with a memory guard size of '0' but '33554432' is expected for the host"
640            ),
641        }
642
643        Ok(())
644    }
645
646    #[test]
647    fn test_tunables_bool_mismatch() -> Result<()> {
648        let mut config = Config::new();
649        config.epoch_interruption(true);
650
651        let engine = Engine::new(&config)?;
652        let mut metadata = Metadata::new(&engine)?;
653        metadata.tunables.epoch_interruption = false;
654
655        match metadata.check_compatible(&engine) {
656            Ok(_) => unreachable!(),
657            Err(e) => assert_eq!(
658                e.to_string(),
659                "Module was compiled without epoch interruption but it is enabled for the host"
660            ),
661        }
662
663        let mut config = Config::new();
664        config.epoch_interruption(false);
665
666        let engine = Engine::new(&config)?;
667        let mut metadata = Metadata::new(&engine)?;
668        metadata.tunables.epoch_interruption = true;
669
670        match metadata.check_compatible(&engine) {
671            Ok(_) => unreachable!(),
672            Err(e) => assert_eq!(
673                e.to_string(),
674                "Module was compiled with epoch interruption but it is not enabled for the host"
675            ),
676        }
677
678        Ok(())
679    }
680
681    /// This test is only run a platform that is known to implement threads
682    #[test]
683    #[cfg(all(target_arch = "x86_64", not(miri)))]
684    fn test_feature_mismatch() -> Result<()> {
685        let mut config = Config::new();
686        config.wasm_threads(true);
687
688        let engine = Engine::new(&config)?;
689        let mut metadata = Metadata::new(&engine)?;
690        metadata.features &= !wasmparser::WasmFeatures::THREADS.bits();
691
692        // If a feature is disabled in the module and enabled in the host,
693        // that's always ok.
694        metadata.check_compatible(&engine)?;
695
696        let mut config = Config::new();
697        config.wasm_threads(false);
698
699        let engine = Engine::new(&config)?;
700        let mut metadata = Metadata::new(&engine)?;
701        metadata.features |= wasmparser::WasmFeatures::THREADS.bits();
702
703        match metadata.check_compatible(&engine) {
704            Ok(_) => unreachable!(),
705            Err(e) => assert_eq!(
706                e.to_string(),
707                "Module was compiled with support for WebAssembly feature \
708                `threads` but it is not enabled for the host"
709            ),
710        }
711
712        Ok(())
713    }
714
715    #[test]
716    fn engine_weak_upgrades() {
717        let engine = Engine::default();
718        let weak = engine.weak();
719        weak.upgrade()
720            .expect("engine is still alive, so weak reference can upgrade");
721        drop(engine);
722        assert!(
723            weak.upgrade().is_none(),
724            "engine was dropped, so weak reference cannot upgrade"
725        );
726    }
727
728    #[test]
729    #[cfg_attr(miri, ignore)]
730    fn cache_accounts_for_opt_level() -> Result<()> {
731        let _ = env_logger::try_init();
732
733        let td = TempDir::new()?;
734        let config_path = td.path().join("config.toml");
735        std::fs::write(
736            &config_path,
737            &format!(
738                "
739                    [cache]
740                    directory = '{}'
741                ",
742                td.path().join("cache").display()
743            ),
744        )?;
745        let mut cfg = Config::new();
746        cfg.cranelift_opt_level(OptLevel::None)
747            .cache(Some(Cache::from_file(Some(&config_path))?));
748        let engine = Engine::new(&cfg)?;
749        Module::new(&engine, "(module (func))")?;
750        let cache_config = engine
751            .config()
752            .cache
753            .as_ref()
754            .expect("Missing cache config");
755        assert_eq!(cache_config.cache_hits(), 0);
756        assert_eq!(cache_config.cache_misses(), 1);
757        Module::new(&engine, "(module (func))")?;
758        assert_eq!(cache_config.cache_hits(), 1);
759        assert_eq!(cache_config.cache_misses(), 1);
760
761        let mut cfg = Config::new();
762        cfg.cranelift_opt_level(OptLevel::Speed)
763            .cache(Some(Cache::from_file(Some(&config_path))?));
764        let engine = Engine::new(&cfg)?;
765        let cache_config = engine
766            .config()
767            .cache
768            .as_ref()
769            .expect("Missing cache config");
770        Module::new(&engine, "(module (func))")?;
771        assert_eq!(cache_config.cache_hits(), 0);
772        assert_eq!(cache_config.cache_misses(), 1);
773        Module::new(&engine, "(module (func))")?;
774        assert_eq!(cache_config.cache_hits(), 1);
775        assert_eq!(cache_config.cache_misses(), 1);
776
777        let mut cfg = Config::new();
778        cfg.cranelift_opt_level(OptLevel::SpeedAndSize)
779            .cache(Some(Cache::from_file(Some(&config_path))?));
780        let engine = Engine::new(&cfg)?;
781        let cache_config = engine
782            .config()
783            .cache
784            .as_ref()
785            .expect("Missing cache config");
786        Module::new(&engine, "(module (func))")?;
787        assert_eq!(cache_config.cache_hits(), 0);
788        assert_eq!(cache_config.cache_misses(), 1);
789        Module::new(&engine, "(module (func))")?;
790        assert_eq!(cache_config.cache_hits(), 1);
791        assert_eq!(cache_config.cache_misses(), 1);
792
793        let mut cfg = Config::new();
794        cfg.debug_info(true)
795            .cache(Some(Cache::from_file(Some(&config_path))?));
796        let engine = Engine::new(&cfg)?;
797        let cache_config = engine
798            .config()
799            .cache
800            .as_ref()
801            .expect("Missing cache config");
802        Module::new(&engine, "(module (func))")?;
803        assert_eq!(cache_config.cache_hits(), 0);
804        assert_eq!(cache_config.cache_misses(), 1);
805        Module::new(&engine, "(module (func))")?;
806        assert_eq!(cache_config.cache_hits(), 1);
807        assert_eq!(cache_config.cache_misses(), 1);
808
809        Ok(())
810    }
811
812    #[test]
813    fn precompile_compatibility_key_accounts_for_opt_level() {
814        fn hash_for_config(cfg: &Config) -> u64 {
815            let engine = Engine::new(cfg).expect("Config should be valid");
816            let mut hasher = DefaultHasher::new();
817            engine.precompile_compatibility_hash().hash(&mut hasher);
818            hasher.finish()
819        }
820        let mut cfg = Config::new();
821        cfg.cranelift_opt_level(OptLevel::None);
822        let opt_none_hash = hash_for_config(&cfg);
823        cfg.cranelift_opt_level(OptLevel::Speed);
824        let opt_speed_hash = hash_for_config(&cfg);
825        assert_ne!(opt_none_hash, opt_speed_hash)
826    }
827
828    #[test]
829    fn precompile_compatibility_key_accounts_for_module_version_strategy() -> Result<()> {
830        fn hash_for_config(cfg: &Config) -> u64 {
831            let engine = Engine::new(cfg).expect("Config should be valid");
832            let mut hasher = DefaultHasher::new();
833            engine.precompile_compatibility_hash().hash(&mut hasher);
834            hasher.finish()
835        }
836        let mut cfg_custom_version = Config::new();
837        cfg_custom_version.module_version(ModuleVersionStrategy::Custom("1.0.1111".to_string()))?;
838        let custom_version_hash = hash_for_config(&cfg_custom_version);
839
840        let mut cfg_default_version = Config::new();
841        cfg_default_version.module_version(ModuleVersionStrategy::WasmtimeVersion)?;
842        let default_version_hash = hash_for_config(&cfg_default_version);
843
844        let mut cfg_none_version = Config::new();
845        cfg_none_version.module_version(ModuleVersionStrategy::None)?;
846        let none_version_hash = hash_for_config(&cfg_none_version);
847
848        assert_ne!(custom_version_hash, default_version_hash);
849        assert_ne!(custom_version_hash, none_version_hash);
850        assert_ne!(default_version_hash, none_version_hash);
851
852        Ok(())
853    }
854
855    #[test]
856    #[cfg_attr(miri, ignore)]
857    #[cfg(feature = "component-model")]
858    fn components_are_cached() -> Result<()> {
859        use crate::component::Component;
860
861        let td = TempDir::new()?;
862        let config_path = td.path().join("config.toml");
863        std::fs::write(
864            &config_path,
865            &format!(
866                "
867                    [cache]
868                    directory = '{}'
869                ",
870                td.path().join("cache").display()
871            ),
872        )?;
873        let mut cfg = Config::new();
874        cfg.cache(Some(Cache::from_file(Some(&config_path))?));
875        let engine = Engine::new(&cfg)?;
876        let cache_config = engine
877            .config()
878            .cache
879            .as_ref()
880            .expect("Missing cache config");
881        Component::new(&engine, "(component (core module (func)))")?;
882        assert_eq!(cache_config.cache_hits(), 0);
883        assert_eq!(cache_config.cache_misses(), 1);
884        Component::new(&engine, "(component (core module (func)))")?;
885        assert_eq!(cache_config.cache_hits(), 1);
886        assert_eq!(cache_config.cache_misses(), 1);
887
888        Ok(())
889    }
890}