Note Lead by Obfuscation 

Forum: U Chicago, Com Sci 221, autumn 2000
Date: 2000, Nov 06
From: C. Donour Sizemore donour

#I mentioned how MIPS does something a little more basic than
#most ISA's which recursion.  Here's an example.  You'll
#notice the recursive procedure, hanoi, does the stack
#allocation manually.  In theory the jal (jump-and-link)
#procedure could do this, but the designers decided against
#it.  If those of you who aren't familiar with MIPS, sw=store
#word and lw= load word.

#################
# TOWERS OF HANOI 
#################

	        .data
enter_string:	.asciiz "Enter number disks "
move_string:	.asciiz "Move disk "
from_string:	.asciiz " from peg "
to_string:	.asciiz " to peg "			
newline:        .asciiz "\n"
badnum:         .asciiz "Invalid Entry"
        .text

        .globl main

	# MAIN PROCDURE 	
main:
	# setup stack for main procedure
	sub $sp, $sp, 4	# allocate space for stack pointer
        sw $ra, 0($sp)	# store stack pointer

	# enter the number of disks
	li $v0, 4
	la $a0, enter_string
	syscall

	# read in number of disks -- result in $v0
	li $v0, 5
	syscall

	# load arguments to hanoi procedure
	move $a0, $v0
	li $a1, 1
	li $a2, 2
	li $a3, 3

	# call hanoi procedure
	jal hanoi

	# return from main
	lw $ra, 0($sp)  # restore the stack pointer
	add $sp, $sp, 4	# deallocate the stack space

        # in theory, return 0 from main
        add $v0, $zero, $zero
	j $ra

	# HANOI PROCDURE 	
hanoi:
	# test for $a0 = 0, if so just return
	beq $a0, $zero, baseCase

	# else, do the everything inside the if
	# so, now we need to push all args on stack and save the ra
	sub $sp, $sp, 20
	sw $a0, 0($sp)
	sw $a1, 4($sp)
	sw $a2, 8($sp)
	sw $a3, 12($sp)
	sw $ra, 16($sp)

	#rearrange arguments regs for first call to hanoi
	sub $a0, $a0, 1
	move $t0, $a3
	move $a3, $a2
	move $a2, $t0

	#first call to hanoi
	jal hanoi

	#print move disk string
	li $v0, 4
	la $a0, move_string
	syscall

	#print disk #
	li $v0, 1
	lw $a0, 0($sp)
	syscall

	#print from peg string
	li $v0, 4
	la $a0, from_string
	syscall

	#print disk #
	li $v0, 1
	lw $a0, 4($sp)
	syscall

	#print to peg string
	li $v0, 4
	la $a0, to_string
	syscall

	#print disk #
	li $v0, 1
	lw $a0, 8($sp)
	syscall

	#print newline
	li $v0, 4
	la $a0, newline
	syscall

	# prep to 2nd call to hanoi
	lw $a0, 0($sp)
	sub $a0, $a0, 1 # subtract 1 from restored number of disks
	lw $a1, 12($sp)
	lw $a2, 8($sp)
	lw $a3, 4($sp)

	# call hanoi the 2nd time
	jal hanoi

	# restore ra and sp prior to return
	# please note, you don't need to restore the args since
	# they are read from the stack by the calling proc
	lw $ra, 16($sp)
	add $sp, $sp, 20

baseCase:	
        j $ra


Messages

1. Question questions concerning obfuscation by Michael C. Brizic, 2000, Nov 06
(_ Feedback Untitled by C. Donour Sizemore, 2000, Nov 08

to: "Lead by Obfuscation"