首页 > 解决方案 > 使用 Rust 构建 `.wasm` 二进制文件时访问 `__heap_base`

问题描述

想要遵循本文中所做的事情:https ://surma.dev/things/c-to-webassembly/但使用 Rust 并编写自定义分配器。

为此,我需要访问__heap_basellvm 添加的变量作为堆在线性内存中开始位置的指针。有没有办法在 Rust 中实现这一点?

我尝试了

extern "C" {
    static __heap_base: i32;
}

#[no_mangle]
pub unsafe extern "C" fn main() -> i32 {
    __heap_base
}

但它们返回 0 而不是二进制中分配的实际值。

标签: rustllvmwebassemblylld

解决方案


After working a bit with this. An idea of an answer is that there seems to be a difference between the values of your program and the values the compiler/linker then defines in the wasm file. There's not a 1 to 1 relationship in principle.

When you define a variable in C/Rust you get the variable and not the address of the variable itself. I.e: if you define a pointer you get the address of the data the pointer points to and not the address of where the value of that pointer is stored.

So by specifying static __heap_base: i32 you are asking the compiler for __heap_base the value to be an i32, not heap base the pointer (which is what llvm then writes as a wasm i32 whatever type you set for __heap_base). The address of that value is the actual pointer to the __heap_base

Why you can just import __heap_base as the value that is pointed to by heap base still is not that clear to me. Maybe symbols always mean values and something like *__heap_base is just the pointer which when dereferenced gives you __heap_base (the value) and it's treated like this internally


推荐阅读