Reputation: 3222
After reading the specifications I was trying to grow some memory and did the following:
(module
(table 0 anyfunc)
(memory $0 1)
(export "memory" (memory $0))
(export "f" (func $0))
(func $0 (param $0 i32) (result i32)
get_local $0
grow_memory
)
)
Now I was hoping that if we input 10 that we have a page size multiple of 11, so something like:
(memory $0 1)
Becomes
(memory $0 11)
I had to add a return value since the stack wasnt emptied. Now I assume that the method returns something other than -1 if it succeeds right? In this case I think it works and I should have more pages.
I know there is also the JS way but I prefer doing all this stuff directly inside WebAssembly. Interesting though is the fact that we can import C functions such as malloc, free, strcopy etc from "Env"..
So my question is: is my approach for growing the memory correct? Should I import the C style modules instead? What is the relation between grow_memory and realloc(), or say the difference?
Upvotes: 1
Views: 2956
Reputation: 6863
grow_memory
returns the previous size (in pages) or -1
according to its specification.
This doesn't change the initial page allocation (memory $0 1)
! That's a static property of the module, whereas current memory size is a dynamic property of the memory. It's like growing an array which you initially reserved 1 element for. You still initially reserved 1, what's changed is the current size.
You could also use drop
to ignore the return value of grow_memory
.
malloc
/ free
/ realloc
are all things you can implement using grow_memory
. That opcode is similar to sbrk
. Of course, the WebAssembly embedder also uses memory allocation to grant your opcode's request, which may itself be implemented with malloc
/ free
/ realloc
, or more likely with mmap
.
Upvotes: 2