1 use crate::prelude::*; 2 use crate::runtime::vm::{ 3 CompiledModuleId, MemoryImage, MmapVec, ModuleMemoryImages, VMArrayCallFunction, 4 VMNativeCallFunction, VMWasmCallFunction, 5 }; 6 use crate::sync::OnceLock; 7 use crate::{ 8 code::CodeObject, 9 code_memory::CodeMemory, 10 instantiate::CompiledModule, 11 resources::ResourcesRequired, 12 type_registry::TypeCollection, 13 types::{ExportType, ExternType, ImportType}, 14 Engine, 15 }; 16 use alloc::sync::Arc; 17 use anyhow::{bail, Result}; 18 use core::fmt; 19 use core::mem; 20 use core::ops::Range; 21 use core::ptr::NonNull; 22 #[cfg(feature = "std")] 23 use std::path::Path; 24 use wasmparser::{Parser, ValidPayload, Validator}; 25 use wasmtime_environ::{ 26 CompiledModuleInfo, DefinedFuncIndex, DefinedMemoryIndex, EntityIndex, HostPtr, ModuleTypes, 27 ObjectKind, VMOffsets, VMSharedTypeIndex, 28 }; 29 mod registry; 30 31 pub use registry::{ 32 get_wasm_trap, register_code, unregister_code, ModuleRegistry, RegisteredModuleId, 33 }; 34 35 /// A compiled WebAssembly module, ready to be instantiated. 36 /// 37 /// A `Module` is a compiled in-memory representation of an input WebAssembly 38 /// binary. A `Module` is then used to create an [`Instance`](crate::Instance) 39 /// through an instantiation process. You cannot call functions or fetch 40 /// globals, for example, on a `Module` because it's purely a code 41 /// representation. Instead you'll need to create an 42 /// [`Instance`](crate::Instance) to interact with the wasm module. 43 /// 44 /// A `Module` can be created by compiling WebAssembly code through APIs such as 45 /// [`Module::new`]. This would be a JIT-style use case where code is compiled 46 /// just before it's used. Alternatively a `Module` can be compiled in one 47 /// process and [`Module::serialize`] can be used to save it to storage. A later 48 /// call to [`Module::deserialize`] will quickly load the module to execute and 49 /// does not need to compile any code, representing a more AOT-style use case. 50 /// 51 /// Currently a `Module` does not implement any form of tiering or dynamic 52 /// optimization of compiled code. Creation of a `Module` via [`Module::new`] or 53 /// related APIs will perform the entire compilation step synchronously. When 54 /// finished no further compilation will happen at runtime or later during 55 /// execution of WebAssembly instances for example. 56 /// 57 /// Compilation of WebAssembly by default goes through Cranelift and is 58 /// recommended to be done once-per-module. The same WebAssembly binary need not 59 /// be compiled multiple times and can instead used an embedder-cached result of 60 /// the first call. 61 /// 62 /// `Module` is thread-safe and safe to share across threads. 63 /// 64 /// ## Modules and `Clone` 65 /// 66 /// Using `clone` on a `Module` is a cheap operation. It will not create an 67 /// entirely new module, but rather just a new reference to the existing module. 68 /// In other words it's a shallow copy, not a deep copy. 69 /// 70 /// ## Examples 71 /// 72 /// There are a number of ways you can create a `Module`, for example pulling 73 /// the bytes from a number of locations. One example is loading a module from 74 /// the filesystem: 75 /// 76 /// ```no_run 77 /// # use wasmtime::*; 78 /// # fn main() -> anyhow::Result<()> { 79 /// let engine = Engine::default(); 80 /// let module = Module::from_file(&engine, "path/to/foo.wasm")?; 81 /// # Ok(()) 82 /// # } 83 /// ``` 84 /// 85 /// You can also load the wasm text format if more convenient too: 86 /// 87 /// ```no_run 88 /// # use wasmtime::*; 89 /// # fn main() -> anyhow::Result<()> { 90 /// let engine = Engine::default(); 91 /// // Now we're using the WebAssembly text extension: `.wat`! 92 /// let module = Module::from_file(&engine, "path/to/foo.wat")?; 93 /// # Ok(()) 94 /// # } 95 /// ``` 96 /// 97 /// And if you've already got the bytes in-memory you can use the 98 /// [`Module::new`] constructor: 99 /// 100 /// ```no_run 101 /// # use wasmtime::*; 102 /// # fn main() -> anyhow::Result<()> { 103 /// let engine = Engine::default(); 104 /// # let wasm_bytes: Vec<u8> = Vec::new(); 105 /// let module = Module::new(&engine, &wasm_bytes)?; 106 /// 107 /// // It also works with the text format! 108 /// let module = Module::new(&engine, "(module (func))")?; 109 /// # Ok(()) 110 /// # } 111 /// ``` 112 /// 113 /// Serializing and deserializing a module looks like: 114 /// 115 /// ```no_run 116 /// # use wasmtime::*; 117 /// # fn main() -> anyhow::Result<()> { 118 /// let engine = Engine::default(); 119 /// # let wasm_bytes: Vec<u8> = Vec::new(); 120 /// let module = Module::new(&engine, &wasm_bytes)?; 121 /// let module_bytes = module.serialize()?; 122 /// 123 /// // ... can save `module_bytes` to disk or other storage ... 124 /// 125 /// // recreate the module from the serialized bytes. For the `unsafe` bits 126 /// // see the documentation of `deserialize`. 127 /// let module = unsafe { Module::deserialize(&engine, &module_bytes)? }; 128 /// # Ok(()) 129 /// # } 130 /// ``` 131 /// 132 /// [`Config`]: crate::Config 133 #[derive(Clone)] 134 pub struct Module { 135 inner: Arc<ModuleInner>, 136 } 137 138 struct ModuleInner { 139 engine: Engine, 140 /// The compiled artifacts for this module that will be instantiated and 141 /// executed. 142 module: CompiledModule, 143 144 /// Runtime information such as the underlying mmap, type information, etc. 145 /// 146 /// Note that this `Arc` is used to share information between compiled 147 /// modules within a component. For bare core wasm modules created with 148 /// `Module::new`, for example, this is a uniquely owned `Arc`. 149 code: Arc<CodeObject>, 150 151 /// A set of initialization images for memories, if any. 152 /// 153 /// Note that this is behind a `OnceCell` to lazily create this image. On 154 /// Linux where `memfd_create` may be used to create the backing memory 155 /// image this is a pretty expensive operation, so by deferring it this 156 /// improves memory usage for modules that are created but may not ever be 157 /// instantiated. 158 memory_images: OnceLock<Option<ModuleMemoryImages>>, 159 160 /// Flag indicating whether this module can be serialized or not. 161 serializable: bool, 162 163 /// Runtime offset information for `VMContext`. 164 offsets: VMOffsets<HostPtr>, 165 } 166 167 impl fmt::Debug for Module { 168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 169 f.debug_struct("Module") 170 .field("name", &self.name()) 171 .finish_non_exhaustive() 172 } 173 } 174 175 impl fmt::Debug for ModuleInner { 176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 177 f.debug_struct("ModuleInner") 178 .field("name", &self.module.module().name.as_ref()) 179 .finish_non_exhaustive() 180 } 181 } 182 183 impl Module { 184 /// Creates a new WebAssembly `Module` from the given in-memory `bytes`. 185 /// 186 /// The `bytes` provided must be in one of the following formats: 187 /// 188 /// * A [binary-encoded][binary] WebAssembly module. This is always supported. 189 /// * A [text-encoded][text] instance of the WebAssembly text format. 190 /// This is only supported when the `wat` feature of this crate is enabled. 191 /// If this is supplied then the text format will be parsed before validation. 192 /// Note that the `wat` feature is enabled by default. 193 /// 194 /// The data for the wasm module must be loaded in-memory if it's present 195 /// elsewhere, for example on disk. This requires that the entire binary is 196 /// loaded into memory all at once, this API does not support streaming 197 /// compilation of a module. 198 /// 199 /// The WebAssembly binary will be decoded and validated. It will also be 200 /// compiled according to the configuration of the provided `engine`. 201 /// 202 /// # Errors 203 /// 204 /// This function may fail and return an error. Errors may include 205 /// situations such as: 206 /// 207 /// * The binary provided could not be decoded because it's not a valid 208 /// WebAssembly binary 209 /// * The WebAssembly binary may not validate (e.g. contains type errors) 210 /// * Implementation-specific limits were exceeded with a valid binary (for 211 /// example too many locals) 212 /// * The wasm binary may use features that are not enabled in the 213 /// configuration of `engine` 214 /// * If the `wat` feature is enabled and the input is text, then it may be 215 /// rejected if it fails to parse. 216 /// 217 /// The error returned should contain full information about why module 218 /// creation failed if one is returned. 219 /// 220 /// [binary]: https://webassembly.github.io/spec/core/binary/index.html 221 /// [text]: https://webassembly.github.io/spec/core/text/index.html 222 /// 223 /// # Examples 224 /// 225 /// The `new` function can be invoked with a in-memory array of bytes: 226 /// 227 /// ```no_run 228 /// # use wasmtime::*; 229 /// # fn main() -> anyhow::Result<()> { 230 /// # let engine = Engine::default(); 231 /// # let wasm_bytes: Vec<u8> = Vec::new(); 232 /// let module = Module::new(&engine, &wasm_bytes)?; 233 /// # Ok(()) 234 /// # } 235 /// ``` 236 /// 237 /// Or you can also pass in a string to be parsed as the wasm text 238 /// format: 239 /// 240 /// ``` 241 /// # use wasmtime::*; 242 /// # fn main() -> anyhow::Result<()> { 243 /// # let engine = Engine::default(); 244 /// let module = Module::new(&engine, "(module (func))")?; 245 /// # Ok(()) 246 /// # } 247 /// ``` 248 #[cfg(any(feature = "cranelift", feature = "winch"))] 249 pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> { 250 crate::CodeBuilder::new(engine) 251 .wasm(bytes.as_ref(), None)? 252 .compile_module() 253 } 254 255 /// Creates a new WebAssembly `Module` from the contents of the given 256 /// `file` on disk. 257 /// 258 /// This is a convenience function that will read the `file` provided and 259 /// pass the bytes to the [`Module::new`] function. For more information 260 /// see [`Module::new`] 261 /// 262 /// # Examples 263 /// 264 /// ```no_run 265 /// # use wasmtime::*; 266 /// # fn main() -> anyhow::Result<()> { 267 /// let engine = Engine::default(); 268 /// let module = Module::from_file(&engine, "./path/to/foo.wasm")?; 269 /// # Ok(()) 270 /// # } 271 /// ``` 272 /// 273 /// The `.wat` text format is also supported: 274 /// 275 /// ```no_run 276 /// # use wasmtime::*; 277 /// # fn main() -> anyhow::Result<()> { 278 /// # let engine = Engine::default(); 279 /// let module = Module::from_file(&engine, "./path/to/foo.wat")?; 280 /// # Ok(()) 281 /// # } 282 /// ``` 283 #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))] 284 pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> { 285 crate::CodeBuilder::new(engine) 286 .wasm_file(file.as_ref())? 287 .compile_module() 288 } 289 290 /// Creates a new WebAssembly `Module` from the given in-memory `binary` 291 /// data. 292 /// 293 /// This is similar to [`Module::new`] except that it requires that the 294 /// `binary` input is a WebAssembly binary, the text format is not supported 295 /// by this function. It's generally recommended to use [`Module::new`], but 296 /// if it's required to not support the text format this function can be 297 /// used instead. 298 /// 299 /// # Examples 300 /// 301 /// ``` 302 /// # use wasmtime::*; 303 /// # fn main() -> anyhow::Result<()> { 304 /// # let engine = Engine::default(); 305 /// let wasm = b"\0asm\x01\0\0\0"; 306 /// let module = Module::from_binary(&engine, wasm)?; 307 /// # Ok(()) 308 /// # } 309 /// ``` 310 /// 311 /// Note that the text format is **not** accepted by this function: 312 /// 313 /// ``` 314 /// # use wasmtime::*; 315 /// # fn main() -> anyhow::Result<()> { 316 /// # let engine = Engine::default(); 317 /// assert!(Module::from_binary(&engine, b"(module)").is_err()); 318 /// # Ok(()) 319 /// # } 320 /// ``` 321 #[cfg(any(feature = "cranelift", feature = "winch"))] 322 pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Module> { 323 crate::CodeBuilder::new(engine) 324 .wasm(binary, None)? 325 .wat(false)? 326 .compile_module() 327 } 328 329 /// Creates a new WebAssembly `Module` from the contents of the given `file` 330 /// on disk, but with assumptions that the file is from a trusted source. 331 /// The file should be a binary- or text-format WebAssembly module, or a 332 /// precompiled artifact generated by the same version of Wasmtime. 333 /// 334 /// # Unsafety 335 /// 336 /// All of the reasons that [`deserialize`] is `unsafe` apply to this 337 /// function as well. Arbitrary data loaded from a file may trick Wasmtime 338 /// into arbitrary code execution since the contents of the file are not 339 /// validated to be a valid precompiled module. 340 /// 341 /// [`deserialize`]: Module::deserialize 342 /// 343 /// Additionally though this function is also `unsafe` because the file 344 /// referenced must remain unchanged and a valid precompiled module for the 345 /// entire lifetime of the [`Module`] returned. Any changes to the file on 346 /// disk may change future instantiations of the module to be incorrect. 347 /// This is because the file is mapped into memory and lazily loaded pages 348 /// reflect the current state of the file, not necessarily the original 349 /// state of the file. 350 #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))] 351 pub unsafe fn from_trusted_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Module> { 352 let mmap = MmapVec::from_file(file.as_ref())?; 353 if &mmap[0..4] == b"\x7fELF" { 354 let code = engine.load_code(mmap, ObjectKind::Module)?; 355 return Module::from_parts(engine, code, None); 356 } 357 358 crate::CodeBuilder::new(engine) 359 .wasm(&mmap, Some(file.as_ref()))? 360 .compile_module() 361 } 362 363 /// Deserializes an in-memory compiled module previously created with 364 /// [`Module::serialize`] or [`Engine::precompile_module`]. 365 /// 366 /// This function will deserialize the binary blobs emitted by 367 /// [`Module::serialize`] and [`Engine::precompile_module`] back into an 368 /// in-memory [`Module`] that's ready to be instantiated. 369 /// 370 /// Note that the [`Module::deserialize_file`] method is more optimized than 371 /// this function, so if the serialized module is already present in a file 372 /// it's recommended to use that method instead. 373 /// 374 /// # Unsafety 375 /// 376 /// This function is marked as `unsafe` because if fed invalid input or used 377 /// improperly this could lead to memory safety vulnerabilities. This method 378 /// should not, for example, be exposed to arbitrary user input. 379 /// 380 /// The structure of the binary blob read here is only lightly validated 381 /// internally in `wasmtime`. This is intended to be an efficient 382 /// "rehydration" for a [`Module`] which has very few runtime checks beyond 383 /// deserialization. Arbitrary input could, for example, replace valid 384 /// compiled code with any other valid compiled code, meaning that this can 385 /// trivially be used to execute arbitrary code otherwise. 386 /// 387 /// For these reasons this function is `unsafe`. This function is only 388 /// designed to receive the previous input from [`Module::serialize`] and 389 /// [`Engine::precompile_module`]. If the exact output of those functions 390 /// (unmodified) is passed to this function then calls to this function can 391 /// be considered safe. It is the caller's responsibility to provide the 392 /// guarantee that only previously-serialized bytes are being passed in 393 /// here. 394 /// 395 /// Note that this function is designed to be safe receiving output from 396 /// *any* compiled version of `wasmtime` itself. This means that it is safe 397 /// to feed output from older versions of Wasmtime into this function, in 398 /// addition to newer versions of wasmtime (from the future!). These inputs 399 /// will deterministically and safely produce an `Err`. This function only 400 /// successfully accepts inputs from the same version of `wasmtime`, but the 401 /// safety guarantee only applies to externally-defined blobs of bytes, not 402 /// those defined by any version of wasmtime. (this means that if you cache 403 /// blobs across versions of wasmtime you can be safely guaranteed that 404 /// future versions of wasmtime will reject old cache entries). 405 pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Module> { 406 let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Module)?; 407 Module::from_parts(engine, code, None) 408 } 409 410 /// Same as [`deserialize`], except that the contents of `path` are read to 411 /// deserialize into a [`Module`]. 412 /// 413 /// This method is provided because it can be faster than [`deserialize`] 414 /// since the data doesn't need to be copied around, but rather the module 415 /// can be used directly from an mmap'd view of the file provided. 416 /// 417 /// [`deserialize`]: Module::deserialize 418 /// 419 /// # Unsafety 420 /// 421 /// All of the reasons that [`deserialize`] is `unsafe` applies to this 422 /// function as well. Arbitrary data loaded from a file may trick Wasmtime 423 /// into arbitrary code execution since the contents of the file are not 424 /// validated to be a valid precompiled module. 425 /// 426 /// Additionally though this function is also `unsafe` because the file 427 /// referenced must remain unchanged and a valid precompiled module for the 428 /// entire lifetime of the [`Module`] returned. Any changes to the file on 429 /// disk may change future instantiations of the module to be incorrect. 430 /// This is because the file is mapped into memory and lazily loaded pages 431 /// reflect the current state of the file, not necessarily the origianl 432 /// state of the file. 433 #[cfg(feature = "std")] 434 pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Module> { 435 let code = engine.load_code_file(path.as_ref(), ObjectKind::Module)?; 436 Module::from_parts(engine, code, None) 437 } 438 439 /// Entrypoint for creating a `Module` for all above functions, both 440 /// of the AOT and jit-compiled cateogries. 441 /// 442 /// In all cases the compilation artifact, `code_memory`, is provided here. 443 /// The `info_and_types` argument is `None` when a module is being 444 /// deserialized from a precompiled artifact or it's `Some` if it was just 445 /// compiled and the values are already available. 446 pub(crate) fn from_parts( 447 engine: &Engine, 448 code_memory: Arc<CodeMemory>, 449 info_and_types: Option<(CompiledModuleInfo, ModuleTypes)>, 450 ) -> Result<Self> { 451 // Acquire this module's metadata and type information, deserializing 452 // it from the provided artifact if it wasn't otherwise provided 453 // already. 454 let (info, types) = match info_and_types { 455 Some((info, types)) => (info, types), 456 None => postcard::from_bytes(code_memory.wasmtime_info()).err2anyhow()?, 457 }; 458 459 // Register function type signatures into the engine for the lifetime 460 // of the `Module` that will be returned. This notably also builds up 461 // maps for trampolines to be used for this module when inserted into 462 // stores. 463 // 464 // Note that the unsafety here should be ok since the `trampolines` 465 // field should only point to valid trampoline function pointers 466 // within the text section. 467 let signatures = TypeCollection::new_for_module(engine, &types); 468 469 // Package up all our data into a `CodeObject` and delegate to the final 470 // step of module compilation. 471 let code = Arc::new(CodeObject::new(code_memory, signatures, types.into())); 472 Module::from_parts_raw(engine, code, info, true) 473 } 474 475 pub(crate) fn from_parts_raw( 476 engine: &Engine, 477 code: Arc<CodeObject>, 478 info: CompiledModuleInfo, 479 serializable: bool, 480 ) -> Result<Self> { 481 let module = CompiledModule::from_artifacts( 482 code.code_memory().clone(), 483 info, 484 engine.profiler(), 485 engine.unique_id_allocator(), 486 )?; 487 488 // Validate the module can be used with the current instance allocator. 489 let offsets = VMOffsets::new(HostPtr, module.module()); 490 engine 491 .allocator() 492 .validate_module(module.module(), &offsets)?; 493 494 Ok(Self { 495 inner: Arc::new(ModuleInner { 496 engine: engine.clone(), 497 code, 498 memory_images: OnceLock::new(), 499 module, 500 serializable, 501 offsets, 502 }), 503 }) 504 } 505 506 /// Validates `binary` input data as a WebAssembly binary given the 507 /// configuration in `engine`. 508 /// 509 /// This function will perform a speedy validation of the `binary` input 510 /// WebAssembly module (which is in [binary form][binary], the text format 511 /// is not accepted by this function) and return either `Ok` or `Err` 512 /// depending on the results of validation. The `engine` argument indicates 513 /// configuration for WebAssembly features, for example, which are used to 514 /// indicate what should be valid and what shouldn't be. 515 /// 516 /// Validation automatically happens as part of [`Module::new`]. 517 /// 518 /// # Errors 519 /// 520 /// If validation fails for any reason (type check error, usage of a feature 521 /// that wasn't enabled, etc) then an error with a description of the 522 /// validation issue will be returned. 523 /// 524 /// [binary]: https://webassembly.github.io/spec/core/binary/index.html 525 pub fn validate(engine: &Engine, binary: &[u8]) -> Result<()> { 526 let mut validator = Validator::new_with_features(engine.config().features); 527 528 let mut functions = Vec::new(); 529 for payload in Parser::new(0).parse_all(binary) { 530 let payload = payload.err2anyhow()?; 531 if let ValidPayload::Func(a, b) = validator.payload(&payload).err2anyhow()? { 532 functions.push((a, b)); 533 } 534 if let wasmparser::Payload::Version { encoding, .. } = &payload { 535 if let wasmparser::Encoding::Component = encoding { 536 bail!("component passed to module validation"); 537 } 538 } 539 } 540 541 engine 542 .run_maybe_parallel(functions, |(validator, body)| { 543 // FIXME: it would be best here to use a rayon-specific parallel 544 // iterator that maintains state-per-thread to share the function 545 // validator allocations (`Default::default` here) across multiple 546 // functions. 547 validator.into_validator(Default::default()).validate(&body) 548 }) 549 .err2anyhow()?; 550 Ok(()) 551 } 552 553 /// Serializes this module to a vector of bytes. 554 /// 555 /// This function is similar to the [`Engine::precompile_module`] method 556 /// where it produces an artifact of Wasmtime which is suitable to later 557 /// pass into [`Module::deserialize`]. If a module is never instantiated 558 /// then it's recommended to use [`Engine::precompile_module`] instead of 559 /// this method, but if a module is both instantiated and serialized then 560 /// this method can be useful to get the serialized version without 561 /// compiling twice. 562 #[cfg(any(feature = "cranelift", feature = "winch"))] 563 pub fn serialize(&self) -> Result<Vec<u8>> { 564 // The current representation of compiled modules within a compiled 565 // component means that it cannot be serialized. The mmap returned here 566 // is the mmap for the entire component and while it contains all 567 // necessary data to deserialize this particular module it's all 568 // embedded within component-specific information. 569 // 570 // It's not the hardest thing in the world to support this but it's 571 // expected that there's not much of a use case at this time. In theory 572 // all that needs to be done is to edit the `.wasmtime.info` section 573 // to contains this module's metadata instead of the metadata for the 574 // whole component. The metadata itself is fairly trivially 575 // recreateable here it's more that there's no easy one-off API for 576 // editing the sections of an ELF object to use here. 577 // 578 // Overall for now this simply always returns an error in this 579 // situation. If you're reading this and feel that the situation should 580 // be different please feel free to open an issue. 581 if !self.inner.serializable { 582 bail!("cannot serialize a module exported from a component"); 583 } 584 Ok(self.compiled_module().mmap().to_vec()) 585 } 586 587 pub(crate) fn compiled_module(&self) -> &CompiledModule { 588 &self.inner.module 589 } 590 591 fn code_object(&self) -> &Arc<CodeObject> { 592 &self.inner.code 593 } 594 595 pub(crate) fn env_module(&self) -> &wasmtime_environ::Module { 596 self.compiled_module().module() 597 } 598 599 pub(crate) fn types(&self) -> &ModuleTypes { 600 self.inner.code.module_types() 601 } 602 603 pub(crate) fn signatures(&self) -> &TypeCollection { 604 self.inner.code.signatures() 605 } 606 607 /// Returns identifier/name that this [`Module`] has. This name 608 /// is used in traps/backtrace details. 609 /// 610 /// Note that most LLVM/clang/Rust-produced modules do not have a name 611 /// associated with them, but other wasm tooling can be used to inject or 612 /// add a name. 613 /// 614 /// # Examples 615 /// 616 /// ``` 617 /// # use wasmtime::*; 618 /// # fn main() -> anyhow::Result<()> { 619 /// # let engine = Engine::default(); 620 /// let module = Module::new(&engine, "(module $foo)")?; 621 /// assert_eq!(module.name(), Some("foo")); 622 /// 623 /// let module = Module::new(&engine, "(module)")?; 624 /// assert_eq!(module.name(), None); 625 /// 626 /// # Ok(()) 627 /// # } 628 /// ``` 629 pub fn name(&self) -> Option<&str> { 630 self.compiled_module().module().name.as_deref() 631 } 632 633 /// Returns the list of imports that this [`Module`] has and must be 634 /// satisfied. 635 /// 636 /// This function returns the list of imports that the wasm module has, but 637 /// only the types of each import. The type of each import is used to 638 /// typecheck the [`Instance::new`](crate::Instance::new) method's `imports` 639 /// argument. The arguments to that function must match up 1-to-1 with the 640 /// entries in the array returned here. 641 /// 642 /// The imports returned reflect the order of the imports in the wasm module 643 /// itself, and note that no form of deduplication happens. 644 /// 645 /// # Examples 646 /// 647 /// Modules with no imports return an empty list here: 648 /// 649 /// ``` 650 /// # use wasmtime::*; 651 /// # fn main() -> anyhow::Result<()> { 652 /// # let engine = Engine::default(); 653 /// let module = Module::new(&engine, "(module)")?; 654 /// assert_eq!(module.imports().len(), 0); 655 /// # Ok(()) 656 /// # } 657 /// ``` 658 /// 659 /// and modules with imports will have a non-empty list: 660 /// 661 /// ``` 662 /// # use wasmtime::*; 663 /// # fn main() -> anyhow::Result<()> { 664 /// # let engine = Engine::default(); 665 /// let wat = r#" 666 /// (module 667 /// (import "host" "foo" (func)) 668 /// ) 669 /// "#; 670 /// let module = Module::new(&engine, wat)?; 671 /// assert_eq!(module.imports().len(), 1); 672 /// let import = module.imports().next().unwrap(); 673 /// assert_eq!(import.module(), "host"); 674 /// assert_eq!(import.name(), "foo"); 675 /// match import.ty() { 676 /// ExternType::Func(_) => { /* ... */ } 677 /// _ => panic!("unexpected import type!"), 678 /// } 679 /// # Ok(()) 680 /// # } 681 /// ``` 682 pub fn imports<'module>( 683 &'module self, 684 ) -> impl ExactSizeIterator<Item = ImportType<'module>> + 'module { 685 let module = self.compiled_module().module(); 686 let types = self.types(); 687 let engine = self.engine(); 688 module 689 .imports() 690 .map(move |(module, field, ty)| ImportType::new(module, field, ty, types, engine)) 691 .collect::<Vec<_>>() 692 .into_iter() 693 } 694 695 /// Returns the list of exports that this [`Module`] has and will be 696 /// available after instantiation. 697 /// 698 /// This function will return the type of each item that will be returned 699 /// from [`Instance::exports`](crate::Instance::exports). Each entry in this 700 /// list corresponds 1-to-1 with that list, and the entries here will 701 /// indicate the name of the export along with the type of the export. 702 /// 703 /// # Examples 704 /// 705 /// Modules might not have any exports: 706 /// 707 /// ``` 708 /// # use wasmtime::*; 709 /// # fn main() -> anyhow::Result<()> { 710 /// # let engine = Engine::default(); 711 /// let module = Module::new(&engine, "(module)")?; 712 /// assert!(module.exports().next().is_none()); 713 /// # Ok(()) 714 /// # } 715 /// ``` 716 /// 717 /// When the exports are not empty, you can inspect each export: 718 /// 719 /// ``` 720 /// # use wasmtime::*; 721 /// # fn main() -> anyhow::Result<()> { 722 /// # let engine = Engine::default(); 723 /// let wat = r#" 724 /// (module 725 /// (func (export "foo")) 726 /// (memory (export "memory") 1) 727 /// ) 728 /// "#; 729 /// let module = Module::new(&engine, wat)?; 730 /// assert_eq!(module.exports().len(), 2); 731 /// 732 /// let mut exports = module.exports(); 733 /// let foo = exports.next().unwrap(); 734 /// assert_eq!(foo.name(), "foo"); 735 /// match foo.ty() { 736 /// ExternType::Func(_) => { /* ... */ } 737 /// _ => panic!("unexpected export type!"), 738 /// } 739 /// 740 /// let memory = exports.next().unwrap(); 741 /// assert_eq!(memory.name(), "memory"); 742 /// match memory.ty() { 743 /// ExternType::Memory(_) => { /* ... */ } 744 /// _ => panic!("unexpected export type!"), 745 /// } 746 /// # Ok(()) 747 /// # } 748 /// ``` 749 pub fn exports<'module>( 750 &'module self, 751 ) -> impl ExactSizeIterator<Item = ExportType<'module>> + 'module { 752 let module = self.compiled_module().module(); 753 let types = self.types(); 754 let engine = self.engine(); 755 module.exports.iter().map(move |(name, entity_index)| { 756 ExportType::new(name, module.type_of(*entity_index), types, engine) 757 }) 758 } 759 760 /// Looks up an export in this [`Module`] by name. 761 /// 762 /// This function will return the type of an export with the given name. 763 /// 764 /// # Examples 765 /// 766 /// There may be no export with that name: 767 /// 768 /// ``` 769 /// # use wasmtime::*; 770 /// # fn main() -> anyhow::Result<()> { 771 /// # let engine = Engine::default(); 772 /// let module = Module::new(&engine, "(module)")?; 773 /// assert!(module.get_export("foo").is_none()); 774 /// # Ok(()) 775 /// # } 776 /// ``` 777 /// 778 /// When there is an export with that name, it is returned: 779 /// 780 /// ``` 781 /// # use wasmtime::*; 782 /// # fn main() -> anyhow::Result<()> { 783 /// # let engine = Engine::default(); 784 /// let wat = r#" 785 /// (module 786 /// (func (export "foo")) 787 /// (memory (export "memory") 1) 788 /// ) 789 /// "#; 790 /// let module = Module::new(&engine, wat)?; 791 /// let foo = module.get_export("foo"); 792 /// assert!(foo.is_some()); 793 /// 794 /// let foo = foo.unwrap(); 795 /// match foo { 796 /// ExternType::Func(_) => { /* ... */ } 797 /// _ => panic!("unexpected export type!"), 798 /// } 799 /// 800 /// # Ok(()) 801 /// # } 802 /// ``` 803 pub fn get_export(&self, name: &str) -> Option<ExternType> { 804 let module = self.compiled_module().module(); 805 let entity_index = module.exports.get(name)?; 806 Some(ExternType::from_wasmtime( 807 self.engine(), 808 self.types(), 809 &module.type_of(*entity_index), 810 )) 811 } 812 813 /// Looks up an export in this [`Module`] by name to get its index. 814 /// 815 /// This function will return the index of an export with the given name. This can be useful 816 /// to avoid the cost of looking up the export by name multiple times. Instead the 817 /// [`ModuleExport`] can be stored and used to look up the export on the 818 /// [`Instance`](crate::Instance) later. 819 pub fn get_export_index(&self, name: &str) -> Option<ModuleExport> { 820 let compiled_module = self.compiled_module(); 821 let module = compiled_module.module(); 822 module 823 .exports 824 .get_full(name) 825 .map(|(export_name_index, _, &entity)| ModuleExport { 826 module: self.id(), 827 entity, 828 export_name_index, 829 }) 830 } 831 832 /// Returns the [`Engine`] that this [`Module`] was compiled by. 833 pub fn engine(&self) -> &Engine { 834 &self.inner.engine 835 } 836 837 /// Returns a summary of the resources required to instantiate this 838 /// [`Module`]. 839 /// 840 /// Potential uses of the returned information: 841 /// 842 /// * Determining whether your pooling allocator configuration supports 843 /// instantiating this module. 844 /// 845 /// * Deciding how many of which `Module` you want to instantiate within a 846 /// fixed amount of resources, e.g. determining whether to create 5 847 /// instances of module X or 10 instances of module Y. 848 /// 849 /// # Example 850 /// 851 /// ``` 852 /// # fn main() -> wasmtime::Result<()> { 853 /// use wasmtime::{Config, Engine, Module}; 854 /// 855 /// let mut config = Config::new(); 856 /// config.wasm_multi_memory(true); 857 /// let engine = Engine::new(&config)?; 858 /// 859 /// let module = Module::new(&engine, r#" 860 /// (module 861 /// ;; Import a memory. Doesn't count towards required resources. 862 /// (import "a" "b" (memory 10)) 863 /// ;; Define two local memories. These count towards the required 864 /// ;; resources. 865 /// (memory 1) 866 /// (memory 6) 867 /// ) 868 /// "#)?; 869 /// 870 /// let resources = module.resources_required(); 871 /// 872 /// // Instantiating the module will require allocating two memories, and 873 /// // the maximum initial memory size is six Wasm pages. 874 /// assert_eq!(resources.num_memories, 2); 875 /// assert_eq!(resources.max_initial_memory_size, Some(6)); 876 /// 877 /// // The module doesn't need any tables. 878 /// assert_eq!(resources.num_tables, 0); 879 /// assert_eq!(resources.max_initial_table_size, None); 880 /// # Ok(()) } 881 /// ``` 882 pub fn resources_required(&self) -> ResourcesRequired { 883 let em = self.env_module(); 884 let num_memories = u32::try_from(em.memory_plans.len() - em.num_imported_memories).unwrap(); 885 let max_initial_memory_size = em 886 .memory_plans 887 .values() 888 .skip(em.num_imported_memories) 889 .map(|plan| plan.memory.minimum) 890 .max(); 891 let num_tables = u32::try_from(em.table_plans.len() - em.num_imported_tables).unwrap(); 892 let max_initial_table_size = em 893 .table_plans 894 .values() 895 .skip(em.num_imported_tables) 896 .map(|plan| plan.table.minimum) 897 .max(); 898 ResourcesRequired { 899 num_memories, 900 max_initial_memory_size, 901 num_tables, 902 max_initial_table_size, 903 } 904 } 905 906 /// Returns the `ModuleInner` cast as `ModuleRuntimeInfo` for use 907 /// by the runtime. 908 pub(crate) fn runtime_info(&self) -> Arc<dyn crate::runtime::vm::ModuleRuntimeInfo> { 909 // N.B.: this needs to return a clone because we cannot 910 // statically cast the &Arc<ModuleInner> to &Arc<dyn Trait...>. 911 self.inner.clone() 912 } 913 914 pub(crate) fn module_info(&self) -> &dyn crate::runtime::vm::ModuleInfo { 915 &*self.inner 916 } 917 918 /// Returns the range of bytes in memory where this module's compilation 919 /// image resides. 920 /// 921 /// The compilation image for a module contains executable code, data, debug 922 /// information, etc. This is roughly the same as the `Module::serialize` 923 /// but not the exact same. 924 /// 925 /// The range of memory reported here is exposed to allow low-level 926 /// manipulation of the memory in platform-specific manners such as using 927 /// `mlock` to force the contents to be paged in immediately or keep them 928 /// paged in after they're loaded. 929 /// 930 /// It is not safe to modify the memory in this range, nor is it safe to 931 /// modify the protections of memory in this range. 932 pub fn image_range(&self) -> Range<*const u8> { 933 self.compiled_module().mmap().image_range() 934 } 935 936 /// Force initialization of copy-on-write images to happen here-and-now 937 /// instead of when they're requested during first instantiation. 938 /// 939 /// When [copy-on-write memory 940 /// initialization](crate::Config::memory_init_cow) is enabled then Wasmtime 941 /// will lazily create the initialization image for a module. This method 942 /// can be used to explicitly dictate when this initialization happens. 943 /// 944 /// Note that this largely only matters on Linux when memfd is used. 945 /// Otherwise the copy-on-write image typically comes from disk and in that 946 /// situation the creation of the image is trivial as the image is always 947 /// sourced from disk. On Linux, though, when memfd is used a memfd is 948 /// created and the initialization image is written to it. 949 /// 950 /// Also note that this method is not required to be called, it's available 951 /// as a performance optimization if required but is otherwise handled 952 /// automatically. 953 pub fn initialize_copy_on_write_image(&self) -> Result<()> { 954 self.inner.memory_images()?; 955 Ok(()) 956 } 957 958 /// Get the map from `.text` section offsets to Wasm binary offsets for this 959 /// module. 960 /// 961 /// Each entry is a (`.text` section offset, Wasm binary offset) pair. 962 /// 963 /// Entries are yielded in order of `.text` section offset. 964 /// 965 /// Some entries are missing a Wasm binary offset. This is for code that is 966 /// not associated with any single location in the Wasm binary, or for when 967 /// source information was optimized away. 968 /// 969 /// Not every module has an address map, since address map generation can be 970 /// turned off on `Config`. 971 /// 972 /// There is not an entry for every `.text` section offset. Every offset 973 /// after an entry's offset, but before the next entry's offset, is 974 /// considered to map to the same Wasm binary offset as the original 975 /// entry. For example, the address map will not contain the following 976 /// sequence of entries: 977 /// 978 /// ```ignore 979 /// [ 980 /// // ... 981 /// (10, Some(42)), 982 /// (11, Some(42)), 983 /// (12, Some(42)), 984 /// (13, Some(43)), 985 /// // ... 986 /// ] 987 /// ``` 988 /// 989 /// Instead, it will drop the entries for offsets `11` and `12` since they 990 /// are the same as the entry for offset `10`: 991 /// 992 /// ```ignore 993 /// [ 994 /// // ... 995 /// (10, Some(42)), 996 /// (13, Some(43)), 997 /// // ... 998 /// ] 999 /// ``` 1000 pub fn address_map<'a>(&'a self) -> Option<impl Iterator<Item = (usize, Option<u32>)> + 'a> { 1001 Some( 1002 wasmtime_environ::iterate_address_map( 1003 self.code_object().code_memory().address_map_data(), 1004 )? 1005 .map(|(offset, file_pos)| (offset as usize, file_pos.file_offset())), 1006 ) 1007 } 1008 1009 /// Get this module's code object's `.text` section, containing its compiled 1010 /// executable code. 1011 pub fn text(&self) -> &[u8] { 1012 self.code_object().code_memory().text() 1013 } 1014 1015 /// Get the locations of functions in this module's `.text` section. 1016 /// 1017 /// Each function's location is a (`.text` section offset, length) pair. 1018 pub fn function_locations<'a>(&'a self) -> impl ExactSizeIterator<Item = (usize, usize)> + 'a { 1019 self.compiled_module().finished_functions().map(|(f, _)| { 1020 let loc = self.compiled_module().func_loc(f); 1021 (loc.start as usize, loc.length as usize) 1022 }) 1023 } 1024 1025 pub(crate) fn id(&self) -> CompiledModuleId { 1026 self.inner.module.unique_id() 1027 } 1028 } 1029 1030 impl ModuleInner { 1031 fn memory_images(&self) -> Result<Option<&ModuleMemoryImages>> { 1032 let images = self 1033 .memory_images 1034 .get_or_try_init(|| memory_images(&self.engine, &self.module))? 1035 .as_ref(); 1036 Ok(images) 1037 } 1038 } 1039 1040 impl Drop for ModuleInner { 1041 fn drop(&mut self) { 1042 // When a `Module` is being dropped that means that it's no longer 1043 // present in any `Store` and it's additionally not longer held by any 1044 // embedder. Take this opportunity to purge any lingering instantiations 1045 // within a pooling instance allocator, if applicable. 1046 self.engine 1047 .allocator() 1048 .purge_module(self.module.unique_id()); 1049 } 1050 } 1051 1052 /// Describes the location of an export in a module. 1053 #[derive(Copy, Clone)] 1054 pub struct ModuleExport { 1055 /// The module that this export is defined in. 1056 pub(crate) module: CompiledModuleId, 1057 /// A raw index into the wasm module. 1058 pub(crate) entity: EntityIndex, 1059 /// The index of the export name. 1060 pub(crate) export_name_index: usize, 1061 } 1062 1063 fn _assert_send_sync() { 1064 fn _assert<T: Send + Sync>() {} 1065 _assert::<Module>(); 1066 } 1067 1068 impl crate::runtime::vm::ModuleRuntimeInfo for ModuleInner { 1069 fn module(&self) -> &Arc<wasmtime_environ::Module> { 1070 self.module.module() 1071 } 1072 1073 fn engine_type_index( 1074 &self, 1075 module_index: wasmtime_environ::ModuleInternedTypeIndex, 1076 ) -> VMSharedTypeIndex { 1077 self.code 1078 .signatures() 1079 .shared_type(module_index) 1080 .expect("bad module-level interned type index") 1081 } 1082 1083 fn function(&self, index: DefinedFuncIndex) -> NonNull<VMWasmCallFunction> { 1084 let ptr = self 1085 .module 1086 .finished_function(index) 1087 .as_ptr() 1088 .cast::<VMWasmCallFunction>() 1089 .cast_mut(); 1090 NonNull::new(ptr).unwrap() 1091 } 1092 1093 fn native_to_wasm_trampoline( 1094 &self, 1095 index: DefinedFuncIndex, 1096 ) -> Option<NonNull<VMNativeCallFunction>> { 1097 let ptr = self 1098 .module 1099 .native_to_wasm_trampoline(index)? 1100 .as_ptr() 1101 .cast::<VMNativeCallFunction>() 1102 .cast_mut(); 1103 Some(NonNull::new(ptr).unwrap()) 1104 } 1105 1106 fn array_to_wasm_trampoline(&self, index: DefinedFuncIndex) -> Option<VMArrayCallFunction> { 1107 let ptr = self.module.array_to_wasm_trampoline(index)?.as_ptr(); 1108 Some(unsafe { mem::transmute::<*const u8, VMArrayCallFunction>(ptr) }) 1109 } 1110 1111 fn wasm_to_native_trampoline( 1112 &self, 1113 signature: VMSharedTypeIndex, 1114 ) -> Option<NonNull<VMWasmCallFunction>> { 1115 log::trace!("Looking up trampoline for {signature:?}"); 1116 let trampoline_shared_ty = self.engine.signatures().trampoline_type(signature); 1117 let trampoline_module_ty = self 1118 .code 1119 .signatures() 1120 .trampoline_type(trampoline_shared_ty)?; 1121 debug_assert!(self 1122 .engine 1123 .signatures() 1124 .borrow( 1125 self.code 1126 .signatures() 1127 .shared_type(trampoline_module_ty) 1128 .unwrap() 1129 ) 1130 .unwrap() 1131 .unwrap_func() 1132 .is_trampoline_type()); 1133 1134 let ptr = self 1135 .module 1136 .wasm_to_native_trampoline(trampoline_module_ty) 1137 .as_ptr() 1138 .cast::<VMWasmCallFunction>() 1139 .cast_mut(); 1140 Some(NonNull::new(ptr).unwrap()) 1141 } 1142 1143 fn memory_image(&self, memory: DefinedMemoryIndex) -> Result<Option<&Arc<MemoryImage>>> { 1144 let images = self.memory_images()?; 1145 Ok(images.and_then(|images| images.get_memory_image(memory))) 1146 } 1147 1148 fn unique_id(&self) -> Option<CompiledModuleId> { 1149 Some(self.module.unique_id()) 1150 } 1151 1152 fn wasm_data(&self) -> &[u8] { 1153 self.module.code_memory().wasm_data() 1154 } 1155 1156 fn type_ids(&self) -> &[VMSharedTypeIndex] { 1157 self.code.signatures().as_module_map().values().as_slice() 1158 } 1159 1160 fn offsets(&self) -> &VMOffsets<HostPtr> { 1161 &self.offsets 1162 } 1163 } 1164 1165 impl crate::runtime::vm::ModuleInfo for ModuleInner { 1166 fn lookup_stack_map(&self, pc: usize) -> Option<&wasmtime_environ::StackMap> { 1167 let text_offset = pc - self.module.text().as_ptr() as usize; 1168 let (index, func_offset) = self.module.func_by_text_offset(text_offset)?; 1169 let info = self.module.wasm_func_info(index); 1170 1171 // Do a binary search to find the stack map for the given offset. 1172 let index = match info 1173 .stack_maps 1174 .binary_search_by_key(&func_offset, |i| i.code_offset) 1175 { 1176 // Found it. 1177 Ok(i) => i, 1178 1179 // No stack map associated with this PC. 1180 // 1181 // Because we know we are in Wasm code, and we must be at some kind 1182 // of call/safepoint, then the Cranelift backend must have avoided 1183 // emitting a stack map for this location because no refs were live. 1184 Err(_) => return None, 1185 }; 1186 1187 Some(&info.stack_maps[index].stack_map) 1188 } 1189 } 1190 1191 /// A barebones implementation of ModuleRuntimeInfo that is useful for 1192 /// cases where a purpose-built environ::Module is used and a full 1193 /// CompiledModule does not exist (for example, for tests or for the 1194 /// default-callee instance). 1195 pub(crate) struct BareModuleInfo { 1196 module: Arc<wasmtime_environ::Module>, 1197 one_signature: Option<VMSharedTypeIndex>, 1198 offsets: VMOffsets<HostPtr>, 1199 } 1200 1201 impl BareModuleInfo { 1202 pub(crate) fn empty(module: Arc<wasmtime_environ::Module>) -> Self { 1203 BareModuleInfo::maybe_imported_func(module, None) 1204 } 1205 1206 pub(crate) fn maybe_imported_func( 1207 module: Arc<wasmtime_environ::Module>, 1208 one_signature: Option<VMSharedTypeIndex>, 1209 ) -> Self { 1210 BareModuleInfo { 1211 offsets: VMOffsets::new(HostPtr, &module), 1212 module, 1213 one_signature, 1214 } 1215 } 1216 1217 pub(crate) fn into_traitobj(self) -> Arc<dyn crate::runtime::vm::ModuleRuntimeInfo> { 1218 Arc::new(self) 1219 } 1220 } 1221 1222 impl crate::runtime::vm::ModuleRuntimeInfo for BareModuleInfo { 1223 fn module(&self) -> &Arc<wasmtime_environ::Module> { 1224 &self.module 1225 } 1226 1227 fn engine_type_index( 1228 &self, 1229 _module_index: wasmtime_environ::ModuleInternedTypeIndex, 1230 ) -> VMSharedTypeIndex { 1231 unreachable!() 1232 } 1233 1234 fn function(&self, _index: DefinedFuncIndex) -> NonNull<VMWasmCallFunction> { 1235 unreachable!() 1236 } 1237 1238 fn array_to_wasm_trampoline(&self, _index: DefinedFuncIndex) -> Option<VMArrayCallFunction> { 1239 unreachable!() 1240 } 1241 1242 fn native_to_wasm_trampoline( 1243 &self, 1244 _index: DefinedFuncIndex, 1245 ) -> Option<NonNull<VMNativeCallFunction>> { 1246 unreachable!() 1247 } 1248 1249 fn wasm_to_native_trampoline( 1250 &self, 1251 _signature: VMSharedTypeIndex, 1252 ) -> Option<NonNull<VMWasmCallFunction>> { 1253 unreachable!() 1254 } 1255 1256 fn memory_image(&self, _memory: DefinedMemoryIndex) -> Result<Option<&Arc<MemoryImage>>> { 1257 Ok(None) 1258 } 1259 1260 fn unique_id(&self) -> Option<CompiledModuleId> { 1261 None 1262 } 1263 1264 fn wasm_data(&self) -> &[u8] { 1265 &[] 1266 } 1267 1268 fn type_ids(&self) -> &[VMSharedTypeIndex] { 1269 match &self.one_signature { 1270 Some(id) => core::slice::from_ref(id), 1271 None => &[], 1272 } 1273 } 1274 1275 fn offsets(&self) -> &VMOffsets<HostPtr> { 1276 &self.offsets 1277 } 1278 } 1279 1280 /// Helper method to construct a `ModuleMemoryImages` for an associated 1281 /// `CompiledModule`. 1282 fn memory_images(engine: &Engine, module: &CompiledModule) -> Result<Option<ModuleMemoryImages>> { 1283 // If initialization via copy-on-write is explicitly disabled in 1284 // configuration then this path is skipped entirely. 1285 if !engine.config().memory_init_cow { 1286 return Ok(None); 1287 } 1288 1289 // ... otherwise logic is delegated to the `ModuleMemoryImages::new` 1290 // constructor. 1291 let mmap = if engine.config().force_memory_init_memfd { 1292 None 1293 } else { 1294 Some(module.mmap()) 1295 }; 1296 ModuleMemoryImages::new(module.module(), module.code_memory().wasm_data(), mmap) 1297 } 1298 1299 #[cfg(test)] 1300 mod tests { 1301 use crate::{Engine, Module}; 1302 use wasmtime_environ::MemoryInitialization; 1303 1304 #[test] 1305 fn cow_on_by_default() { 1306 let engine = Engine::default(); 1307 let module = Module::new( 1308 &engine, 1309 r#" 1310 (module 1311 (memory 1) 1312 (data (i32.const 100) "abcd") 1313 ) 1314 "#, 1315 ) 1316 .unwrap(); 1317 1318 let init = &module.env_module().memory_initialization; 1319 assert!(matches!(init, MemoryInitialization::Static { .. })); 1320 } 1321 } 1322