How to work with wasm runtime memory?

In wasm binary which was compiled with wasm32-unknown-unknown I have 16 blocks of initial memory by default (btw can't get rid of it).

(module
  (memory (;0;) 16)
  (global (;0;) i32 (i32.const 1048576))
  (global (;1;) i32 (i32.const 1048576))
  (export "memory" (memory 0))
  (export "__data_end" (global 0))
  (export "__heap_base" (global 1)))

I don't have any idea how can I work with it. I mean I don't know how to generate instructions like i32.load or i32.store in my output binary and I can't find any documentation.

For example, I tried to get memory like this but got a lot of errors:

#![no_std]

extern "C" {
    static __heap_base: usize;
}

#[no_mangle]
pub fn get_memory_part() -> i32 {
    let ptr: *const i32;

    let data = unsafe {
        core::slice::from_raw_parts(&ptr, __heap_base)
    };

    // I got an error here
    data[0]
}

I did something wrong.. Please help!

(Also I can create static const and expose it outside, but this will create extra memory and increase total memory of the wasm module..)

The pre-allocated memory is for use by the stack only (and to store global variables, string literals, ...). You can't use if for anything else like heap memory. If you want heap memory, you will have to use memory.grow to allocate new memory or better just use the default memory allocator which handles sub-page allocations and reusing freed memory for you.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.