Stream: wasmtime

Topic: repr(C) struct guest to host


view this post on Zulip Jean Mertz (May 09 2020 at 16:17):

I have a repr(C) struct in my guest Wasm module written in Rust. Right now I'm using serde to serialize the struct to JSON and have it into_boxed_slice. I then use a callback ffi function to pass the pointer and length to the host. This all works, but I'm trying to make it work without having to serialize the struct.

On the guest I'm now doing Box::into_raw(Box::new(my_struct)) and pass that pointer as i32 to the host. Now I'm having issues getting this ptr back into my struct with Box::from_raw. I'm not sure how to get to the right offset in memory. I have a ptr to the start of the wasm memory using wasmtime's data_ptr(), but I've tried different things to use my i32 ptr value and combine that with data_ptr() to go to the right offset, and then cast it back to my struct, unsuccessfully.

I feel like I'm missing a crucial piece of the puzzle here, so if anyone has any pointers, I'd be happy to hear them!

view this post on Zulip Jean Mertz (May 09 2020 at 16:28):

At the host, I tried something like this:

let ptr = mem.data_ptr().offset(my_guest_ptr_as_i32 as isize);
let my_struct = *Box::from_raw(ptr as *mut MyStruct);

which result in the following error when running:

test(41136,0x11b392dc0) malloc: *** error for object 0x11b4dd018: pointer being freed was not allocated
test(41136,0x11b392dc0) malloc: *** set a breakpoint in malloc_error_break to debug

Reading the docs for offset, I'm fairly confident my usage of passing in the guest i32 ptr as the offset isn't correct, but I'm unsure what the solution is. I'm also unsure how this is supposed to work given that data_ptr() returns a *mut u8 and I'm casting that to *mut MyStruct.

view this post on Zulip Yury Delendik (May 11 2020 at 14:03):

depends on MyStruct fields: if there structs that require dereferencing (String, Vec, etc) then you will get similar errors. Notice that wasm ptr and usize size are different from hosts.

view this post on Zulip Pat Hickey (May 12 2020 at 18:20):

The wiggle tool is designed to take care of host side conversions of complex datatypes that are described in the .witx format

view this post on Zulip Pat Hickey (May 12 2020 at 18:20):

It’s used by wasi-common but can be used elsewhere as well


Last updated: Nov 22 2024 at 16:03 UTC