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