movq assembly function

2019-03-12 03:06发布

问题:

I was reading some code and was not sure what this line does:

movq (%rsp), %rsp

回答1:

movq (assuming you're talking about x86) is a move of a quadword (64-bit value). This particular instruction:

movq (%rsp), %rsp

looks very much like code that will walk up through stack frames. This particular instruction grabs the quadword pointed to by the current stack pointer, and loads it into the stack pointer, overwriting it.

By way of example, this code sequence (based on real code, and in Intel rather that AT&T format) will continuously load the stack pointer from its contents until the value 16 bytes beyond it is 0.

576  cmpq    [rsp+0x10],0x0
582  jz      594
588  movq    rsp,[rsp]
592  jmp     576
594  ...

It's possible it may not be stack-frame walking code but it's be unusual since it would be suborning the stack pointer for something it's not usually used for.

It is unusual in that moving up stack frames usually involves stack pointer and base pointer but that's usually for just going up one level (i.e., a return from a function).

For the sort of code shown above where you want to move up multiple levels, it's probably faster to just use the stack pointer until you get where you need to be, then pop the base pointer off then (calling conventions will often push the current base pointer before changing it, so that a simple pop will recover the old value).



回答2:

It is a 64bit value mov. Its 64bit because of the "q" in movq which is quad and quad is 64bit.

There can be other example such as movl in which l is 32 bit.

but in the case of movq (%rsp), %rsp using ATT syntax..

The movq (%rsp), %rsp -> movq is called opcode, (%rsp) is called source or src and %rsp is called the destination or the dst.

what it does is that it looks up in register %rsp gets its value and goes to the memory [the bracket "()" means going into memory value] of that value and then assigns it to %rsp.

While both are same register the difference is that the value of %rsp changes.

EG:lets say %rsp has value 22. But the memory of %rsp is 30.

Using this instruction movq (%rsp), %rsp

the new value of %rsp is 30. Again because (%rsp) gets the value of %rsp which is assume 22 and then (%rsp) goes to the memory value 30 and then assigns it to %rsp on the destination, which is %rsp itself.