Sahil Chitnis
Sahil Chitnis

Reputation: 35

x86 assembly recursive function -> Illegal instruction error

Code1: implements main function which calls fact (factorial) function

section .data
    msg db "Enter the Number whose factorial is to be calculated",10,0
    msg1 db "The factorial is: ",0
    ioput db "%d"

section .bss
    a resd 1

section .text
    global main
    extern printf,scanf,fact
main:   
    pusha 
    push msg
    call printf
    add esp,4
    popa

    pusha 
    push a
    push ioput
    call scanf
    add esp,8
    popa

    mov ebx,dword[a]

    pusha
    push ebx
    call fact
    add esp,4


    pusha
    push msg1
    call printf
    add esp,4
    popa

    pusha
    push eax
    push ioput
    call printf
    add esp,8
    popa

    ret

Code2 which implements fact (factorial function):

section .text
    global fact
    extern printf,scanf
fact:   
    enter 0,0
    cmp ebx,1
    jnz next
    ret

next:
    push ebx
    dec ebx
    call fact
    pop ebx
    mul eax,ebx
    leave
    ret

System stats: 32 bit machine, Ubuntu 14.04, Nasm is used

Problem statement: Program received signal SIGILL, Illegal instruction. Why am I getting this error?

Upvotes: 1

Views: 1070

Answers (1)

Sep Roland
Sep Roland

Reputation: 39676

mov ebx,dword[a]

pusha
push ebx
call fact
add esp,4

This is the part of your program that has some problems!

  1. You need to initialize EAX to get meaningful results from calling fact. A convenient number would be 1.
  2. Since you used pusha you also need to use popa. I would have preferred none because your code doesn't really need it.
  3. The fact routine doesn't use a parameter passed on the stack. It simply uses the EBX register for that purpose. This means that you can omit push ebx and add esp,4 and also that you could remove the enter and leave instructions from fact.

This is the code you could write to solve it all.

mov ebx,dword[a]
mov eax,1
pusha
call fact
mov [esp+28],eax
popa

A shorter version is

mov ebx,dword[a]
mov eax,1
call fact

Upvotes: 2

Related Questions