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