1 use anyhow::Result;
2 
3 #[cfg(not(target_os = "linux"))]
4 fn main() -> Result<()> {
5     eprintln!("This example only runs on Linux right now");
6     Ok(())
7 }
8 
9 #[cfg(target_os = "linux")]
10 fn main() -> Result<()> {
11     use anyhow::{anyhow, Context};
12     use libloading::os::unix::{Library, Symbol, RTLD_GLOBAL, RTLD_NOW};
13     use object::{Object, ObjectSymbol};
14     use std::io::Write;
15     use wasmtime::{Config, Engine};
16 
17     let mut args = std::env::args();
18     let _current_exe = args.next();
19     let triple = args
20         .next()
21         .ok_or_else(|| anyhow!("missing argument 1: triple"))?;
22     let embedding_so_path = args
23         .next()
24         .ok_or_else(|| anyhow!("missing argument 2: path to libembedding.so"))?;
25     let platform_so_path = args
26         .next()
27         .ok_or_else(|| anyhow!("missing argument 3: path to libwasmtime-platform.so"))?;
28 
29     // Path to the artifact which is the build of the embedding.
30     //
31     // In this example this is a dynamic library intended to be run on Linux.
32     // Note that this is just an example of an artifact and custom build
33     // processes can produce different kinds of artifacts.
34     let binary = std::fs::read(&embedding_so_path)?;
35     let object = object::File::parse(&binary[..])?;
36 
37     // Showcase verification that the dynamic library in question doesn't depend
38     // on much. Wasmtime build in a "minimal platform" mode is allowed to
39     // depend on some standard C symbols such as `memcpy` but any OS-related
40     // symbol must be prefixed by `wasmtime_*` and be documented in
41     // `crates/wasmtime/src/runtime/vm/sys/custom/capi.rs`.
42     //
43     // This is effectively a double-check of the above assertion and showing how
44     // running `libembedding.so` in this case requires only minimal
45     // dependencies.
46     for sym in object.symbols() {
47         if !sym.is_undefined() || sym.is_weak() {
48             continue;
49         }
50 
51         match sym.name()? {
52             "memmove" | "memset" | "memcmp" | "memcpy" | "bcmp" | "__tls_get_addr" => {}
53             s if s.starts_with("wasmtime_") => {}
54             other => {
55                 panic!("unexpected dependency on symbol `{other}`")
56             }
57         }
58     }
59 
60     // Precompile modules for the embedding. Right now Wasmtime in no_std mode
61     // does not have support for Cranelift meaning that AOT mode must be used.
62     // Modules are compiled here and then given to the embedding via the `run`
63     // function below.
64     //
65     // Note that `Config::target` is used here to enable cross-compilation.
66     let mut config = Config::new();
67     config.target(&triple)?;
68     let engine = Engine::new(&config)?;
69     let smoke = engine.precompile_module(b"(module)")?;
70     let simple_add = engine.precompile_module(
71         br#"
72             (module
73                 (func (export "add") (param i32 i32) (result i32)
74                     (i32.add (local.get 0) (local.get 1)))
75             )
76         "#,
77     )?;
78     let simple_host_fn = engine.precompile_module(
79         br#"
80             (module
81                 (import "host" "multiply" (func $multiply (param i32 i32) (result i32)))
82                 (func (export "add_and_mul") (param i32 i32 i32) (result i32)
83                     (i32.add (call $multiply (local.get 0) (local.get 1)) (local.get 2)))
84             )
85         "#,
86     )?;
87 
88     // Next is an example of running this embedding, which also serves as test
89     // that basic functionality actually works.
90     //
91     // Here the `wasmtime_*` symbols are implemented by
92     // `./embedding/wasmtime-platform.c` which is an example implementation
93     // against glibc on Linux. This library is compiled into
94     // `libwasmtime-platform.so` and is dynamically opened here to make it
95     // available for later symbol resolution. This is just an implementation
96     // detail of this exable to enably dynamically loading `libembedding.so`
97     // next.
98     //
99     // Next the `libembedding.so` library is opened and the `run` symbol is
100     // run. The dependencies of `libembedding.so` are either satisfied by our
101     // ambient libc (e.g. `memcpy` and friends) or `libwasmtime-platform.so`
102     // (e.g. `wasmtime_*` symbols).
103     //
104     // The embedding is then run to showcase an example and then an error, if
105     // any, is written to stderr.
106     unsafe {
107         let _platform_symbols = Library::open(Some(&platform_so_path), RTLD_NOW | RTLD_GLOBAL)
108             .with_context(|| {
109                 format!(
110                     "failed to open {platform_so_path:?}; cwd = {:?}",
111                     std::env::current_dir()
112                 )
113             })?;
114 
115         let lib = Library::new(&embedding_so_path).context("failed to create new library")?;
116         let run: Symbol<
117             extern "C" fn(
118                 *mut u8,
119                 usize,
120                 *const u8,
121                 usize,
122                 *const u8,
123                 usize,
124                 *const u8,
125                 usize,
126             ) -> usize,
127         > = lib
128             .get(b"run")
129             .context("failed to find the `run` symbol in the library")?;
130 
131         let mut error_buf = Vec::with_capacity(1024);
132         let len = run(
133             error_buf.as_mut_ptr(),
134             error_buf.capacity(),
135             smoke.as_ptr(),
136             smoke.len(),
137             simple_add.as_ptr(),
138             simple_add.len(),
139             simple_host_fn.as_ptr(),
140             simple_host_fn.len(),
141         );
142         error_buf.set_len(len);
143 
144         std::io::stderr().write_all(&error_buf).unwrap();
145     }
146     Ok(())
147 }
148