xref: /wasmtime-44.0.1/crates/bench-api/src/lib.rs (revision 08b7c877)
1 //! A C API for benchmarking Wasmtime's WebAssembly compilation, instantiation,
2 //! and execution.
3 //!
4 //! The API expects calls that match the following state machine:
5 //!
6 //! ```text
7 //!               |
8 //!               |
9 //!               V
10 //! .---> wasm_bench_create
11 //! |        |        |
12 //! |        |        |
13 //! |        |        V
14 //! |        |   wasm_bench_compile
15 //! |        |     |            |
16 //! |        |     |            |     .----.
17 //! |        |     |            |     |    |
18 //! |        |     |            V     V    |
19 //! |        |     |     wasm_bench_instantiate <------.
20 //! |        |     |            |        |             |
21 //! |        |     |            |        |             |
22 //! |        |     |            |        |             |
23 //! |        |     |     .------'        '-----> wasm_bench_execute
24 //! |        |     |     |                             |
25 //! |        |     |     |                             |
26 //! |        V     V     V                             |
27 //! '------ wasm_bench_free <--------------------------'
28 //!               |
29 //!               |
30 //!               V
31 //! ```
32 //!
33 //! All API calls must happen on the same thread.
34 //!
35 //! Functions which return pointers use null as an error value. Function which
36 //! return `int` use `0` as OK and non-zero as an error value.
37 //!
38 //! # Example
39 //!
40 //! ```
41 //! use std::ptr;
42 //! use wasmtime_bench_api::*;
43 //!
44 //! let working_dir = std::env::current_dir().unwrap().display().to_string();
45 //! let stdout_path = "./stdout.log";
46 //! let stderr_path = "./stderr.log";
47 //!
48 //! // Functions to start/end timers for compilation.
49 //! //
50 //! // The `compilation_timer` pointer configured in the `WasmBenchConfig` is
51 //! // passed through.
52 //! extern "C" fn compilation_start(timer: *mut u8) {
53 //!     // Start your compilation timer here.
54 //! }
55 //! extern "C" fn compilation_end(timer: *mut u8) {
56 //!     // End your compilation timer here.
57 //! }
58 //!
59 //! // Similar for instantiation.
60 //! extern "C" fn instantiation_start(timer: *mut u8) {
61 //!     // Start your instantiation timer here.
62 //! }
63 //! extern "C" fn instantiation_end(timer: *mut u8) {
64 //!     // End your instantiation timer here.
65 //! }
66 //!
67 //! // Similar for execution.
68 //! extern "C" fn execution_start(timer: *mut u8) {
69 //!     // Start your execution timer here.
70 //! }
71 //! extern "C" fn execution_end(timer: *mut u8) {
72 //!     // End your execution timer here.
73 //! }
74 //!
75 //! let config = WasmBenchConfig {
76 //!     working_dir_ptr: working_dir.as_ptr(),
77 //!     working_dir_len: working_dir.len(),
78 //!     stdout_path_ptr: stdout_path.as_ptr(),
79 //!     stdout_path_len: stdout_path.len(),
80 //!     stderr_path_ptr: stderr_path.as_ptr(),
81 //!     stderr_path_len: stderr_path.len(),
82 //!     stdin_path_ptr: ptr::null(),
83 //!     stdin_path_len: 0,
84 //!     compilation_timer: ptr::null_mut(),
85 //!     compilation_start,
86 //!     compilation_end,
87 //!     instantiation_timer: ptr::null_mut(),
88 //!     instantiation_start,
89 //!     instantiation_end,
90 //!     execution_timer: ptr::null_mut(),
91 //!     execution_start,
92 //!     execution_end,
93 //!     execution_flags_ptr: ptr::null(),
94 //!     execution_flags_len: 0,
95 //! };
96 //!
97 //! let mut bench_api = ptr::null_mut();
98 //! unsafe {
99 //!     let code = wasm_bench_create(config, &mut bench_api);
100 //!     assert_eq!(code, OK);
101 //!     assert!(!bench_api.is_null());
102 //! };
103 //!
104 //! let wasm = wat::parse_bytes(br#"
105 //!     (module
106 //!         (func $bench_start (import "bench" "start"))
107 //!         (func $bench_end (import "bench" "end"))
108 //!         (func $start (export "_start")
109 //!             call $bench_start
110 //!             i32.const 1
111 //!             i32.const 2
112 //!             i32.add
113 //!             drop
114 //!             call $bench_end
115 //!         )
116 //!     )
117 //! "#).unwrap();
118 //!
119 //! // This will call the `compilation_{start,end}` timing functions on success.
120 //! let code = unsafe { wasm_bench_compile(bench_api, wasm.as_ptr(), wasm.len()) };
121 //! assert_eq!(code, OK);
122 //!
123 //! // This will call the `instantiation_{start,end}` timing functions on success.
124 //! let code = unsafe { wasm_bench_instantiate(bench_api) };
125 //! assert_eq!(code, OK);
126 //!
127 //! // This will call the `execution_{start,end}` timing functions on success.
128 //! let code = unsafe { wasm_bench_execute(bench_api) };
129 //! assert_eq!(code, OK);
130 //!
131 //! unsafe {
132 //!     wasm_bench_free(bench_api);
133 //! }
134 //! ```
135 
136 mod unsafe_send_sync;
137 
138 use crate::unsafe_send_sync::UnsafeSendSync;
139 use anyhow::{anyhow, Context, Result};
140 use std::os::raw::{c_int, c_void};
141 use std::slice;
142 use std::{env, path::PathBuf};
143 use target_lexicon::Triple;
144 use wasmtime::{Config, Engine, Instance, Linker, Module, Store};
145 use wasmtime_cli_flags::CommonOptions;
146 use wasmtime_wasi::{sync::WasiCtxBuilder, WasiCtx};
147 
148 pub type ExitCode = c_int;
149 pub const OK: ExitCode = 0;
150 pub const ERR: ExitCode = -1;
151 
152 // Randomize the location of heap objects to avoid accidental locality being an
153 // uncontrolled variable that obscures performance evaluation in our
154 // experiments.
155 #[cfg(feature = "shuffling-allocator")]
156 #[global_allocator]
157 static ALLOC: shuffling_allocator::ShufflingAllocator<std::alloc::System> =
158     shuffling_allocator::wrap!(&std::alloc::System);
159 
160 /// Configuration options for the benchmark.
161 #[repr(C)]
162 pub struct WasmBenchConfig {
163     /// The working directory where benchmarks should be executed.
164     pub working_dir_ptr: *const u8,
165     pub working_dir_len: usize,
166 
167     /// The file path that should be created and used as `stdout`.
168     pub stdout_path_ptr: *const u8,
169     pub stdout_path_len: usize,
170 
171     /// The file path that should be created and used as `stderr`.
172     pub stderr_path_ptr: *const u8,
173     pub stderr_path_len: usize,
174 
175     /// The (optional) file path that should be opened and used as `stdin`. If
176     /// not provided, then the WASI context will not have a `stdin` initialized.
177     pub stdin_path_ptr: *const u8,
178     pub stdin_path_len: usize,
179 
180     /// The functions to start and stop performance timers/counters during Wasm
181     /// compilation.
182     pub compilation_timer: *mut u8,
183     pub compilation_start: extern "C" fn(*mut u8),
184     pub compilation_end: extern "C" fn(*mut u8),
185 
186     /// The functions to start and stop performance timers/counters during Wasm
187     /// instantiation.
188     pub instantiation_timer: *mut u8,
189     pub instantiation_start: extern "C" fn(*mut u8),
190     pub instantiation_end: extern "C" fn(*mut u8),
191 
192     /// The functions to start and stop performance timers/counters during Wasm
193     /// execution.
194     pub execution_timer: *mut u8,
195     pub execution_start: extern "C" fn(*mut u8),
196     pub execution_end: extern "C" fn(*mut u8),
197 
198     /// The (optional) flags to use when running Wasmtime. These correspond to
199     /// the flags used when running Wasmtime from the command line.
200     pub execution_flags_ptr: *const u8,
201     pub execution_flags_len: usize,
202 }
203 
204 impl WasmBenchConfig {
205     fn working_dir(&self) -> Result<PathBuf> {
206         let working_dir =
207             unsafe { std::slice::from_raw_parts(self.working_dir_ptr, self.working_dir_len) };
208         let working_dir = std::str::from_utf8(working_dir)
209             .context("given working directory is not valid UTF-8")?;
210         Ok(working_dir.into())
211     }
212 
213     fn stdout_path(&self) -> Result<PathBuf> {
214         let stdout_path =
215             unsafe { std::slice::from_raw_parts(self.stdout_path_ptr, self.stdout_path_len) };
216         let stdout_path =
217             std::str::from_utf8(stdout_path).context("given stdout path is not valid UTF-8")?;
218         Ok(stdout_path.into())
219     }
220 
221     fn stderr_path(&self) -> Result<PathBuf> {
222         let stderr_path =
223             unsafe { std::slice::from_raw_parts(self.stderr_path_ptr, self.stderr_path_len) };
224         let stderr_path =
225             std::str::from_utf8(stderr_path).context("given stderr path is not valid UTF-8")?;
226         Ok(stderr_path.into())
227     }
228 
229     fn stdin_path(&self) -> Result<Option<PathBuf>> {
230         if self.stdin_path_ptr.is_null() {
231             return Ok(None);
232         }
233 
234         let stdin_path =
235             unsafe { std::slice::from_raw_parts(self.stdin_path_ptr, self.stdin_path_len) };
236         let stdin_path =
237             std::str::from_utf8(stdin_path).context("given stdin path is not valid UTF-8")?;
238         Ok(Some(stdin_path.into()))
239     }
240 
241     fn execution_flags(&self) -> Result<Option<Config>> {
242         if self.execution_flags_ptr.is_null() {
243             return Ok(None);
244         }
245 
246         let execution_flags = unsafe {
247             std::slice::from_raw_parts(self.execution_flags_ptr, self.execution_flags_len)
248         };
249         let execution_flags = std::str::from_utf8(execution_flags)
250             .context("given execution flags string is not valid UTF-8")?;
251 
252         let options = CommonOptions::parse_from_str(execution_flags)?;
253         let config = options.config(Some(&Triple::host().to_string()))?;
254         Ok(Some(config))
255     }
256 }
257 
258 /// Exposes a C-compatible way of creating the engine from the bytes of a single
259 /// Wasm module.
260 ///
261 /// On success, the `out_bench_ptr` is initialized to a pointer to a structure
262 /// that contains the engine's initialized state, and `0` is returned. On
263 /// failure, a non-zero status code is returned and `out_bench_ptr` is left
264 /// untouched.
265 #[no_mangle]
266 pub extern "C" fn wasm_bench_create(
267     config: WasmBenchConfig,
268     out_bench_ptr: *mut *mut c_void,
269 ) -> ExitCode {
270     let result = (|| -> Result<_> {
271         let working_dir = config.working_dir()?;
272         let working_dir =
273             cap_std::fs::Dir::open_ambient_dir(&working_dir, cap_std::ambient_authority())
274                 .with_context(|| {
275                     format!(
276                         "failed to preopen the working directory: {}",
277                         working_dir.display(),
278                     )
279                 })?;
280 
281         let stdout_path = config.stdout_path()?;
282         let stderr_path = config.stderr_path()?;
283         let stdin_path = config.stdin_path()?;
284         let engine_config = config.execution_flags()?;
285 
286         let state = Box::new(BenchState::new(
287             engine_config,
288             config.compilation_timer,
289             config.compilation_start,
290             config.compilation_end,
291             config.instantiation_timer,
292             config.instantiation_start,
293             config.instantiation_end,
294             config.execution_timer,
295             config.execution_start,
296             config.execution_end,
297             move || {
298                 let mut cx = WasiCtxBuilder::new();
299 
300                 let stdout = std::fs::File::create(&stdout_path)
301                     .with_context(|| format!("failed to create {}", stdout_path.display()))?;
302                 let stdout = cap_std::fs::File::from_std(stdout);
303                 let stdout = wasi_cap_std_sync::file::File::from_cap_std(stdout);
304                 cx = cx.stdout(Box::new(stdout));
305 
306                 let stderr = std::fs::File::create(&stderr_path)
307                     .with_context(|| format!("failed to create {}", stderr_path.display()))?;
308                 let stderr = cap_std::fs::File::from_std(stderr);
309                 let stderr = wasi_cap_std_sync::file::File::from_cap_std(stderr);
310                 cx = cx.stderr(Box::new(stderr));
311 
312                 if let Some(stdin_path) = &stdin_path {
313                     let stdin = std::fs::File::open(stdin_path)
314                         .with_context(|| format!("failed to open {}", stdin_path.display()))?;
315                     let stdin = cap_std::fs::File::from_std(stdin);
316                     let stdin = wasi_cap_std_sync::file::File::from_cap_std(stdin);
317                     cx = cx.stdin(Box::new(stdin));
318                 }
319 
320                 // Allow access to the working directory so that the benchmark can read
321                 // its input workload(s).
322                 cx = cx.preopened_dir(working_dir.try_clone()?, ".")?;
323 
324                 // Pass this env var along so that the benchmark program can use smaller
325                 // input workload(s) if it has them and that has been requested.
326                 if let Ok(val) = env::var("WASM_BENCH_USE_SMALL_WORKLOAD") {
327                     cx = cx.env("WASM_BENCH_USE_SMALL_WORKLOAD", &val)?;
328                 }
329 
330                 Ok(cx.build())
331             },
332         )?);
333         Ok(Box::into_raw(state) as _)
334     })();
335 
336     if let Ok(bench_ptr) = result {
337         unsafe {
338             assert!(!out_bench_ptr.is_null());
339             *out_bench_ptr = bench_ptr;
340         }
341     }
342 
343     to_exit_code(result.map(|_| ()))
344 }
345 
346 /// Free the engine state allocated by this library.
347 #[no_mangle]
348 pub extern "C" fn wasm_bench_free(state: *mut c_void) {
349     assert!(!state.is_null());
350     unsafe {
351         Box::from_raw(state as *mut BenchState);
352     }
353 }
354 
355 /// Compile the Wasm benchmark module.
356 #[no_mangle]
357 pub extern "C" fn wasm_bench_compile(
358     state: *mut c_void,
359     wasm_bytes: *const u8,
360     wasm_bytes_length: usize,
361 ) -> ExitCode {
362     let state = unsafe { (state as *mut BenchState).as_mut().unwrap() };
363     let wasm_bytes = unsafe { slice::from_raw_parts(wasm_bytes, wasm_bytes_length) };
364     let result = state.compile(wasm_bytes).context("failed to compile");
365     to_exit_code(result)
366 }
367 
368 /// Instantiate the Wasm benchmark module.
369 #[no_mangle]
370 pub extern "C" fn wasm_bench_instantiate(state: *mut c_void) -> ExitCode {
371     let state = unsafe { (state as *mut BenchState).as_mut().unwrap() };
372     let result = state.instantiate().context("failed to instantiate");
373     to_exit_code(result)
374 }
375 
376 /// Execute the Wasm benchmark module.
377 #[no_mangle]
378 pub extern "C" fn wasm_bench_execute(state: *mut c_void) -> ExitCode {
379     let state = unsafe { (state as *mut BenchState).as_mut().unwrap() };
380     let result = state.execute().context("failed to execute");
381     to_exit_code(result)
382 }
383 
384 /// Helper function for converting a Rust result to a C error code.
385 ///
386 /// This will print an error indicating some information regarding the failure.
387 fn to_exit_code<T>(result: impl Into<Result<T>>) -> ExitCode {
388     match result.into() {
389         Ok(_) => OK,
390         Err(error) => {
391             eprintln!("{:?}", error);
392             ERR
393         }
394     }
395 }
396 
397 /// This structure contains the actual Rust implementation of the state required
398 /// to manage the Wasmtime engine between calls.
399 struct BenchState {
400     linker: Linker<HostState>,
401     compilation_timer: *mut u8,
402     compilation_start: extern "C" fn(*mut u8),
403     compilation_end: extern "C" fn(*mut u8),
404     instantiation_timer: *mut u8,
405     instantiation_start: extern "C" fn(*mut u8),
406     instantiation_end: extern "C" fn(*mut u8),
407     make_wasi_cx: Box<dyn FnMut() -> Result<WasiCtx>>,
408     module: Option<Module>,
409     store_and_instance: Option<(Store<HostState>, Instance)>,
410 }
411 
412 struct HostState {
413     wasi: WasiCtx,
414     #[cfg(feature = "wasi-nn")]
415     wasi_nn: wasmtime_wasi_nn::WasiNnCtx,
416 
417     #[cfg(feature = "wasi-crypto")]
418     wasi_crypto: wasmtime_wasi_crypto::WasiCryptoCtx,
419 }
420 
421 impl BenchState {
422     fn new(
423         engine_config: Option<Config>,
424         compilation_timer: *mut u8,
425         compilation_start: extern "C" fn(*mut u8),
426         compilation_end: extern "C" fn(*mut u8),
427         instantiation_timer: *mut u8,
428         instantiation_start: extern "C" fn(*mut u8),
429         instantiation_end: extern "C" fn(*mut u8),
430         execution_timer: *mut u8,
431         execution_start: extern "C" fn(*mut u8),
432         execution_end: extern "C" fn(*mut u8),
433         make_wasi_cx: impl FnMut() -> Result<WasiCtx> + 'static,
434     ) -> Result<Self> {
435         // NB: do not configure a code cache.
436         let engine = Engine::new(&engine_config.unwrap_or(Config::new()))?;
437         let mut linker = Linker::<HostState>::new(&engine);
438 
439         // Define the benchmarking start/end functions.
440         let execution_timer = unsafe {
441             // Safe because this bench API's contract requires that its methods
442             // are only ever called from a single thread.
443             UnsafeSendSync::new(execution_timer)
444         };
445         linker.func_wrap("bench", "start", move || {
446             execution_start(*execution_timer.get());
447             Ok(())
448         })?;
449         linker.func_wrap("bench", "end", move || {
450             execution_end(*execution_timer.get());
451             Ok(())
452         })?;
453 
454         wasmtime_wasi::add_to_linker(&mut linker, |cx| &mut cx.wasi)?;
455 
456         #[cfg(feature = "wasi-nn")]
457         wasmtime_wasi_nn::add_to_linker(&mut linker, |cx| &mut cx.wasi_nn)?;
458 
459         #[cfg(feature = "wasi-crypto")]
460         wasmtime_wasi_crypto::add_to_linker(&mut linker, |cx| &mut cx.wasi_crypto)?;
461 
462         Ok(Self {
463             linker,
464             compilation_timer,
465             compilation_start,
466             compilation_end,
467             instantiation_timer,
468             instantiation_start,
469             instantiation_end,
470             make_wasi_cx: Box::new(make_wasi_cx) as _,
471             module: None,
472             store_and_instance: None,
473         })
474     }
475 
476     fn compile(&mut self, bytes: &[u8]) -> Result<()> {
477         assert!(
478             self.module.is_none(),
479             "create a new engine to repeat compilation"
480         );
481 
482         (self.compilation_start)(self.compilation_timer);
483         let module = Module::from_binary(self.linker.engine(), bytes)?;
484         (self.compilation_end)(self.compilation_timer);
485 
486         self.module = Some(module);
487         Ok(())
488     }
489 
490     fn instantiate(&mut self) -> Result<()> {
491         let module = self
492             .module
493             .as_ref()
494             .expect("compile the module before instantiating it");
495 
496         let host = HostState {
497             wasi: (self.make_wasi_cx)().context("failed to create a WASI context")?,
498             #[cfg(feature = "wasi-nn")]
499             wasi_nn: wasmtime_wasi_nn::WasiNnCtx::new()?,
500             #[cfg(feature = "wasi-crypto")]
501             wasi_crypto: wasmtime_wasi_nn::WasiCryptoCtx::new(),
502         };
503 
504         // NB: Start measuring instantiation time *after* we've created the WASI
505         // context, since that needs to do file I/O to setup
506         // stdin/stdout/stderr.
507         (self.instantiation_start)(self.instantiation_timer);
508         let mut store = Store::new(self.linker.engine(), host);
509         let instance = self.linker.instantiate(&mut store, &module)?;
510         (self.instantiation_end)(self.instantiation_timer);
511 
512         self.store_and_instance = Some((store, instance));
513         Ok(())
514     }
515 
516     fn execute(&mut self) -> Result<()> {
517         let (mut store, instance) = self
518             .store_and_instance
519             .take()
520             .expect("instantiate the module before executing it");
521 
522         let start_func = instance.get_typed_func::<(), (), _>(&mut store, "_start")?;
523         match start_func.call(&mut store, ()) {
524             Ok(_) => Ok(()),
525             Err(trap) => {
526                 // Since _start will likely return by using the system `exit` call, we must
527                 // check the trap code to see if it actually represents a successful exit.
528                 match trap.i32_exit_status() {
529                     Some(0) => Ok(()),
530                     Some(n) => Err(anyhow!("_start exited with a non-zero code: {}", n)),
531                     None => Err(anyhow!(
532                         "executing the benchmark resulted in a trap: {}",
533                         trap
534                     )),
535                 }
536             }
537         }
538     }
539 }
540