MCPcopy Create free account
hub / github.com/bytecodealliance/wasmtime / load_module

Method load_module

src/common.rs:194–259  ·  view source on GitHub ↗
(
        &self,
        engine: &Engine,
        path: &Path,
        preloaded_bytes: Option<&[u8]>,
    )

Source from the content-addressed store, hash-verified

192 }
193
194 pub fn load_module(
195 &self,
196 engine: &Engine,
197 path: &Path,
198 preloaded_bytes: Option<&[u8]>,
199 ) -> Result<RunTarget> {
200 let path = match path.to_str() {
201 #[cfg(unix)]
202 Some("-") => "/dev/stdin".as_ref(),
203 _ => path,
204 };
205 if let Some(bytes) = preloaded_bytes {
206 self.load_module_contents(
207 engine,
208 path,
209 &bytes,
210 || unsafe { Module::deserialize(engine, &bytes) },
211 #[cfg(feature = "component-model")]
212 || unsafe { Component::deserialize(engine, &bytes) },
213 )
214 } else {
215 let file =
216 File::open(path).with_context(|| format!("failed to open wasm module {path:?}"))?;
217
218 // First attempt to load the module as an mmap. If this succeeds then
219 // detection can be done with the contents of the mmap and if a
220 // precompiled module is detected then `deserialize_file` can be used
221 // which is a slightly more optimal version than `deserialize` since we
222 // can leave most of the bytes on disk until they're referenced.
223 //
224 // If the mmap fails, for example if stdin is a pipe, then fall back to
225 // `std::fs::read` to load the contents. At that point precompiled
226 // modules must go through the `deserialize` functions.
227 //
228 // Note that this has the unfortunate side effect for precompiled
229 // modules on disk that they're opened once to detect what they are and
230 // then again internally in Wasmtime as part of the `deserialize_file`
231 // API. Currently there's no way to pass the `MmapVec` here through to
232 // Wasmtime itself (that'd require making `MmapVec` a public type, both
233 // which isn't ready to happen at this time). It's hoped though that
234 // opening a file twice isn't too bad in the grand scheme of things with
235 // respect to the CLI.
236 match wasmtime::_internal::MmapVec::from_file(file) {
237 Ok(map) => self.load_module_contents(
238 engine,
239 path,
240 &map,
241 || unsafe { Module::deserialize_file(engine, path) },
242 #[cfg(feature = "component-model")]
243 || unsafe { Component::deserialize_file(engine, path) },
244 ),
245 Err(_) => {
246 let bytes = std::fs::read(path)
247 .with_context(|| format!("failed to read file: {}", path.display()))?;
248 self.load_module_contents(
249 engine,
250 path,
251 &bytes,

Callers 5

executeMethod · 0.80
serve_under_debuggerMethod · 0.80
serveMethod · 0.80
executeMethod · 0.80
instantiate_and_runMethod · 0.80

Calls 6

to_strMethod · 0.80
load_module_contentsMethod · 0.80
with_contextMethod · 0.80
deserializeFunction · 0.50
readFunction · 0.50
as_refMethod · 0.45

Tested by

no test coverage detected