1

I am trying to increment the eax variable by 2 within a procedure followed by pushing the eax value onto the stack/passing the result to printf:

; nasm -f elf test.asm && gcc -m32 -o test test.o

section .text
global main
extern printf

add_by_2:
        add     eax, 2
        push    eax
        push    message
        call    printf
        add     esp, 8
        ret
        
main:
        mov     eax, 1
        call    add_by_2
        call    add_by_2
        call    add_by_2
        ret

message db "%d", 0xa, 3, 0

After the third call the eax variable is not incremented by 2.

stdout:

3
5
5

Expected stdout:

3
5
7

What is wrong with this code? How do I correct the code to correctly increment eax by 2 even after the third call to add_by_2. I am open to any method to increment the number stored in eax by two (even if I need to use other registers).

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
code455
  • 11
  • 2
  • 1
    The call to `printf` potentially overwrites the value in EAX. EAX, ECX, EDX are volatile registers in the 32-bit System V ABI so can be clobbered https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl .EAX happens to be the return value for `printf` which contains the total number of characters printed. – Michael Petch Nov 01 '20 at 15:51
  • Is there a workaround to this? If you have a solution I'll accept the answer. – code455 Nov 01 '20 at 15:56
  • 4
    Use EBX, ESI, EDI instead of EAX since they don't get clobbered by `printf`. You could also save EAX in `add_by_2` by pushing the value in EAX (`push eax`) on the stack at the start of the function and restoring it before the `ret` by using `pop eax`. In `add_by_2` You could move the value in EAX to EBX, EDI, OR ESI before the call to `printf` and move it back to EAX after the call to `printf`. – Michael Petch Nov 01 '20 at 16:04
  • The output you get is the expected output -- printf returns the number of characters printed in EAX. Each call to printf prints 3 character (a digit, a newline, and a ctrl-C), so will return 3. – Chris Dodd Nov 02 '20 at 02:27

0 Answers0