b15
b15

Reputation: 2351

Ret illegal instruction

I'm working with a project that implements a function in assembly that is called in a main.c. The signature function declaration in C is void strrev(char *str) ; The Ret instruction is giving me an illegal instruction error. Why? This is my first time doing this.

Trying to only post the relevant code:

SECTION .text
        global strrev

strrev:
        push    ebp
        mov     ebp, esp

        push    esi
        push    edi
        push    ebx

// doing things with al, bl, ecx, edi, and esi registers here


// restore registers and return    
        mov     esp,    ebp
        pop     ebx
        pop     edi
        pop     esi
        pop     ebp

        ret

Error:

(gdb)
Program received signal SIGILL, Illegal instruction.
0xbffff49a in ?? ()

Compiling and linking this way:

nasm -f elf -g strrepl.asm
nasm -f elf -g strrev.asm
gcc -Wall -g -c main7.c
gcc -Wall -g strrepl.o strrev.o main7.o

Upvotes: 1

Views: 840

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222679

mov esp, ebp changes esp to point to where it was when mov ebp, esp was executed. That was before you pushed esi, edi, and ebx onto the stack, so you can no longer pop them. Since you do, the stack is wrong, and the ret does not work as desired.

You can likely delete the mov esp, ebp instruction. Restoring the stack pointer like that is needed only if you have variable changes to the stack pointer in the routine (e.g., to move the stack to a desired alignment or to make space for a variable-length array). If your stack is handled simply, then you merely pop in reverse order of what you push. If you do have variable changes to the stack, then you need to restore the pointer to a different location, not the ebp you have saved, so that you can pop ebx, edi, and esi.

Upvotes: 4

Related Questions