2

I just started learning assembly and I'm having trouble. I know plenty of Python and some c++. I'm using MASM with VS 2022. My first assembly program was calculating Fibonacci numbers:

.code

main proc
    MOV rcx, 13
    call fib
    ;Now I would like to access the 5th fib number.
    ret
main endp


fib proc
    MOV r8, 0
    MOV r9, 1

  fibBody:
    CMP rcx, 0
    jz endFib
    DEC rcx

    MOV r10, r8
    MOV r8, r9
    ADD r9, r10
    JO endFib
    JMP fibBody

  endFib:
    MOV rax, r8
    RET

fib endp
end

You load a number into rcx, call fib which will calculate fib(rcx) and put the result into rax. Now returning the result by putting it into rax, returning main which results in the exitcode fib(rcx) (the value stored in rax) is bad way of doing this.

My question is: How can I store the result after each step in RAM and how do I access the results outside of fib? Can I just push r9 after each calculation and after the function call LEA r10, [rsp + "some number"] to look at any fib number I calculated?

Finding information is very hard if you don't actually know what you need and because there are so many different types of assembly (I barely know how to ADD let alone know/see the differences between assemblers) I'm having a lot of trouble.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 2
    "Can I just `push r9` after each calculation and after the function" No, because the `call` and `retn` instructions also use the stack, so you normally have to balance the stack (run as many `pop` instructions as you did `push` instructions prior) before returning from your function. You can use a global array variable, or pass a size and a pointer to an array (could be global, heap, or stack) to your subfunction for its use as an output buffer. – ecm Mar 05 '22 at 13:50
  • 2
    [Assembly Language (x86): How to create a loop to calculate Fibonacci sequence](https://stackoverflow.com/q/32659715) has an example of a function that takes a pointer + length and stores Fibonacci numbers into an array. It's in NASM syntax, but for registers it's the same. For example of doing things in MASM syntax, you can look at compiler output from MSVC. (https://godbolt.org/ and related: [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) applies partly to MSVC) – Peter Cordes Mar 05 '22 at 13:54

0 Answers0