Home > Mobile >  What does x86 `movq %rsp, (%rdi)` and `movq (%rsi), %rsp` do and how are they different?
What does x86 `movq %rsp, (%rdi)` and `movq (%rsi), %rsp` do and how are they different?

Time:09-27

I am playing with some "just for fun" code that implements custom threading.

Of course, it has to implement context switching too, and this bit comes from the context-switching function:

        movq %rsp, (%rdi)
        
        movq (%rsi), %rsp

I am not that much familiar with x86 and assembly in general and having hard times to figure out what is happening.

Seems to me that movq (%rsi), %rsp dereferences a (virtual) memory address stored in the %rsi and copies 8 bytes (since q) to the %rsp.

However, I can't figure out what does the movq %rsp, (%rdi) line do? (%rdi) seems to be a target register, i.e. the one that will take new value.. however it does not match with the brackets around it... as far as I understand (...) means dereferencing..

Please, explain.

CodePudding user response:

Correct, (%register) means to dereference the value in the register and use it as a memory location.

So (in AT&T syntax):

movq %rsp, (%rdi) means "copy the value in rsp to the location whose memory address is stored in rdi".

and

movq (%rsi), %rsp means "copy the value from the location whose memory address is stored in rsi to rsp".

The purpose appears to be to save the current stack pointer (save location pointed to by rdi) and load a new stack pointer (load location pointed to by rsi) during a thread switch.

  • Related