2

I have a 64 bit register which holds a memory address. If I perform an arithmetic operation on the lower half of the register and then try to dereference it, I get a segmentation fault. Here is an example:

movsx rax, BYTE PTR [rdi]  # ok
add edi, 1 # the address is correct but....
movsx rax, BYTE PTR [rdi] # segmentation fault here

If I change edi to rdi in line 2 it works, so I am just wondering why I can't use the lower half of rdi in this case. I would also appreciate it if anyone has any links/references with information about the proper use of the lower parts of registers.

Thanks a lot for your help.

ds1848
  • 172
  • 6

2 Answers2

5

When you do operations on a edi or any other 32-bit bottom-half register, it automatically zeros the top half of the whole register.

Therefore the upper 32-bits of rdi will be zero after the add edi, 1.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • As for why the behavior is like this (rather than leaving the upper-half untouched), my guess is that it breaks a lot of false-dependencies and drastically helps with register renaming. – Mysticial Apr 21 '12 at 05:55
  • I see -- now it makes sense. The reason why I couldn't figure it out was because I was using printf to show the address and used the format specifier "%X" instead of "%lX" -- so it looked to me like the address was 32 instead of 64 bits. Well well -- thanks a lot for the help. – ds1848 Apr 21 '12 at 18:33
  • [Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?](//stackoverflow.com/q/11177137) yes, the obvious reason is to avoid false dependencies, making it possible for 32-bit operand-size to be efficient (and usable as the default). – Peter Cordes Oct 31 '19 at 06:14
4

From the "AMD64 Architecture Programmer’s Manual Volume 1: Application Programming"

3.1.2 64-bit Mode Registers:

In general, byte and word operands are stored in the low 8 or 16 bits of GPRs without modifying their high 56 or 48 bits, respectively. Doubleword operands, however, are normally stored in the low 32 bits of GPRs and zero-extended to 64 bits.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • Thanks a lot for the link. For whatever reason the link from the AMD site does not work for me, but I was able to get it [here](http://www.google.com/url?sa=t&rct=j&q=amd64+programmer%27s+manual&source=web&cd=7&ved=0CFYQFjAG&url=http%3A%2F%2Fwww.serc.iisc.ernet.in%2Ffacilities%2FComputingFacilities%2Fsystems%2Ftyrone%2FApplication%2520Programming.pdf&ei=tf2ST8_hNcHSgQf08un-BA&usg=AFQjCNGQXSCC-sr7kJBjr20LZKo8jmnI8g). Thanks again. – ds1848 Apr 21 '12 at 18:38