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) & expected_e_flags) == 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 & obj::EF_WASMTIME_MODULE != 0 => Some(Precompiled::Module),
160        FileFlags::Elf {
161            os_abi: obj::ELFOSABI_WASMTIME,
162            abi_version: 0,
163            e_flags,
164        } if e_flags & obj::EF_WASMTIME_COMPONENT != 0 => 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
319            // This doesn't affect compilation, it's just a runtime setting.
320            memory_reservation_for_growth: _,
321
322            // This does technically affect compilation but modules with/without
323            // trap information can be loaded into engines with the opposite
324            // setting just fine (it's just a section in the compiled file and
325            // whether it's present or not)
326            generate_address_map: _,
327
328            // Just a debugging aid, doesn't affect functionality at all.
329            debug_adapter_modules: _,
330
331            // This is a runtime GC debugging setting, doesn't affect compilation.
332            gc_zeal_alloc_counter: _,
333
334            gc_heap_reservation,
335            gc_heap_guard_size,
336            gc_heap_may_move,
337            gc_heap_initial_size,
338
339            // This doesn't affect compilation, it's just a runtime setting.
340            gc_heap_reservation_for_growth: _,
341
342            // No need to match whether or not this metadata is emitted, if it
343            // is or isn't then that's fine, the runtime handles it the same
344            // way.
345            metadata_for_internal_asserts: _,
346            metadata_for_gc_heap_corruption: _,
347
348            // Only affects cold-block layout; a compiled artifact loads into an
349            // engine configured either way.
350            branch_hinting: _,
351        } = self.tunables;
352
353        Self::check_collector(collector, other.collector)?;
354        Self::check_int(
355            memory_reservation,
356            other.memory_reservation,
357            "memory reservation",
358        )?;
359        Self::check_int(
360            memory_guard_size,
361            other.memory_guard_size,
362            "memory guard size",
363        )?;
364        Self::check_bool(
365            debug_native,
366            other.debug_native,
367            "native debug information support",
368        )?;
369        Self::check_bool(debug_guest, other.debug_guest, "guest debug")?;
370        Self::check_bool(debug_symbols, other.debug_symbols, "debug symbols")?;
371        Self::check_bool(
372            parse_wasm_debuginfo,
373            other.parse_wasm_debuginfo,
374            "WebAssembly backtrace support",
375        )?;
376        Self::check_bool(consume_fuel, other.consume_fuel, "fuel support")?;
377        Self::check_cost(consume_fuel, operator_cost, &other.operator_cost)?;
378        Self::check_bool(
379            epoch_interruption,
380            other.epoch_interruption,
381            "epoch interruption",
382        )?;
383        Self::check_bool(memory_may_move, other.memory_may_move, "memory may move")?;
384        Self::check_bool(
385            guard_before_linear_memory,
386            other.guard_before_linear_memory,
387            "guard before linear memory",
388        )?;
389        Self::check_bool(table_lazy_init, other.table_lazy_init, "table lazy init")?;
390        Self::check_bool(
391            relaxed_simd_deterministic,
392            other.relaxed_simd_deterministic,
393            "relaxed simd deterministic semantics",
394        )?;
395        Self::check_bool(
396            winch_callable,
397            other.winch_callable,
398            "Winch calling convention",
399        )?;
400        Self::check_bool(
401            signals_based_traps,
402            other.signals_based_traps,
403            "Signals-based traps",
404        )?;
405        Self::check_bool(
406            memory_init_cow,
407            other.memory_init_cow,
408            "memory initialization with CoW",
409        )?;
410        Self::check_int(
411            inlining_small_callee_size,
412            other.inlining_small_callee_size,
413            "function inlining small-callee size",
414        )?;
415        Self::check_int(
416            inlining_sum_size_threshold,
417            other.inlining_sum_size_threshold,
418            "function inlining sum-size threshold",
419        )?;
420        Self::check_bool(
421            concurrency_support,
422            other.concurrency_support,
423            "concurrency support",
424        )?;
425        Self::check_bool(recording, other.recording, "RR recording support")?;
426        Self::check_inlining(inlining, other.inlining)?;
427        Self::check_int(
428            gc_heap_reservation,
429            other.gc_heap_reservation,
430            "GC heap reservation",
431        )?;
432        Self::check_int(
433            gc_heap_guard_size,
434            other.gc_heap_guard_size,
435            "GC heap guard size",
436        )?;
437        Self::check_int(
438            gc_heap_initial_size,
439            other.gc_heap_initial_size,
440            "GC heap initial size",
441        )?;
442        Self::check_bool(gc_heap_may_move, other.gc_heap_may_move, "GC heap may move")?;
443
444        Ok(())
445    }
446
447    fn check_features(&mut self, other: &wasmparser::WasmFeatures) -> Result<()> {
448        let module_features = wasmparser::WasmFeatures::from_bits_truncate(self.features);
449        let missing_features = (*other & module_features) ^ module_features;
450        for (name, _) in missing_features.iter_names() {
451            let name = name.to_ascii_lowercase();
452            bail!(
453                "Module was compiled with support for WebAssembly feature \
454                `{name}` but it is not enabled for the host",
455            );
456        }
457        Ok(())
458    }
459
460    fn check_collector(
461        module: Option<wasmtime_environ::Collector>,
462        host: Option<wasmtime_environ::Collector>,
463    ) -> Result<()> {
464        match (module, host) {
465            // If the module doesn't require GC support it doesn't matter
466            // whether the host has GC support enabled or not.
467            (None, _) => Ok(()),
468            (Some(module), Some(host)) if module == host => Ok(()),
469
470            (Some(_), None) => {
471                bail!("module was compiled with GC however GC is disabled in the host")
472            }
473
474            (Some(module), Some(host)) => {
475                bail!(
476                    "module was compiled for the {module} collector but \
477                     the host is configured to use the {host} collector",
478                )
479            }
480        }
481    }
482
483    fn check_inlining(
484        module: wasmtime_environ::Inlining,
485        host: wasmtime_environ::Inlining,
486    ) -> Result<()> {
487        if module == host {
488            return Ok(());
489        }
490
491        let desc = |cfg| match cfg {
492            wasmtime_environ::Inlining::No => "without intra-module inlining",
493            wasmtime_environ::Inlining::Yes => "with intra-module inlining",
494            wasmtime_environ::Inlining::InterModuleAndIntraGc => {
495                "with intra-module inlining only when using GC"
496            }
497            wasmtime_environ::Inlining::Intrinsics => "with intrinsic inlining",
498            wasmtime_environ::Inlining::InterModule => "with inter-module inlining",
499        };
500
501        let module = desc(module);
502        let host = desc(host);
503
504        bail!("module was compiled {module} however the host is configured {host}")
505    }
506}
507
508#[cfg(test)]
509mod test {
510    use super::*;
511    use crate::{Cache, Config, Module, OptLevel};
512    use std::{
513        collections::hash_map::DefaultHasher,
514        hash::{Hash, Hasher},
515    };
516    use tempfile::TempDir;
517
518    #[test]
519    fn test_architecture_mismatch() -> Result<()> {
520        let engine = Engine::default();
521        let mut metadata = Metadata::new(&engine)?;
522        metadata.target = "unknown-generic-linux".to_string().into();
523
524        match metadata.check_compatible(&engine) {
525            Ok(_) => unreachable!(),
526            Err(e) => assert_eq!(
527                e.to_string(),
528                "Module was compiled for architecture 'unknown'",
529            ),
530        }
531
532        Ok(())
533    }
534
535    // Note that this test runs on a platform that is known to use Cranelift
536    #[test]
537    #[cfg(all(target_arch = "x86_64", not(miri)))]
538    fn test_os_mismatch() -> Result<()> {
539        let engine = Engine::default();
540        let mut metadata = Metadata::new(&engine)?;
541
542        metadata.target = format!(
543            "{}-generic-unknown",
544            target_lexicon::Triple::host().architecture
545        )
546        .into();
547
548        match metadata.check_compatible(&engine) {
549            Ok(_) => unreachable!(),
550            Err(e) => assert_eq!(
551                e.to_string(),
552                "Module was compiled for operating system 'unknown'",
553            ),
554        }
555
556        Ok(())
557    }
558
559    fn assert_contains(error: &Error, msg: &str) {
560        let msg = msg.trim();
561        if error.chain().any(|e| e.to_string().contains(msg)) {
562            return;
563        }
564
565        panic!("failed to find:\n\n'''{msg}\n'''\n\nwithin error message:\n\n'''{error:?}'''")
566    }
567
568    #[test]
569    fn test_cranelift_flags_mismatch() -> Result<()> {
570        let engine = Engine::default();
571        let mut metadata = Metadata::new(&engine)?;
572
573        metadata
574            .shared_flags
575            .push(("preserve_frame_pointers", FlagValue::Bool(false)))?;
576
577        match metadata.check_compatible(&engine) {
578            Ok(_) => unreachable!(),
579            Err(e) => {
580                assert_contains(
581                    &e,
582                    "compilation settings of module incompatible with native host",
583                );
584                assert_contains(
585                    &e,
586                    "setting \"preserve_frame_pointers\" is configured to Bool(false) which is not supported",
587                );
588            }
589        }
590
591        Ok(())
592    }
593
594    #[test]
595    fn test_isa_flags_mismatch() -> Result<()> {
596        let engine = Engine::default();
597        let mut metadata = Metadata::new(&engine)?;
598
599        metadata
600            .isa_flags
601            .push(("not_a_flag", FlagValue::Bool(true)))?;
602
603        match metadata.check_compatible(&engine) {
604            Ok(_) => unreachable!(),
605            Err(e) => {
606                assert_contains(
607                    &e,
608                    "compilation settings of module incompatible with native host",
609                );
610                assert_contains(
611                    &e,
612                    "don't know how to test for target-specific flag \"not_a_flag\" at runtime",
613                );
614            }
615        }
616
617        Ok(())
618    }
619
620    #[test]
621    #[cfg_attr(any(miri, not(has_native_signals)), ignore)]
622    #[cfg(target_pointer_width = "64")] // different defaults on 32-bit platforms
623    fn test_tunables_int_mismatch() -> Result<()> {
624        let engine = Engine::default();
625        let mut metadata = Metadata::new(&engine)?;
626
627        metadata.tunables.memory_guard_size = 0;
628
629        match metadata.check_compatible(&engine) {
630            Ok(_) => unreachable!(),
631            Err(e) => assert_eq!(
632                e.to_string(),
633                "Module was compiled with a memory guard size of '0' but '33554432' is expected for the host"
634            ),
635        }
636
637        Ok(())
638    }
639
640    #[test]
641    fn test_tunables_bool_mismatch() -> Result<()> {
642        let mut config = Config::new();
643        config.epoch_interruption(true);
644
645        let engine = Engine::new(&config)?;
646        let mut metadata = Metadata::new(&engine)?;
647        metadata.tunables.epoch_interruption = false;
648
649        match metadata.check_compatible(&engine) {
650            Ok(_) => unreachable!(),
651            Err(e) => assert_eq!(
652                e.to_string(),
653                "Module was compiled without epoch interruption but it is enabled for the host"
654            ),
655        }
656
657        let mut config = Config::new();
658        config.epoch_interruption(false);
659
660        let engine = Engine::new(&config)?;
661        let mut metadata = Metadata::new(&engine)?;
662        metadata.tunables.epoch_interruption = true;
663
664        match metadata.check_compatible(&engine) {
665            Ok(_) => unreachable!(),
666            Err(e) => assert_eq!(
667                e.to_string(),
668                "Module was compiled with epoch interruption but it is not enabled for the host"
669            ),
670        }
671
672        Ok(())
673    }
674
675    /// This test is only run a platform that is known to implement threads
676    #[test]
677    #[cfg(all(target_arch = "x86_64", not(miri)))]
678    fn test_feature_mismatch() -> Result<()> {
679        let mut config = Config::new();
680        config.wasm_threads(true);
681
682        let engine = Engine::new(&config)?;
683        let mut metadata = Metadata::new(&engine)?;
684        metadata.features &= !wasmparser::WasmFeatures::THREADS.bits();
685
686        // If a feature is disabled in the module and enabled in the host,
687        // that's always ok.
688        metadata.check_compatible(&engine)?;
689
690        let mut config = Config::new();
691        config.wasm_threads(false);
692
693        let engine = Engine::new(&config)?;
694        let mut metadata = Metadata::new(&engine)?;
695        metadata.features |= wasmparser::WasmFeatures::THREADS.bits();
696
697        match metadata.check_compatible(&engine) {
698            Ok(_) => unreachable!(),
699            Err(e) => assert_eq!(
700                e.to_string(),
701                "Module was compiled with support for WebAssembly feature \
702                `threads` but it is not enabled for the host"
703            ),
704        }
705
706        Ok(())
707    }
708
709    #[test]
710    fn engine_weak_upgrades() {
711        let engine = Engine::default();
712        let weak = engine.weak();
713        weak.upgrade()
714            .expect("engine is still alive, so weak reference can upgrade");
715        drop(engine);
716        assert!(
717            weak.upgrade().is_none(),
718            "engine was dropped, so weak reference cannot upgrade"
719        );
720    }
721
722    #[test]
723    #[cfg_attr(miri, ignore)]
724    fn cache_accounts_for_opt_level() -> Result<()> {
725        let _ = env_logger::try_init();
726
727        let td = TempDir::new()?;
728        let config_path = td.path().join("config.toml");
729        std::fs::write(
730            &config_path,
731            &format!(
732                "
733                    [cache]
734                    directory = '{}'
735                ",
736                td.path().join("cache").display()
737            ),
738        )?;
739        let mut cfg = Config::new();
740        cfg.cranelift_opt_level(OptLevel::None)
741            .cache(Some(Cache::from_file(Some(&config_path))?));
742        let engine = Engine::new(&cfg)?;
743        Module::new(&engine, "(module (func))")?;
744        let cache_config = engine
745            .config()
746            .cache
747            .as_ref()
748            .expect("Missing cache config");
749        assert_eq!(cache_config.cache_hits(), 0);
750        assert_eq!(cache_config.cache_misses(), 1);
751        Module::new(&engine, "(module (func))")?;
752        assert_eq!(cache_config.cache_hits(), 1);
753        assert_eq!(cache_config.cache_misses(), 1);
754
755        let mut cfg = Config::new();
756        cfg.cranelift_opt_level(OptLevel::Speed)
757            .cache(Some(Cache::from_file(Some(&config_path))?));
758        let engine = Engine::new(&cfg)?;
759        let cache_config = engine
760            .config()
761            .cache
762            .as_ref()
763            .expect("Missing cache config");
764        Module::new(&engine, "(module (func))")?;
765        assert_eq!(cache_config.cache_hits(), 0);
766        assert_eq!(cache_config.cache_misses(), 1);
767        Module::new(&engine, "(module (func))")?;
768        assert_eq!(cache_config.cache_hits(), 1);
769        assert_eq!(cache_config.cache_misses(), 1);
770
771        let mut cfg = Config::new();
772        cfg.cranelift_opt_level(OptLevel::SpeedAndSize)
773            .cache(Some(Cache::from_file(Some(&config_path))?));
774        let engine = Engine::new(&cfg)?;
775        let cache_config = engine
776            .config()
777            .cache
778            .as_ref()
779            .expect("Missing cache config");
780        Module::new(&engine, "(module (func))")?;
781        assert_eq!(cache_config.cache_hits(), 0);
782        assert_eq!(cache_config.cache_misses(), 1);
783        Module::new(&engine, "(module (func))")?;
784        assert_eq!(cache_config.cache_hits(), 1);
785        assert_eq!(cache_config.cache_misses(), 1);
786
787        let mut cfg = Config::new();
788        cfg.debug_info(true)
789            .cache(Some(Cache::from_file(Some(&config_path))?));
790        let engine = Engine::new(&cfg)?;
791        let cache_config = engine
792            .config()
793            .cache
794            .as_ref()
795            .expect("Missing cache config");
796        Module::new(&engine, "(module (func))")?;
797        assert_eq!(cache_config.cache_hits(), 0);
798        assert_eq!(cache_config.cache_misses(), 1);
799        Module::new(&engine, "(module (func))")?;
800        assert_eq!(cache_config.cache_hits(), 1);
801        assert_eq!(cache_config.cache_misses(), 1);
802
803        Ok(())
804    }
805
806    #[test]
807    fn precompile_compatibility_key_accounts_for_opt_level() {
808        fn hash_for_config(cfg: &Config) -> u64 {
809            let engine = Engine::new(cfg).expect("Config should be valid");
810            let mut hasher = DefaultHasher::new();
811            engine.precompile_compatibility_hash().hash(&mut hasher);
812            hasher.finish()
813        }
814        let mut cfg = Config::new();
815        cfg.cranelift_opt_level(OptLevel::None);
816        let opt_none_hash = hash_for_config(&cfg);
817        cfg.cranelift_opt_level(OptLevel::Speed);
818        let opt_speed_hash = hash_for_config(&cfg);
819        assert_ne!(opt_none_hash, opt_speed_hash)
820    }
821
822    #[test]
823    fn precompile_compatibility_key_accounts_for_module_version_strategy() -> Result<()> {
824        fn hash_for_config(cfg: &Config) -> u64 {
825            let engine = Engine::new(cfg).expect("Config should be valid");
826            let mut hasher = DefaultHasher::new();
827            engine.precompile_compatibility_hash().hash(&mut hasher);
828            hasher.finish()
829        }
830        let mut cfg_custom_version = Config::new();
831        cfg_custom_version.module_version(ModuleVersionStrategy::Custom("1.0.1111".to_string()))?;
832        let custom_version_hash = hash_for_config(&cfg_custom_version);
833
834        let mut cfg_default_version = Config::new();
835        cfg_default_version.module_version(ModuleVersionStrategy::WasmtimeVersion)?;
836        let default_version_hash = hash_for_config(&cfg_default_version);
837
838        let mut cfg_none_version = Config::new();
839        cfg_none_version.module_version(ModuleVersionStrategy::None)?;
840        let none_version_hash = hash_for_config(&cfg_none_version);
841
842        assert_ne!(custom_version_hash, default_version_hash);
843        assert_ne!(custom_version_hash, none_version_hash);
844        assert_ne!(default_version_hash, none_version_hash);
845
846        Ok(())
847    }
848
849    #[test]
850    #[cfg_attr(miri, ignore)]
851    #[cfg(feature = "component-model")]
852    fn components_are_cached() -> Result<()> {
853        use crate::component::Component;
854
855        let td = TempDir::new()?;
856        let config_path = td.path().join("config.toml");
857        std::fs::write(
858            &config_path,
859            &format!(
860                "
861                    [cache]
862                    directory = '{}'
863                ",
864                td.path().join("cache").display()
865            ),
866        )?;
867        let mut cfg = Config::new();
868        cfg.cache(Some(Cache::from_file(Some(&config_path))?));
869        let engine = Engine::new(&cfg)?;
870        let cache_config = engine
871            .config()
872            .cache
873            .as_ref()
874            .expect("Missing cache config");
875        Component::new(&engine, "(component (core module (func)))")?;
876        assert_eq!(cache_config.cache_hits(), 0);
877        assert_eq!(cache_config.cache_misses(), 1);
878        Component::new(&engine, "(component (core module (func)))")?;
879        assert_eq!(cache_config.cache_hits(), 1);
880        assert_eq!(cache_config.cache_misses(), 1);
881
882        Ok(())
883    }
884}