X86 pointer deviation

I am reading my tutorial and it has code for the swap function:

In C:

int exchange(int *xp, int y) { int x = *xp; *xp = y; return x; } 

In x86 build with annotations:

 // xp is at %ebp + 8, y at %ebp + 12 movl 8(%ebp), %edx // get xp movl (%edx), %eax // get x at xp movl 12(%ebp), %ecx // get y movl %ecx, (%edx) // store y at xp 

So, from my understanding, if int * xp pointed to int I am at address A, then the first line of assembly code stores A in% edx. Then it becomes dereferenced in the second row and stored in% eax.

If this is true, I wonder why line 1 "8 (% ebp)" does not play the pointer, storing int I in% edx instead of address A? Isn't that what parentheses do in an assembly?

Or does this mean that when pointers are pushed onto the stack, the address of the pointer is pushed, not the value it has, so that 8 (% ebp) technically contains & xp?

I just wanted to clarify if I understood correctly.

+7
c assembly pointers x86 att
source share
2 answers

xp is a pointer. It has a value of four bytes. This value is pushed onto the stack by the calling function. The prolog function you did not specify sets the base pointer to ebp . The xp value is stored at offset 8 relative to this base pointer.

So, the first line of code separates the base pointer, as indicated by brackets, with an offset of 8 to extract the xp value (which is the address that points to int) and puts it in edx .

The second line of code uses the address in edx to get the int value and puts that value in eax . Note that the return value of the function will be the value in eax .

The third line plays the base pointer at offset 12 to get the y value.

The fourth line uses the address in edx to place y at the location xp points to.

+5
source share

%bp is a pointer to the stack that must be deferred before I can access anything on the stack. Thus, movl 8 (% bp),% edx` selects a value that is at offset 8 in the current frame frame.

This value is a pointer, so we must play it in order to access its contents, regardless of whether it is read or written.

OTOH, y is an int, so getting it is just movl 12(%ebp), %ecx and no further actoin is required.

So movl %ecx, (%edx) is the right thing: put the value stored in ecx in the memory pointed to by edx .

+2
source share

All Articles