Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "malloc" in Wasm

I am learning WebAssembly now and I find that the external function (libc or third party function) can't be accessed by Wasm world easily (using import is a general solution).

I'm trying to use emcc to compile my source code into wasm but malloc and free are widely used in my source code. I don't think that importing malloc and free from real world is practicable.

So, I'm pretty curious about how to implement malloc in wasm world. I have already known how the malloc works in glibc:using brk() or sbrk() to extend heap and some memory management for the liner address. But in wasm world I think it impossible to call brk() or sbrk() to get the liner address.

Is it reasonable to use global var to implement malloc like this ?

u_char mem[10240];


void *wasm_malloc(size_t num)
{
    /*get the free mem idx*/
    return &mem[idx];
}
like image 929
Nail Jay Avatar asked Mar 04 '23 17:03

Nail Jay


1 Answers

Wait, you don't need to do that.

I don't think that importing malloc and free from real world is practicable.

Incorrect. That's exactly the point of using Emscripten. Emscripten is not just a C/C++ to Wasm compiler, but a complete toolchain that includes a web runtime and its own libc specifically designed for running C/C++ program for web browsers with minimal source code modifications.

Emscripten libc is a heavily modified fork of musl. It implements/emulates wide range of standard C libraries (including malloc, sbrk) and POSIX APIs (like pthread and BSD socket), except some APIs that doesn't make sense in a Wasm environment like exec and fork. By using emcc command, you will link those libc ports out of the box. So feel free just using malloc - you don't need to do anything!

If you are still wondering how to implement malloc for Emscripten, Emscripten has two options of malloc implementations - dlmalloc and emmalloc.

dlmalloc is a famous malloc implementation. glibc also uses a forked version of it. You can see Emscripten's version of dlmalloc here.

emmalloc might be more interesting to you. It's a simple and compact malloc implementation for web enviroment, designed by the Emscripten team. You can see the source code here.

like image 161
Bumsik Kim Avatar answered May 12 '23 11:05

Bumsik Kim