Monday, April 6, 2020

MIPS register - immediate addition overflow (addi)

This is sample MIPS assembler code demonstrating register - immediate addition (addi instruction) overflow. It detects addition overflow using MIPS hardware overflow simulation supported by EzMIPS, the MIPS assembler editor & simulator. The code is fully commented.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.

# -------------- Register - Immediate addition overflow ----------- #

.data

szMenu:         .ascii  "Detect register - immediate addition overflow?\n"
                .ascii  "----------------------------------------------\n"
                .ascii  "1. Runtime exception: arithmetic overflow\n"
                .asciiz "2. Exit\n"

.text

main:

# ........ Test the addition overflow of 2 positive numbers ...... #

    li $t4, 0x7fffffff      # = 2147483647
    
    # OVERFLOW!!!
    # 0x7fffffff + 0x00000001 = 0x80000000
    # 2147483647 + 1          = -2147483648

# ... Uncomment to test addition overflow of 2 negative numbers .. #

    #li $t4, 0x80000000     # = -2147483648

    # OVERFLOW!!!
    # 0x80000000  + 0xffffffff = 0x7fffffff
    # -2147483648 + -1         = 2147483647

# ................................................................ #
    
    li $t1, 1
    li $t2, 2

# ................................................................ #

print_menu:

    # print menu
    li $v0, 4
    la $a0, szMenu
    syscall

# ................................................................ #
    
    # get user input
    li $v0, 5
    syscall
    # $v0 holds user input

    beq $v0, $t2, exit
    bne $v0, $t1, print_menu

# ................................................................ #
    
    # Runtime exception: arithmetic overflow of two positive numbers
    # .................................... #
    addi $t0, $t4, 0x1      # addition with Overflow Runtime exception

    # Uncomment the following line to test #
    # .................................... #
    # Runtime exception: arithmetic overflow of two NEGATIVE numbers 
    #addi $t0, $t4, 0xffff   # addition with Overflow Runtime exception

    j print_menu            # if no runtime exception occured, print menu

# ................................................................ #

exit:

    li $v0, 10
    syscall

# ---------------------------------------------------------------- #

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment