Debian Codegraph @

crates/c-api/src/lib.rs

raw
1 //! This crate is the implementation of Wasm-tools's C API.
2 //!
3 //! This crate is not intended to be used from Rust itself and is typically
4 //! compiled as a cdylib/staticlib. Documentation for this crate largely lives in the header
5 //! files of the `include` directory for this crate.
6
7 #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
8 // This crate fundamentally is doing a lot of unsafe FFI and stuff like that, so
9 // it doesn't make sense to allow each individual unsafe block.
10 #![allow(unsafe_code)]
11
12 use arbitrary::{Error, Unstructured};
13 use wasm_smith::{Config, Module};
14
15 #[repr(C)]
16 pub struct wasm_tools_byte_vec_t {
17 data: *mut u8,
18 size: usize,
19 }
20
21 #[repr(i32)]
22 pub enum wasm_tools_error {
23 WASM_TOOLS_SUCCESS = 0,
24 WASM_TOOLS_ERROR = -1,
25 WASM_TOOLS_INSUFFICIENT_ENTROPY = -2,
26 }
27 use wasm_tools_error::*;
28
29 #[unsafe(no_mangle)]
30 pub extern "C" fn wasm_tools_byte_vec_delete(bytes: &mut wasm_tools_byte_vec_t) {
31 unsafe {
32 Vec::from_raw_parts(bytes.data, bytes.size, bytes.size);
33 }
34 }
35
36 /// Create a new WebAssembly module with the given seed.
37 ///
38 /// # Safety
39 ///
40 /// `seed` must be a valid pointer to `seed_len` bytes of memory.
41 #[unsafe(no_mangle)]
42 pub unsafe extern "C" fn wasm_smith_create(
43 seed: *const u8,
44 seed_len: usize,
45 bytes: &mut wasm_tools_byte_vec_t,
46 ) -> wasm_tools_error {
47 // seed == NULL is acceptable as long as seed_len is zero
48 let seed_bytes = if seed_len == 0 {
49 &[]
50 } else {
51 unsafe { std::slice::from_raw_parts(seed, seed_len) }
52 };
53
54 bytes.data = std::ptr::null_mut();
55 let mut u = Unstructured::new(seed_bytes);
56 match Module::new(Config::default(), &mut u) {
57 Ok(module) => {
58 let mut wasm_buffer = module.to_bytes().into_boxed_slice();
59 bytes.data = wasm_buffer.as_mut_ptr();
60 bytes.size = wasm_buffer.len();
61 std::mem::forget(wasm_buffer);
62 WASM_TOOLS_SUCCESS
63 }
64 Err(Error::NotEnoughData) => WASM_TOOLS_INSUFFICIENT_ENTROPY,
65 Err(_e) => WASM_TOOLS_ERROR,
66 }
67 }