xref: /wasmtime-44.0.1/examples/wasip1/main.cc (revision eaa01d7b)
1 /*
2 Example of instantiating a wasm module which uses WASI imports.
3 
4 You can build the example using CMake:
5 
6 mkdir build && (cd build && cmake .. && \
7   cmake --build . --target wasmtime-wasip1-cpp)
8 
9 And then run it:
10 
11 build/wasmtime-wasip1-cpp
12 */
13 
14 #include <fstream>
15 #include <iostream>
16 #include <sstream>
17 #include <vector>
18 #include <wasmtime.hh>
19 
20 using namespace wasmtime;
21 
read_binary_file(const char * path)22 static std::vector<uint8_t> read_binary_file(const char *path) {
23   std::ifstream file(path, std::ios::in | std::ios::binary);
24   if (!file.is_open()) {
25     throw std::runtime_error(std::string("failed to open wasm file: ") + path);
26   }
27   std::vector<uint8_t> data((std::istreambuf_iterator<char>(file)),
28                             std::istreambuf_iterator<char>());
29   return data;
30 }
31 
main()32 int main() {
33   // Define the WASI functions globally on the `Config`.
34   Engine engine;
35   Linker linker(engine);
36   linker.define_wasi().unwrap();
37 
38   // Create a WASI context and put it in a Store; all instances in the store
39   // share this context. `WasiConfig` provides a number of ways to
40   // configure what the target program will have access to.
41   WasiConfig wasi;
42   wasi.inherit_argv();
43   wasi.inherit_stdin();
44   wasi.inherit_stdout();
45   wasi.inherit_stderr();
46 
47   Store store(engine);
48   store.context().set_wasi(std::move(wasi)).unwrap();
49 
50   // Load and compile the wasm module.
51   auto bytes = read_binary_file("target/wasm32-wasip1/debug/wasi.wasm");
52   auto module =
53       Module::compile(engine, Span<uint8_t>(bytes.data(), bytes.size()))
54           .unwrap();
55 
56   // Define the module in the linker (anonymous name matches Rust example
57   // usage).
58   linker.module(store.context(), "", module).unwrap();
59 
60   // Get the default export (command entrypoint) and invoke it.
61   Func default_func = linker.get_default(store.context(), "").unwrap();
62   default_func.call(store, {}).unwrap();
63 
64   return 0;
65 }
66