1

I am currently new to and learning assembly language (primarily with NASM)

In one of the tutorials that I was following, the instructor did

;Input codes, entry points, etc.

_showAge:
    mov rax, 1
    mov rdi, 1
    mov rsi, ageTxt
    mov rdx, 13
    syscall ;"Your age is: "

    mov rax, 1
    mov rdi, 1
    mov rsi, age
    mov rdx, 3
    syscall
    ret

And it works as intended. But when I attempted to shortened the code myself...

_showAge:
    mov rax, 1
    mov rdi, 1
    mov rsi, ageTxt
    mov rdx, 13
    syscall ;"Your age is: "

    mov rsi, age
    mov rdx, 3
    syscall ; Doesn't do anything
    ret

This does not do anything anymore,
My question is what is the reasoning behind why can't we do the following code as shown above?

(This script was tested and ran in Linux x86_64, Ubuntu)

WQYeo
  • 3,973
  • 2
  • 17
  • 26
  • 1
    `rax` is used for the return value so you can't rely on its value being unchanged. `rdi` is preserved. – Jester Jun 15 '18 at 12:35
  • 1
    Point 2 of the x86-64 section of the answer on the duplicate is "*A system-call is done via the syscall instruction. **This clobbers %rcx and %r11, as well as %rax**, but other registers are preserved*." Use `strace` to see what system calls your code actually made. (e.g. with `eax=13` from the write return value, assuming it succeeds). – Peter Cordes Jun 15 '18 at 12:38
  • rtfm https://software.intel.com/en-us/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-1-2a-2b-2c-2d-3a-3b-3c-3d-and-4 – sivizius Jun 16 '18 at 10:30
  • For a list of registers affected and unaffected in syscalls see https://stackoverflow.com/questions/18024672/what-registers-are-preserved-through-a-linux-x86-64-function-call – JasonY Dec 29 '20 at 15:17

1 Answers1

4

System calls return their result in rax. Thus, whatever was in rax before the system call won't be there afterwards. For technical reasons, the rcx and r11 registers are destroyed by system calls, too. All other registers have their contents preserved by the kernel.

fuz
  • 88,405
  • 25
  • 200
  • 352