78687
78687

Reputation: 9

x86 mov instruction in C pointer of different size

I'm trying to replicate an x86 mov instruction, such as mov %ecx,-0x4(%ebp) in C and am confused about how to do it. I have an int array for the registers and an int displacement. How would I move the value of %ecx into the memory address 4 less than the value stored in %ebp?

I have:

int* destAddress=(int*)(displacement + registers[destination]);
*destAddress=registers[source];

I'm getting a Warning: cast to pointer from integer of different size.

Upvotes: 0

Views: 503

Answers (1)

Cody Gray
Cody Gray

Reputation: 244672

mov %ecx,-0x4(%ebp)

or, in Intel syntax:

mov DWORD PTR [ebp-4], ecx

is storing the value in ECX into the memory location [ebp-4].

EBP is the "base pointer" and is commonly used (in unoptimized code) to access data on the stack. Based on the negative offset, this instruction is almost certainly storing the value of ECX into the first DWORD-sized local variable.

If you wanted to translate this to C, it would be:

int local = value;

assuming that value is mapped to the ECX register, and local is a local variable allocated on the stack. Really, that's it.

[Except that a C compiler would generally put a local variable like this in a register, so this would really translate to something more like mov edx, ecx. The only time it would spill to stack would be if it ran out of registers (which isn't uncommon in the very register-poor x86 ISA).

Alternatively, you could force it to spill by making the variable volatile: volatile int local = value;.
But there is no good reason for doing that in real code.]

There is pointer dereferencing going on here under the hood, of course, as you see in the assembly-language instruction, but it doesn't manifest in the C representation.

If you wanted to get some pointer notation in there, say you had an array of values allocated on the stack, and wanted to initialize its first member:

int array[4];
array[0] = value;   // set first element of array to 'value' (== ECX)

The displacement (-4) won't appear at all in the C code. The C compiler handles that.

Upvotes: 1

Related Questions