Search code examples
memorystackwebassemblystack-memory

How can I store a value on the stack at a constant address in the memory in Webassembly?


I have a value on the stack, and I want to store it at a constant address in memory. Would the operation take the address from the stack first, I could put the address on the stack and store the value without problems, like this:

;; This does not work.
;; ↑ a value to be stored on the stack
i32.const 0 ;; the constant memory address
i32.store

But the address is supposed to be behind the value to be stored, so I need to get it there somehow. How can I do that? To get behind the value on the stack, I need to store the value temporarily somewhere, so I need to put it to the memory, but I can't because I need an address behind the value for that. This is a circular problem which I can't figure out.


Solution

  • To get behind the value on the stack, I need to store the value temporarily somewhere, so I need to put it to the memory

    You can also declare local variables in WebAssembly, e.g.:

    
    ;; first line within a function
    (local i32)
    
    ;; store temporary value to the local, 2 here is an index,
    ;; e.g. if the function had two parameters, they have index 0
    ;; and 1, and then this local have index 2.
    (local.set 2 (i32.const 4))
    
    ;; reads a value from the local and put it on the stack:
    (local.get 2)
    
    

    This is a circular problem which I can't figure out.

    By using any number of locals that you need in the function, you can use them as temporary places to hold values. But you need to declare the number and type of them, in the beginning of the function.

    See MDN WebAssembly - Local for more info about locals.