我正在使用clang -> llc -> s2wasm
和clang -> lld
从C编译为WebAssembly。因为没有提供c库,所以我编写了自己的分配器。但我不确定找到空闲记忆的最佳方法是什么。
lld和s2wasm似乎都有内存布局:| globals | stack | free memory |
。使用s2wasm的堆栈指针位于内存地址,使用lld它是全局的(不能从C?中访问)。
我发现的一种方法是使用这个hack在wasm执行开始时读取stackpointer:
int stacktop()
{
int a;
return (int)(&a+1);
}
这将创建一个局部变量,该变量不驻留在线性内存中并获取其地址。要生成地址,编译器会将其放在内存堆栈中。
我使用返回的值作为堆的开头。是否有更优雅,面向未来的方式来寻找自由记忆?
答案 0 :(得分:1)
lld创建一个名为__heap_base
的C符号,它指向堆的基础。它还将此导出为wasm全局,因此嵌入器可以知道堆的起始位置。
答案 1 :(得分:1)
您需要获取lld创建的__heap_base
符号的地址:
$ cat wasm-heap.c
extern unsigned char __heap_base;
__attribute__ ((visibility("default")))
void * get_heap_base(void) {
return &__heap_base;
}
这将返回与导出到JavaScript的__heap_base
WASM变量相同的值:
$ cat wasm-heap.js
var imports = {memory: new WebAssembly.Memory({initial:2})};
const module = new WebAssembly.Module(read('wasm-heap.wasm', 'binary'));
const instance = new WebAssembly.Instance(module, { "env" : imports }).exports;
var u8_data = new Uint8Array(imports["memory"]["buffer"]);
print("Heap base in WASM: " + instance.get_heap_base());
print("Heap base exported to JS: " + instance.__heap_base);
$ js52 wasm-heap.js
Heap base in WASM: 66560
Heap base exported to JS: 66560