CSC231 FibOverflowDWord.asm

From dftwiki3
Jump to: navigation, search
;;; fibOverflowDWord.asm
;;; D. Thiebaut
;;; computes fibonacci until overflow
;;; requires driver.c, asm_io.o, and asm_io.inc
;;; 
;;; compile and link as follows:
;;;
;;;  nasm -f elf -F stabs fibOverflow.asm
;;;  gcc -o fibOverflow driver.c asm_io.o fibOverflow.o
;;; 
%include "asm_io.inc"
        
%assign EXIT        1

        ;; -------------------------
        ;; data segment
        ;; -------------------------
        section .data
msg1    db      "fib(",0
msg2    db      ") = ",0


        section .bss
N       equ     1000        
fib     resd    N               ; reserve 100 bytes
        
        ;; -------------------------
        ;; code area
        ;; -------------------------
        section .text
        global  asm_main

;;; ---------------------------------------------------------
;;; main program
;;; ---------------------------------------------------------
asm_main:       

;;; fib[0] = 1;
;;; fib[1] = 1;
;;; for ( i=2; i<100; i++ ) {
;;;     temp = fib[i-1]+fib[i-2];
;;;     if ( temp <= 0 ) break;
;;;     fib[i] = temp;
;;; }
        mov     dword[fib], 1
        mov     dword[fib+4], 1

        mov     esi, 2*4        ; esi is 2*i
for:    cmp     esi, N*4
        jge     done
        
        mov     eax, dword[fib+esi-1*4]
        add     eax, dword[fib+esi-2*4]
        cmp     eax, 0
        jle     done
        mov     dword[fib+esi], eax
        call    printFibi
        add     esi,4
        jmp     for
        
done:   ret        
        
;;;     print "fib( %d ) = %d" % (i, fib(i) )
        
printFibi:      
        push    eax             ; save fib(i) in stack
        push    esi             ; save i in stack
        mov     eax, msg1        
        call    print_string    ; prints "fib( "

        pop     eax             ; get esi in eax
        shr     eax, 1          ; because esi grows by 4 every time
        shr     eax, 1          
        call    print_int       ; print i

        mov     eax, msg2       ; print ") = "
        call    print_string
        
        pop     eax             ; get fib(i) back from stack
        call    print_int       ; print fact(i)

        call    print_nl        ; next line
        ret