I'm very very new to assembly so please bear with me.
I have this code that passes a value by reference to a function in order to modify it :
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
static void Main()
{
int a = 5 ;
Modify(ref a);
Console.WriteLine(a);
}
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
static void Modify (ref int a )
{
a = 77 ;
}
the generated assembly fot that code is
Program.Main()
L0000: push ebp
L0001: mov ebp, esp
L0003: push eax
L0004: xor eax, eax
L0006: mov [ebp-4], eax ******* (the confusing part 1 )
L0009: mov dword ptr [ebp-4], 5
L0010: lea ecx, [ebp-4]
L0013: call dword ptr [0xa9dc6ac]
L0019: mov ecx, [ebp-4]
L001c: call System.Console.WriteLine(Int32)
L0021: mov esp, ebp
L0023: pop ebp
L0024: ret
my question is : in the instruction L0006 : mov [ebp-4], eax this will copy the value of the register eax into the memory location pointed to by Ebp-4 but Ebp-4 does not point to anything ? what I'm missing ?
Modify
doesn't need to pass a pointer to work correctly. It needs to receive in the current value and return the output value. Which it does. The fact that it doesn't use pointers is an implementation detail.mov [ebp-4], eax
overwrites the same memory location with a constant5
, so the previous store is dead. I hope this is un-optimized assembly. The actual setup of the function arg islea ecx, [ebp-4]
, passing the address of that stack variable in the first arg-passing register, ECX. (Forfastcall
, which I assume this must be using otherwise the LEA makes no sense.)a
by pushingeax
: that stack space is located atebp-4
. Then it doesa=0
as a standard initializer thena=5;
as your code. Next it passes the value&a
, which is computed byebp-4
toModify
by ref inecx
, and later retrieves the value ofa
to pass to WriteLine by value.ebp-4
is an address, the address ofa
. We don't know the value of this address, but that it is on somewhere near the top of the stack. Stored at that address, is the variablea
, which holds (1st) garbage, (2nd) 0, (3rd) 5, and (4th) presumably 77.