Léo Eduardo Silva
Léo Eduardo Silva

Reputation: 141

Stack in Assembly

I need help with a code in Assembly.

I'm coworking on this and my group just did this Assembly code where it supposed to do the same as what I did in #c.

Could someone help me to understand what happens with de stack at least on the first steps so I can go on and conclude the rest?

I'm a begginer in Assembly, but I know that these lines just save the value for the calling function, takes a frame for the called function and save space for local variables, but I can't figure out the next first steps.

mov ebp
mov ebp,esp
sub esp, 16

Here is what I did in #c:

void mult_integer(int X[A_Linhas][A_Colunas], int number)
{
  int c, l;

  for (l = 0; l < A_Linhas; l++)
  {
    for (c = 0; c < A_Colunas; c++)
    {
      X[l][c] = number * X[l][c];
    }
  }
}

And here is the code in Assembly:

mul_integer:
        push    ebp 
        mov     ebp, esp 
        sub     esp, 16 
        mov     dword [ebp-4H], 0
        jmp     L_020

L_017:  mov     dword [ebp-8H], 0
        jmp     L_019

L_018:  mov     edx, dword [ebp-4H]
        mov     eax, edx
        add     eax, eax
        add     eax, edx
        shl     eax, 2
        mov     edx, eax
        mov     eax, dword [ebp+8H]
        lea     ecx, [edx+eax]
        mov     edx, dword [ebp-4H]
        mov     eax, edx
        add     eax, eax
        add     eax, edx
        shl     eax, 2
        mov     edx, eax
        mov     eax, dword [ebp+8H]
        add     edx, eax
        mov     eax, dword [ebp-8H]
        mov     eax, dword [edx+eax*4]
        imul    eax, dword [ebp+0CH]
        mov     edx, eax
        mov     eax, dword [ebp-8H]
        mov     dword [ecx+eax*4], edx
        add     dword [ebp-8H], 1
L_019:  cmp     dword [ebp-8H], 2
        jle     L_018
        add     dword [ebp-4H], 1
L_020:  cmp     dword [ebp-4H], 3
        jle     L_017
        nop
        leave
        ret

Upvotes: 0

Views: 2177

Answers (1)

Krii
Krii

Reputation: 907

When I write mov edx, [ebp-4] or +4, or -4, +8, -8 what am I doing with the stack, exactly?

Take a look at the stack (diagram from Wikipedia's Call Stack article). Note that low memory addresses are at the top of this diagram, while higher memory address are at the bottom.

stack layout with a frame pointer

The frame pointer is stored in register ebp (on x86). It contains the address of the Return Address.

Your local variables are stored before the Return Address. Variable c is 4 bytes in size. By subtracting 4 from the ebp address, you are now pointing to your first local variable, c. Subtract another 4 (making it -8), and you're now pointing to your second local variable l.

Upvotes: 5

Related Questions