rust - 使用 Rust 构建 `.wasm` 二进制文件时访问 `__heap_base`
问题描述
想要遵循本文中所做的事情:https ://surma.dev/things/c-to-webassembly/但使用 Rust 并编写自定义分配器。
为此,我需要访问__heap_base
llvm 添加的变量作为堆在线性内存中开始位置的指针。有没有办法在 Rust 中实现这一点?
我尝试了
extern "C" {
static __heap_base: i32;
}
#[no_mangle]
pub unsafe extern "C" fn main() -> i32 {
__heap_base
}
但它们返回 0 而不是二进制中分配的实际值。
解决方案
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
推荐阅读
- c - printf 中的类型检查是如何实现的?
- android - Avast 报告说我的 android 应用是 Android:Evo-gen [Trj]
- elasticsearch - 如何使热门聚合结果多样化?
- r - 添加后缀并更改多列的值
- assembly - 为什么“程序在 5 秒后超时”发生在 gdb 中?
- javascript - 如何在像producthunt这样的NodeJS中定义快速获取数据的快速路线?
- reactjs - 如何在本机反应中格式化时间字符串
- google-cloud-firestore - 如何从 multipart/formData 请求将文件保存在 Firestore 数据库中?
- asp.net-mvc - 使用 2 个或更多模型创建 API
- javascript - 如何在 JS 中返回所有具有相同值的重复对象?