Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does wee_alloc (a malloc alternative) know where to start the heap in WebAssembly?

I'm trying to utilize wee_alloc in a custom language, running in WebAssembly. However, I need to fully grok how it knows where to start the heap at so that my stack and static allocations do not clobber it and vice versa.

It's my understanding that how malloc, et al. know where to start the heap is platform dependent and often just a convention, or in some cases not applicable. However in WebAssembly we can only have a single contiguous piece of linear memory, so we have to share it and a convention needs to be used.

Reading through the code it appears that what wee_alloc does is make the assumption that whatever memory we start with is off-limits completely, and instead will use the grow_memory instruction to create the first piece of memory needed for the heap. That effectively means that the index/address of the start of the heap is highest index of what ever the initial size is, plus one. (Edit: It's actually not + 1, I forgot that indices are zero based; off-by-one error ☠️)

e.g. if we start off with an initial memory size of 1 page:

 current_memory = 1 page = 64KiB = 65,536 bytes

then the heap starts at index 65537.

Is my understanding correct?

like image 305
jayphelps Avatar asked Nov 07 '22 03:11

jayphelps


1 Answers

Your understanding is correct! With a small exception though: since the indexes are zero based, the last index of the first page is 65535, and the first index of the second page is 65536. - @pepyakin

https://github.com/rustwasm/wee_alloc/issues/61#issuecomment-416868326

like image 92
jayphelps Avatar answered Nov 14 '22 03:11

jayphelps