//---------------------------------------------------------------- // fact.s // // In this assembly language file we implement a "recursive" // function that returns N-factorial for N from zero to ten. // (It can be called by high-level language C/C++ programs.) // // assemble using: $ as fact.s -o fact.o // // programmer: ALLAN CRUSE // written on: 30 NOV 2003 // revised on: 15 APR 2008 -- to correct a comment statement //---------------------------------------------------------------- # symbol for the argument's offset from the base-pointer .equ N, 8 # offset for argument N .section .text #----------------------------------------------------------------- factorial: # # This procedure employs recursion to compute N-factorial for an # unsigned integer N whose value is pushed onto the stack by the # caller. The function-value is returned in register EAX. Note # that the function-argument must be discarded from the stack by # the calling routine rather than by the routine that is called. # push %ebp # preserve frame-pointer movl %esp, %ebp # setup local stackframe push %edx # save register contents cmpl $0, N(%ebp) # argument equals zero? jne recur # no, perform recursion movl $1, %eax # else setup value = 1 jmp factx # and return to caller recur: movl N(%ebp), %eax # get function argument dec %eax # reduce argument value push %eax # push (N-1) onto stack call factorial # and get its factorial add $4, %esp # then discard argument mull 8(%ebp) # multiply N * (N-1)! factx: pop %edx # recover reg contents pop %ebp # restore frame-pointer ret # then return to caller #----------------------------------------------------------------- .global factorial # make entry-point public .end # no more to be assembled