0

I am trying to code a program which prints the squares between 1 and 5 in assembly. But the output is not as expected. The function calling conventions used are those of UNIX.

My code:

            .intel_syntax noprefix
            .data
msg:        .asciz "%d: %d\n"
            .text
            .global main
            .type main, @function
main:       PUSH RBP
            MOV RBP, RSP
            MOV RSI, 1  # i = 0
square:     MOV RAX, RSI
            MUL RSI
            MOV RDI, offset flat:msg
            MOV RDX, RAX
            CALL printf
            INC RSI
            CMP RSI, 5
            JB square
            MOV EAX, 0
            POP RBP
            RET

Output: 1: 1

Daniel
  • 1
  • 2
  • 1
    If you don't know debugging, now is a great time to learn. It works the same in most languages: step line-by-line and see if you're getting the results you're expecting. In assembly language, the registers are key, as is the stack memory referred to by a register. Verify your program state is correct in between each single step during debugging. It's a short program so shouldn't be too hard. You should step over functions like `printf`, and since it is a function, you'll need to verify the program state more completely than with, say `MOV RSI, 1`, where we really only expect one effect. – Erik Eidt Aug 19 '22 at 22:21
  • First try the above, if you don't find anything and you think there's something going wrong with the stack, maybe share what with us.. – Erik Eidt Aug 19 '22 at 22:31
  • 2
    Check the calling convention. You are expecting caller-saved registers to be preserved by `printf` when they aren't. Also, you did not set up `AL` before calling `printf` (must be set to the number of floating-point arguments when calling a function with a variable argument list). – fuz Aug 19 '22 at 22:49
  • You're going to want to keep your running-total product and loop counter in call-preserved registers like RBX and R12. e.g. `imul rbx, r12` / ... / `inc r12` / `cmp r12, 5` – Peter Cordes Aug 19 '22 at 23:40

0 Answers0