Hi, I understand that the host shouldn't implement realloc
or other memory relative functions, but I still need some way to make it work.
Here is a C file, I'll still compile it into test.wasm
and run it via wasmtime test.wasm
.
// test.c
#include <stdio.h>
#include <stdlib.h>
extern void test_func(int *ptr, int size);
int main() {
int *p = malloc(sizeof(int) * 6);
test_func(p, 9);
return 0;
}
And in wasmtime, I wrap the function test_func
like below and register it in Linker
. And actually wasmtime will call test_func
which is declared in helper.c
which is shown down here.
// wasmtime/src/commands/run.rs
linker.func_wrap("env", "test_func", wrap_test_func)?;
// ...
#[link(name = "my-helpers")]
extern "C" {
fn test_func(ptr: *const u32, size: i32);
}
fn wrap_test_func(mut caller: wasmtime::Caller<'_, Host>, _ptr: u32, size: i32) {
let memory = caller.get_export("memory").unwrap().into_memory().unwrap();
let linear_memory: &[u8] = memory.data(&caller);
unsafe {
let ptr: *const u32 = linear_memory.as_ptr().add(_ptr as usize).cast();
test_func(ptr, size)
}
}
helper.c
will be compiled to my-helpers
via build.rs
which I didn't show it here.
// helper.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test_func(int *ptr, int size) {
int *new_ptr;
new_ptr = realloc(ptr, size);
ptr = new_ptr;
printf("%d\n", ptr[1]);
}
The most trickey thing happens here is that I will call realloc
in helper.c
.
So when I actually run wasmtime test.wasm
, the error will occur. The error message is here.
wasmtime(90045,0x104bb8580) malloc: *** error for object 0x300010610: pointer being realloc'd was not allocated
wasmtime(90045,0x104bb8580) malloc: *** set a breakpoint in malloc_error_break to debug
[1] 90045 abort ./wasmtime test.wasm
The main problem here is still that I want to manipulate the wasm memory in host side, and in my code, it's obviously improper. So I wonder if there is a way to fix this.