Skip to content

Instantly share code, notes, and snippets.

@adlrocha

adlrocha/main.rs Secret

Created December 13, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adlrocha/69719141cc07a4c01f1a6b3ffd668e9c to your computer and use it in GitHub Desktop.
Save adlrocha/69719141cc07a4c01f1a6b3ffd668e9c to your computer and use it in GitHub Desktop.
use anyhow::Result;
use wasmtime::*;
use std::ptr::copy;
fn main() -> Result<()> {
// Create our `Store` context and then compile a module and create an
// instance from the compiled module all in one go.
let wasmtime_store = Store::default();
// Load Wasm module
let module = Module::from_file(wasmtime_store.engine(), "../modules/memory.wasm")?;
let instance = Instance::new(&wasmtime_store, &module, &[])?;
// Expose alloc function from Wasm module
let alloc = instance
.get_func("alloc")
.ok_or(anyhow::format_err!("failed to find `alloc` export"))?
.get1::<i32, i32>()?;
// Get linear memory
let memory = instance
.get_memory("memory")
.ok_or(anyhow::format_err!("failed to find `memory` export"))?;
// Input string
let text = String::from("The input string");
let size = text.len() as i32;
// Allocate memory and visualize it.
let mem_ptr = alloc(size+30)?;
println!("Pointer received {:#x}, {}", mem_ptr, size);
println!("Host memory pointer {:#x?}", memory.data_ptr());
println!("wasm allocated memory {:#x?}",
unsafe{ memory.data_unchecked_mut().as_ptr() });
let pointer = unsafe { memory.data_ptr().add(mem_ptr as usize) };
println!("address for wasm object in rust: {:#x?}", pointer);
// Copy input data in linear memory-
unsafe {
let bytes = text.as_bytes();
copy(bytes.as_ptr(),
pointer,
bytes.len());
}
// Expose append function from wasm module
let append = instance
.get_func("append")
.ok_or(anyhow::format_err!("failed to find `append` export"))?
.get2::<i32, i32, i32>()?;
// Execute function
let new_size = append(mem_ptr, size)?;
println!("New Size received: {}", new_size);
// Get output data
let byte3 = unsafe {
String::from_utf8(memory.data_unchecked()[mem_ptr as usize..][..new_size as usize]
.to_vec()).unwrap()
};
println!("Result: {}", byte3);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment