Skip to main content

wasmer_cli/commands/run/
mod.rs

1#![allow(missing_docs, unused)]
2
3mod capabilities;
4mod package_source;
5mod runtime;
6mod target;
7mod wasi;
8
9use std::{
10    borrow::Cow,
11    collections::{BTreeMap, hash_map::DefaultHasher},
12    fmt::{Binary, Display},
13    fs::File,
14    hash::{BuildHasherDefault, Hash, Hasher},
15    io::{ErrorKind, LineWriter, Read, Write},
16    net::SocketAddr,
17    path::{Path, PathBuf},
18    str::FromStr,
19    sync::{Arc, Mutex},
20    time::{Duration, SystemTime, UNIX_EPOCH},
21};
22
23use anyhow::{Context, Error, anyhow, bail};
24use clap::{Parser, ValueEnum};
25use colored::Colorize;
26use futures::future::BoxFuture;
27use indicatif::{MultiProgress, ProgressBar};
28use once_cell::sync::Lazy;
29use tempfile::NamedTempFile;
30use url::Url;
31#[cfg(feature = "sys")]
32use wasmer::sys::NativeEngineExt;
33use wasmer::{
34    AsStoreMut, DeserializeError, Engine, Function, Imports, Instance, Module, RuntimeError, Store,
35    Type, TypedFunction, Value, wat2wasm,
36};
37
38use wasmer_types::{Features, target::Target};
39
40#[cfg(feature = "compiler")]
41use wasmer_compiler::ArtifactBuild;
42use wasmer_config::package::PackageSource;
43use wasmer_package::utils::from_disk;
44use wasmer_types::ModuleHash;
45
46#[cfg(feature = "journal")]
47use wasmer_wasix::journal::{LogFileJournal, SnapshotTrigger};
48use wasmer_wasix::{
49    Runtime, SpawnError, WasiError,
50    bin_factory::{BinaryPackage, BinaryPackageCommand},
51    journal::CompactingLogFileJournal,
52    runners::{
53        MappedCommand, MappedDirectory, Runner,
54        wasi::{RuntimeOrEngine, WasiRunner},
55    },
56    runtime::{
57        ModuleInput, OverriddenRuntime,
58        module_cache::{CacheError, HashedModuleData},
59        package_loader::PackageLoader,
60        resolver::QueryError,
61        task_manager::VirtualTaskManagerExt,
62    },
63};
64use webc::Container;
65use webc::metadata::Manifest;
66
67use crate::{
68    backend::RuntimeOptions,
69    commands::run::{target::TargetOnDisk, wasi::Wasi},
70    config::WasmerEnv,
71    error::PrettyError,
72    logging::Output,
73};
74
75use self::{
76    package_source::CliPackageSource, runtime::MonitoringRuntime, target::ExecutableTarget,
77};
78
79const TICK: Duration = Duration::from_millis(250);
80
81/// The unstable `wasmer run` subcommand.
82#[derive(Debug, Parser)]
83pub struct Run {
84    #[clap(flatten)]
85    env: WasmerEnv,
86    #[clap(flatten)]
87    rt: RuntimeOptions,
88    #[clap(flatten)]
89    wasi: crate::commands::run::Wasi,
90    /// Set the default stack size (default is 1048576)
91    #[clap(long = "stack-size")]
92    stack_size: Option<usize>,
93    /// The entrypoint module for webc packages.
94    #[clap(short, long, aliases = &["command", "command-name"])]
95    entrypoint: Option<String>,
96    /// The function to invoke.
97    #[clap(short, long)]
98    invoke: Option<String>,
99    /// Generate a coredump at this path if a WebAssembly trap occurs
100    #[clap(name = "COREDUMP_PATH", long)]
101    coredump_on_trap: Option<PathBuf>,
102    /// Enable experimental N-API imports for modules that require them
103    #[clap(long = "experimental-napi")]
104    experimental_napi: bool,
105    /// The file, URL, or package to run.
106    #[clap(value_parser = CliPackageSource::infer)]
107    input: CliPackageSource,
108    /// Command-line arguments passed to the package
109    args: Vec<String>,
110}
111
112impl Run {
113    #[cfg(feature = "napi-v8")]
114    fn module_needs_napi(module: &Module) -> bool {
115        let (napi_version, napi_extension_version) = wasmer_napi::module_needs_napi(module);
116        napi_version.is_some() || napi_extension_version.is_some()
117    }
118
119    #[cfg(feature = "napi-v8")]
120    fn maybe_wrap_runtime_with_napi(
121        &self,
122        module: &Module,
123        runtime: Arc<dyn Runtime + Send + Sync>,
124    ) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
125        use anyhow::ensure;
126
127        if !Self::module_needs_napi(module) {
128            return Ok(runtime);
129        }
130        ensure!(
131            self.experimental_napi,
132            "This module imports N-API. Re-run with '--experimental-napi' to enable the experimental N-API runtime."
133        );
134
135        let hooks = wasmer_napi::NapiCtx::default().runtime_hooks();
136        Ok(Arc::new(
137            OverriddenRuntime::new(runtime).with_instantiation_hook(hooks),
138        ))
139    }
140
141    #[cfg(feature = "napi-v8")]
142    fn configure_wasi_runner_for_napi(&self, module: &Module, runner: &mut WasiRunner) {
143        if Self::module_needs_napi(module) {
144            runner
145                .capabilities_mut()
146                .threading
147                .enable_asynchronous_threading = false;
148        }
149    }
150
151    #[cfg(not(feature = "napi-v8"))]
152    fn maybe_wrap_runtime_with_napi(
153        &self,
154        _module: &Module,
155        runtime: Arc<dyn Runtime + Send + Sync>,
156    ) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
157        Ok(runtime)
158    }
159
160    #[cfg(not(feature = "napi-v8"))]
161    fn configure_wasi_runner_for_napi(&self, _module: &Module, _runner: &mut WasiRunner) {}
162
163    #[cfg(feature = "wasm-c-api")]
164    fn module_uses_wasm_c_api(module: &Module) -> bool {
165        wasmer_c_api_imports::module_wasm_c_api_version_used(module).is_some()
166    }
167
168    #[cfg(feature = "wasm-c-api")]
169    fn maybe_wrap_runtime_with_wasm_c_api(
170        &self,
171        module: &Module,
172        runtime: Arc<dyn Runtime + Send + Sync>,
173    ) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
174        maybe_wrap_runtime_with_wasm_c_api(module, runtime)
175    }
176
177    #[cfg(not(feature = "wasm-c-api"))]
178    fn maybe_wrap_runtime_with_wasm_c_api(
179        &self,
180        _module: &Module,
181        runtime: Arc<dyn Runtime + Send + Sync>,
182    ) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
183        Ok(runtime)
184    }
185
186    fn maybe_wrap_runtime_for_module(
187        &self,
188        module: &Module,
189        runtime: Arc<dyn Runtime + Send + Sync>,
190    ) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
191        let runtime = self.maybe_wrap_runtime_with_napi(module, runtime)?;
192        self.maybe_wrap_runtime_with_wasm_c_api(module, runtime)
193    }
194
195    #[cfg(any(feature = "napi-v8", feature = "wasm-c-api"))]
196    fn resolve_wasi_command_module(
197        &self,
198        command_name: &str,
199        pkg: &BinaryPackage,
200        runtime: &Arc<dyn Runtime + Send + Sync>,
201    ) -> Result<Module, Error> {
202        let cmd = pkg.get_command(command_name).with_context(|| {
203            format!("Unable to get metadata for the \"{command_name}\" command")
204        })?;
205        Ok(runtime.resolve_module_sync(ModuleInput::Command(Cow::Borrowed(cmd)), None, None)?)
206    }
207
208    pub fn execute(self, output: Output) -> ! {
209        let result = self.execute_inner(output);
210        exit_with_wasi_exit_code(result);
211    }
212
213    #[tracing::instrument(level = "debug", name = "wasmer_run", skip_all)]
214    fn execute_inner(mut self, output: Output) -> Result<(), Error> {
215        self.print_option_warnings();
216
217        let pb = ProgressBar::new_spinner();
218        pb.set_draw_target(output.draw_target());
219        pb.enable_steady_tick(TICK);
220
221        pb.set_message("Initializing the WebAssembly VM");
222
223        let runtime = tokio::runtime::Builder::new_multi_thread()
224            .enable_all()
225            .build()?;
226        let handle = runtime.handle().clone();
227
228        // Check for the preferred webc version.
229        // Default to v3.
230        let webc_version_var = std::env::var("WASMER_WEBC_VERSION");
231        let preferred_webc_version = match webc_version_var.as_deref() {
232            Ok("2") => webc::Version::V2,
233            Ok("3") | Err(_) => webc::Version::V3,
234            Ok(other) => {
235                bail!("unknown webc version: '{other}'");
236            }
237        };
238
239        let _guard = handle.enter();
240
241        // Get the input file path
242        let mut wasm_bytes: Option<Vec<u8>> = None;
243
244        // Try to detect WebAssembly features before selecting a backend
245        tracing::info!("Input source: {:?}", self.input);
246        if let CliPackageSource::File(path) = &self.input {
247            tracing::info!("Input file path: {}", path.display());
248
249            // Try to read and detect any file that exists, regardless of extension
250            let target = TargetOnDisk::from_file(path);
251            if let Ok(target) = target {
252                match target {
253                    TargetOnDisk::WebAssemblyBinary => {
254                        if let Ok(data) = std::fs::read(path) {
255                            wasm_bytes = Some(data);
256                        } else {
257                            tracing::info!("Failed to read file: {}", path.display());
258                        }
259                    }
260                    TargetOnDisk::Wat => match std::fs::read(path) {
261                        Ok(data) => match wat2wasm(&data) {
262                            Ok(wasm) => {
263                                wasm_bytes = Some(wasm.to_vec());
264                            }
265                            Err(e) => {
266                                tracing::info!(
267                                    "Failed to convert WAT to Wasm for {}: {e}",
268                                    path.display()
269                                );
270                            }
271                        },
272                        Err(e) => {
273                            tracing::info!("Failed to read WAT file {}: {e}", path.display());
274                        }
275                    },
276                    _ => {}
277                }
278            } else {
279                tracing::info!(
280                    "Failed to read file for feature detection: {}",
281                    path.display()
282                );
283            }
284        } else {
285            tracing::info!("Input is not a file, skipping WebAssembly feature detection");
286        }
287
288        // Get engine with feature-based backend selection if possible
289        let mut engine = match &wasm_bytes {
290            Some(wasm_bytes) => {
291                tracing::info!("Attempting to detect WebAssembly features from binary");
292
293                self.rt
294                    .get_engine_for_module(wasm_bytes, &Target::default())?
295            }
296            None => {
297                // No WebAssembly file available for analysis, check if we have a webc package
298                if let CliPackageSource::Package(pkg_source) = &self.input {
299                    tracing::info!("Checking package for WebAssembly features: {}", pkg_source);
300                    self.rt.get_engine(&Target::default())?
301                } else {
302                    tracing::info!("No feature detection possible, using default engine");
303                    self.rt.get_engine(&Target::default())?
304                }
305            }
306        };
307
308        let engine_kind = engine.deterministic_id();
309        tracing::info!("Executing on backend {engine_kind:?}");
310
311        #[cfg(feature = "sys")]
312        if engine.is_sys()
313            && let Some(stack_size) = self.stack_size
314        {
315            wasmer_vm::set_stack_size(stack_size);
316        }
317
318        let engine = engine.clone();
319
320        let runtime = self.wasi.prepare_runtime(
321            engine,
322            &self.env,
323            &capabilities::get_capability_cache_path(&self.env, &self.input)?,
324            runtime,
325            preferred_webc_version,
326            self.rt.compiler_debug_dir.is_some(),
327        )?;
328
329        // This is a slow operation, so let's temporarily wrap the runtime with
330        // something that displays progress
331        let monitoring_runtime = Arc::new(MonitoringRuntime::new(
332            runtime,
333            pb.clone(),
334            output.is_quiet_or_no_tty(),
335        ));
336        let runtime: Arc<dyn Runtime + Send + Sync> = monitoring_runtime.runtime.clone();
337        let monitoring_runtime: Arc<dyn Runtime + Send + Sync> = monitoring_runtime;
338
339        let target = self.input.resolve_target(&monitoring_runtime, &pb)?;
340
341        if let ExecutableTarget::Package(ref pkg) = target {
342            self.wasi
343                .volumes
344                .extend(pkg.additional_host_mapped_directories.clone());
345        }
346
347        pb.finish_and_clear();
348
349        // push the TTY state so we can restore it after the program finishes
350        let tty = runtime.tty().map(|tty| tty.tty_get());
351
352        let result = {
353            match target {
354                ExecutableTarget::WebAssembly {
355                    module,
356                    module_hash,
357                    path,
358                } => self.execute_wasm(&path, module, module_hash, runtime.clone()),
359                ExecutableTarget::Package(pkg) => {
360                    // Check if we should update the engine based on the WebC package features
361                    if let Some(cmd) = pkg.get_entrypoint_command()
362                        && let Some(features) = cmd.wasm_features()
363                    {
364                        // Get the right engine for these features
365                        let backends = self.rt.get_available_backends()?;
366                        let available_engines = backends
367                            .iter()
368                            .map(|b| b.to_string())
369                            .collect::<Vec<_>>()
370                            .join(", ");
371
372                        let filtered_backends = RuntimeOptions::filter_backends_by_features(
373                            backends.clone(),
374                            &features,
375                            &Target::default(),
376                        );
377
378                        if let Some(backend) = filtered_backends.first() {
379                            let engine_id = backend.to_string();
380
381                            // Get a new engine that's compatible with the required features
382                            if let Ok(new_engine) = backend.get_engine(&Target::default(), &self.rt)
383                            {
384                                tracing::info!(
385                                    "The command '{}' requires to run the Wasm module with the features {:?}. The backends available are {}. Choosing {}.",
386                                    cmd.name(),
387                                    features,
388                                    available_engines,
389                                    engine_id
390                                );
391                                // Create a new runtime with the updated engine
392                                let capability_cache_path =
393                                    capabilities::get_capability_cache_path(
394                                        &self.env,
395                                        &self.input,
396                                    )?;
397                                let new_runtime = self.wasi.prepare_runtime(
398                                    new_engine,
399                                    &self.env,
400                                    &capability_cache_path,
401                                    tokio::runtime::Builder::new_multi_thread()
402                                        .enable_all()
403                                        .build()?,
404                                    preferred_webc_version,
405                                    self.rt.compiler_debug_dir.is_some(),
406                                )?;
407
408                                let new_runtime = Arc::new(MonitoringRuntime::new(
409                                    new_runtime,
410                                    pb.clone(),
411                                    output.is_quiet_or_no_tty(),
412                                ));
413                                return self.execute_webc(&pkg, new_runtime);
414                            }
415                        }
416                    }
417                    self.execute_webc(&pkg, monitoring_runtime)
418                }
419            }
420        };
421
422        // restore the TTY state as the execution may have changed it
423        if let Some(state) = tty
424            && let Some(tty) = runtime.tty()
425        {
426            tty.tty_set(state);
427        }
428
429        if let Err(e) = &result {
430            self.maybe_save_coredump(e);
431        }
432
433        result
434    }
435
436    #[tracing::instrument(skip_all)]
437    fn execute_wasm(
438        &self,
439        path: &Path,
440        module: Module,
441        module_hash: ModuleHash,
442        runtime: Arc<dyn Runtime + Send + Sync>,
443    ) -> Result<(), Error> {
444        if wasmer_wasix::is_wasi_module(&module) || wasmer_wasix::is_wasix_module(&module) {
445            self.execute_wasi_module(path, module, module_hash, runtime)
446        } else {
447            self.execute_pure_wasm_module(&module)
448        }
449    }
450
451    #[tracing::instrument(skip_all)]
452    fn execute_webc(
453        &self,
454        pkg: &BinaryPackage,
455        runtime: Arc<dyn Runtime + Send + Sync>,
456    ) -> Result<(), Error> {
457        let id = match self.entrypoint.as_deref() {
458            Some(cmd) => cmd,
459            None => pkg.infer_entrypoint()?,
460        };
461        let cmd = pkg
462            .get_command(id)
463            .with_context(|| format!("Unable to get metadata for the \"{id}\" command"))?;
464
465        let uses = self.load_injected_packages(&runtime)?;
466
467        if WasiRunner::can_run_command(cmd.metadata())? {
468            self.run_wasi(id, pkg, uses, runtime)
469        } else {
470            bail!(
471                "Unable to find a runner that supports \"{}\"",
472                cmd.metadata().runner
473            );
474        }
475    }
476
477    #[tracing::instrument(level = "debug", skip_all)]
478    fn load_injected_packages(
479        &self,
480        runtime: &Arc<dyn Runtime + Send + Sync>,
481    ) -> Result<Vec<BinaryPackage>, Error> {
482        let mut dependencies = Vec::new();
483
484        for name in &self.wasi.uses {
485            let specifier = name
486                .parse::<PackageSource>()
487                .with_context(|| format!("Unable to parse \"{name}\" as a package specifier"))?;
488            let pkg = {
489                let specifier = specifier.clone();
490                let inner_runtime = runtime.clone();
491                runtime
492                    .task_manager()
493                    .spawn_and_block_on(async move {
494                        BinaryPackage::from_registry(&specifier, inner_runtime.as_ref()).await
495                    })
496                    .with_context(|| format!("Unable to load \"{name}\""))??
497            };
498            dependencies.push(pkg);
499        }
500
501        Ok(dependencies)
502    }
503
504    fn run_wasi(
505        &self,
506        command_name: &str,
507        pkg: &BinaryPackage,
508        uses: Vec<BinaryPackage>,
509        runtime: Arc<dyn Runtime + Send + Sync>,
510    ) -> Result<(), Error> {
511        #[cfg(feature = "napi-v8")]
512        let (module, runtime) = {
513            let module = self.resolve_wasi_command_module(command_name, pkg, &runtime)?;
514            let runtime = self.maybe_wrap_runtime_for_module(&module, runtime)?;
515            (module, runtime)
516        };
517
518        #[cfg(all(not(feature = "napi-v8"), feature = "wasm-c-api"))]
519        let runtime = {
520            let module = self.resolve_wasi_command_module(command_name, pkg, &runtime)?;
521            self.maybe_wrap_runtime_for_module(&module, runtime)?
522        };
523
524        // Assume webcs are always WASIX
525        let mut runner = self.build_wasi_runner(&runtime, true)?;
526        #[cfg(feature = "napi-v8")]
527        self.configure_wasi_runner_for_napi(&module, &mut runner);
528        Runner::run_command(&mut runner, command_name, pkg, runtime)
529    }
530
531    #[tracing::instrument(skip_all)]
532    fn execute_pure_wasm_module(&self, module: &Module) -> Result<(), Error> {
533        /// The rest of the execution happens in the main thread, so we can create the
534        /// store here.
535        let mut store = self.rt.get_store()?;
536        let imports = Imports::default();
537        let instance = Instance::new(&mut store, module, &imports)
538            .context("Unable to instantiate the WebAssembly module")?;
539
540        let entry_function  = match &self.invoke {
541            Some(entry) => {
542                instance.exports
543                    .get_function(entry)
544                    .with_context(|| format!("The module doesn't export a function named \"{entry}\""))?
545            },
546            None => {
547                instance.exports.get_function("_start")
548                    .context("The module doesn't export a \"_start\" function. Either implement it or specify an entry function with --invoke")?
549            }
550        };
551
552        let result = invoke_function(&instance, &mut store, entry_function, &self.args)?;
553
554        match result {
555            Ok(return_values) => {
556                println!(
557                    "{}",
558                    return_values
559                        .iter()
560                        .map(|val| val.to_string())
561                        .collect::<Vec<String>>()
562                        .join(" ")
563                );
564                Ok(())
565            }
566            Err(err) => {
567                bail!("{}", err.display(&mut store));
568            }
569        }
570    }
571
572    fn build_wasi_runner(
573        &self,
574        runtime: &Arc<dyn Runtime + Send + Sync>,
575        is_wasix: bool,
576    ) -> Result<WasiRunner, anyhow::Error> {
577        let packages = self.load_injected_packages(runtime)?;
578
579        let mut runner = WasiRunner::new();
580
581        let (is_home_mapped, mapped_directories) = self.wasi.build_mapped_directories(is_wasix)?;
582
583        runner
584            .with_args(&self.args)
585            .with_injected_packages(packages)
586            .with_envs(self.wasi.env_vars.clone())
587            .with_mapped_host_commands(self.wasi.build_mapped_commands()?)
588            .with_mapped_directories(mapped_directories)
589            .with_home_mapped(is_home_mapped)
590            .with_forward_host_env(self.wasi.forward_host_env)
591            .with_capabilities(self.wasi.capabilities());
592
593        if let Some(cwd) = self.wasi.cwd.as_ref() {
594            if !cwd.starts_with("/") {
595                bail!("The argument to --cwd must be an absolute path");
596            }
597            runner.with_current_dir(cwd.clone());
598        }
599
600        if let Some(ref entry_function) = self.invoke {
601            runner.with_entry_function(entry_function);
602        }
603
604        #[cfg(feature = "journal")]
605        {
606            for trigger in self.wasi.snapshot_on.iter().cloned() {
607                runner.with_snapshot_trigger(trigger);
608            }
609            if self.wasi.snapshot_on.is_empty() && !self.wasi.writable_journals.is_empty() {
610                runner.with_default_snapshot_triggers();
611            }
612            if let Some(period) = self.wasi.snapshot_interval {
613                if self.wasi.writable_journals.is_empty() {
614                    return Err(anyhow::format_err!(
615                        "If you specify a snapshot interval then you must also specify a writable journal file"
616                    ));
617                }
618                runner.with_snapshot_interval(Duration::from_millis(period));
619            }
620            if self.wasi.stop_after_snapshot {
621                runner.with_stop_running_after_snapshot(true);
622            }
623            let (r, w) = self.wasi.build_journals()?;
624            for journal in r {
625                runner.with_read_only_journal(journal);
626            }
627            for journal in w {
628                runner.with_writable_journal(journal);
629            }
630            runner.with_skip_stdio_during_bootstrap(self.wasi.skip_stdio_during_bootstrap);
631        }
632
633        Ok(runner)
634    }
635
636    #[tracing::instrument(skip_all)]
637    fn execute_wasi_module(
638        &self,
639        wasm_path: &Path,
640        module: Module,
641        module_hash: ModuleHash,
642        runtime: Arc<dyn Runtime + Send + Sync>,
643    ) -> Result<(), Error> {
644        let program_name = wasm_path.display().to_string();
645        let runtime = self.maybe_wrap_runtime_for_module(&module, runtime)?;
646
647        let mut runner =
648            self.build_wasi_runner(&runtime, wasmer_wasix::is_wasix_module(&module))?;
649        self.configure_wasi_runner_for_napi(&module, &mut runner);
650        runner.run_wasm(
651            RuntimeOrEngine::Runtime(runtime),
652            &program_name,
653            module,
654            module_hash,
655        )
656    }
657
658    #[allow(unused_variables)]
659    fn maybe_save_coredump(&self, e: &Error) {
660        #[cfg(feature = "coredump")]
661        if let Some(coredump) = &self.coredump_on_trap
662            && let Err(e) = generate_coredump(e, self.input.to_string(), coredump)
663        {
664            tracing::warn!(
665                error = &*e as &dyn std::error::Error,
666                coredump_path=%coredump.display(),
667                "Unable to generate a coredump",
668            );
669        }
670    }
671
672    fn print_option_warnings(&self) {
673        if !self.wasi.mapped_dirs.is_empty() {
674            eprintln!(
675                "{}The `{}` option is deprecated and will be removed in the next major release. Please use `{}` instead.",
676                "warning: ".yellow(),
677                "--mapdir".yellow(),
678                "--volume".green()
679            );
680        }
681        if !self.wasi.pre_opened_directories.is_empty() {
682            eprintln!(
683                "{}The `{}` option is deprecated and will be removed in the next major release. Please use `{}` instead.",
684                "warning: ".yellow(),
685                "--dir".yellow(),
686                "--volume".green()
687            );
688        }
689    }
690}
691
692#[cfg(feature = "wasm-c-api")]
693fn maybe_wrap_runtime_with_wasm_c_api(
694    module: &Module,
695    runtime: Arc<dyn Runtime + Send + Sync>,
696) -> Result<Arc<dyn Runtime + Send + Sync>, Error> {
697    if !Run::module_uses_wasm_c_api(module) {
698        return Ok(runtime);
699    }
700
701    let runtime_for_resolver = runtime.clone();
702    let hooks =
703        wasmer_c_api_imports::WasmCapiRuntimeHooks::new().with_resolve_module_sync(move |bytes| {
704            runtime_for_resolver
705                .resolve_module_sync(ModuleInput::Bytes(Cow::Owned(bytes)), None, None)
706                .context("failed to resolve Wasm C API module")
707        });
708    Ok(Arc::new(
709        OverriddenRuntime::new(runtime).with_instantiation_hook(hooks),
710    ))
711}
712
713fn invoke_function(
714    instance: &Instance,
715    store: &mut Store,
716    func: &Function,
717    args: &[String],
718) -> anyhow::Result<Result<Box<[Value]>, RuntimeError>> {
719    let func_ty = func.ty(store);
720    let required_arguments = func_ty.params().len();
721    let provided_arguments = args.len();
722
723    anyhow::ensure!(
724        required_arguments == provided_arguments,
725        "Function expected {required_arguments} arguments, but received {provided_arguments}"
726    );
727
728    let invoke_args = args
729        .iter()
730        .zip(func_ty.params().iter())
731        .map(|(arg, param_type)| {
732            parse_value(arg, *param_type)
733                .with_context(|| format!("Unable to convert {arg:?} to {param_type:?}"))
734        })
735        .collect::<Result<Vec<_>, _>>()?;
736
737    Ok(func.call(store, &invoke_args))
738}
739
740fn parse_value(s: &str, ty: wasmer_types::Type) -> Result<Value, Error> {
741    let value = match ty {
742        Type::I32 => Value::I32(s.parse()?),
743        Type::I64 => Value::I64(s.parse()?),
744        Type::F32 => Value::F32(s.parse()?),
745        Type::F64 => Value::F64(s.parse()?),
746        Type::V128 => Value::V128(s.parse()?),
747        _ => bail!("There is no known conversion from {s:?} to {ty:?}"),
748    };
749    Ok(value)
750}
751
752#[cfg(feature = "coredump")]
753fn generate_coredump(err: &Error, source_name: String, coredump_path: &Path) -> Result<(), Error> {
754    let err: &wasmer::RuntimeError = match err.downcast_ref() {
755        Some(e) => e,
756        None => {
757            log::warn!("no runtime error found to generate coredump with");
758            return Ok(());
759        }
760    };
761
762    let mut coredump_builder =
763        wasm_coredump_builder::CoredumpBuilder::new().executable_name(&source_name);
764
765    let mut thread_builder = wasm_coredump_builder::ThreadBuilder::new().thread_name("main");
766
767    for frame in err.trace() {
768        let coredump_frame = wasm_coredump_builder::FrameBuilder::new()
769            .codeoffset(frame.func_offset() as u32)
770            .funcidx(frame.func_index())
771            .build();
772        thread_builder.add_frame(coredump_frame);
773    }
774
775    coredump_builder.add_thread(thread_builder.build());
776
777    let coredump = coredump_builder
778        .serialize()
779        .map_err(Error::msg)
780        .context("Coredump serializing failed")?;
781
782    std::fs::write(coredump_path, &coredump).with_context(|| {
783        format!(
784            "Unable to save the coredump to \"{}\"",
785            coredump_path.display()
786        )
787    })?;
788
789    Ok(())
790}
791
792/// Exit the current process, using the WASI exit code if the error contains
793/// one.
794fn exit_with_wasi_exit_code(result: Result<(), Error>) -> ! {
795    let exit_code = match result {
796        Ok(_) => 0,
797        Err(error) => {
798            match error.chain().find_map(get_exit_code) {
799                Some(exit_code) => exit_code.raw(),
800                None => {
801                    eprintln!("{:?}", PrettyError::new(error));
802                    // Something else happened
803                    1
804                }
805            }
806        }
807    };
808
809    std::io::stdout().flush().ok();
810    std::io::stderr().flush().ok();
811
812    std::process::exit(exit_code);
813}
814
815fn get_exit_code(
816    error: &(dyn std::error::Error + 'static),
817) -> Option<wasmer_wasix::types::wasi::ExitCode> {
818    if let Some(WasiError::Exit(exit_code)) = error.downcast_ref() {
819        return Some(*exit_code);
820    }
821    if let Some(error) = error.downcast_ref::<wasmer_wasix::WasiRuntimeError>() {
822        return error.as_exit_code();
823    }
824
825    None
826}
827
828#[cfg(all(test, feature = "wasm-c-api"))]
829mod tests {
830    use std::sync::Arc;
831
832    use super::*;
833    use wasmer_wasix::{
834        PluggableRuntime, WasiError, runtime::task_manager::tokio::TokioTaskManager,
835    };
836
837    fn wasm_c_api_guest() -> Vec<u8> {
838        wat2wasm(
839            br#"(module
840                (import "wasi_snapshot_preview1" "proc_exit" (func $proc_exit (param i32)))
841                (import "wasm_c_api_v0" "wasm_engine_new" (func $wasm_engine_new (result i32)))
842                (import "wasm_c_api_v0" "wasm_store_new" (func $wasm_store_new (param i32) (result i32)))
843                (import "wasm_c_api_v0" "wasm_module_validate" (func $wasm_module_validate (param i32 i32) (result i32)))
844                (import "wasm_c_api_v0" "wasm_module_new" (func $wasm_module_new (param i32 i32) (result i32)))
845
846                (memory (export "memory") 1)
847                (data (i32.const 16) "\08\00\00\00\20\00\00\00")
848                (data (i32.const 32) "\00asm\01\00\00\00")
849
850                (func (export "_start")
851                    (local $engine i32)
852                    (local $store i32)
853                    (local $module i32)
854
855                    (local.set $engine (call $wasm_engine_new))
856                    (if (i32.eqz (local.get $engine))
857                        (then (call $proc_exit (i32.const 10))))
858
859                    (local.set $store (call $wasm_store_new (local.get $engine)))
860                    (if (i32.eqz (local.get $store))
861                        (then (call $proc_exit (i32.const 11))))
862
863                    (if (i32.eqz (call $wasm_module_validate (local.get $store) (i32.const 16)))
864                        (then (call $proc_exit (i32.const 12))))
865
866                    (local.set $module (call $wasm_module_new (local.get $store) (i32.const 16)))
867                    (if (i32.eqz (local.get $module))
868                        (then (call $proc_exit (i32.const 13))))
869                )
870            )"#,
871        )
872        .expect("guest wat parses")
873        .into_owned()
874    }
875
876    #[test]
877    fn cli_wasm_c_api_runtime_wrapper_runs_wasix_guest() {
878        let wasm = wasm_c_api_guest();
879        let store = Store::default();
880        let module = Module::new(&store, &wasm).expect("guest module compiles");
881        assert!(Run::module_uses_wasm_c_api(&module));
882
883        let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
884            .enable_all()
885            .build()
886            .expect("tokio runtime starts");
887        let _guard = tokio_runtime.enter();
888        let mut base_runtime = PluggableRuntime::new(Arc::new(TokioTaskManager::new(
889            tokio_runtime.handle().clone(),
890        )));
891        base_runtime.set_engine(store.engine().clone());
892
893        let runtime = maybe_wrap_runtime_with_wasm_c_api(&module, Arc::new(base_runtime))
894            .expect("runtime wrapper is installed");
895        let mut import_store = runtime.new_store();
896        let mut import_store_mut = import_store.as_store_mut();
897        let (imports, _state) = runtime
898            .additional_imports(&module, &mut import_store_mut)
899            .expect("wasm c api imports are created");
900        assert!(imports.exists("wasm_c_api_v0", "wasm_engine_new"));
901
902        let result = WasiRunner::new().run_wasm(
903            RuntimeOrEngine::Runtime(runtime),
904            "wasm-c-api-cli-smoke",
905            module,
906            ModuleHash::new(&wasm),
907        );
908
909        match result {
910            Ok(()) => {}
911            Err(err) => {
912                if let Some(WasiError::Exit(code)) = err.downcast_ref::<WasiError>() {
913                    panic!("guest exited with status {code}");
914                }
915                panic!("guest failed: {err:?}");
916            }
917        }
918    }
919}