Converting i386 to x86-64 assembler
Originally published on csvensson.blogspot.com. View saved original ↗
One Linux topic there really is a limited amount of information about on the web is converting i386 assembly into x86-64. At a surface level there's not huge differences, x86-64 has an extra 8 general purpose registers, so less has to be put on the stack (& of course all registers are now 64 bit).
As a rule of thumb the x86-64 equivalent GPR registers all start with an r for addressing them in 64 bit mode (this is required for certain operations such as stack manipulation). Then the normal instructions are used, except that they are postfixed with a q (quad word) instead of l (long) for manipulating them. i.e.
movl (%ebx), %eax becomes movq (%rbp), %rax
What can be a subtle annoyance is that syscall numbers & the registers for passing arguments to the Linux kernel have all changed in x86-64. The register associations can be viewed in /usr/src/linux/arch/x86_64/kernel/entry.S & the mapping to syscalls on your system can be found in /usr/include/asm-x86_64/unistd.h
This article (http://www.milw0rm.com/papers/110) contains a nice summary of what has changed & is more accessible then the information on the x86-64.org web site (http://www.x86-64.org/)
For instance to perform the open system call, in i386 we have:
movl $5, %eax
movl 8(%ebp), %ebx # assuming we want the second memory location on the stack
movl $0, %ecx
movl $0644, %edx
int $0x80
In x86-64 this becomes (note the change in registers, & sycall no. from 5 to 2)
movl $2, %eax
movq 16(%rbp), %rdi
movl $0, %esi
movl $0644, %edx
int $0x80
We could safely replace all instances of movl with movq providing we were using GPR's 64 bit counterparts (%rax, ...), however, this is clearly unnecessary as 32 bit is clearly adequate for storing the remaining arguments.
Also, any operations working on the stack need to be performed using 64 bit addressing, hence the 8 byte offsets used for accessing variables on it (of course using popq would take this into account automatically).
Cite this post
Conor Svensson (21 February 2007). Converting i386 to x86-64 assembler. https://conorsvensson.com/archive/blogspot/converting-i386-to-x86-64-assembler/
BibTeX
@misc{svensson2007-converting-i386-to-x86-64-assembler,
author = {Conor Svensson},
title = {{Converting i386 to x86-64 assembler}},
year = {2007},
month = feb,
url = {https://conorsvensson.com/archive/blogspot/converting-i386-to-x86-64-assembler/}
}