Saturday, January 9, 2010

System Calls

In order to perform I/O with the console, SPIM provides a small library of system calls. In general, system calls are set up by placing a system call in register $v0, and any arguments in register $a0 and $a1. Returned values are placed in register $v0. See the table and the example program below for usage.


Service
System Call Code
Arguments
Result
Print_int
1
$a0 = integer


Print_float
2
$f12 = float


Print_double
3
$f12 = double


Print_string
4
$a0 = string


Read_int
5


Integer (in $v0)
Read_float
6


Float (in $f0)
Read_double
7


Double (in $f0)
Read_string
8
$a0 = buffer, $a1 = length


Sbrk
9
$a0 = amount
Address (in $v0)
exit
10






# This program takes input from the user and echoes it back


.data
# Constant strings to be output to the terminal
promptInt: .asciiz "Please input an integer: "
resultInt: .asciiz "Next integer is: "
linefeed: .asciiz "\n"
enterkey: .asciiz "Press any key to end program."


.text
main:
# prompt for an integer
li $v0,4 # code for print_string
la $a0,promptInt # point $a0 to prompt string
syscall #print the prompt
# get an integer from the user
li $v0,5 # code for read_int
syscall #get int from user --> returned in $v0
move $t0,$v0 # move the resulting int to $t0
# compute the next integer
addi $t0, $t0, 1 # t0 <-- t0 + 1
# print out text for the result
li $v0,4 #code for print_string
la $a0,resultInt # point $a0 to result string
syscall # print the result string
# print out the result
li $v0,1 # code for print_int
move $a0,$t0 # put result in $a0
syscall # print out the result
# print out a line feed
li $v0,4 # code for print_string
la $a0,linefeed # point $a0 to linefeed string
syscall # print linefeed
# wait for the enter key to be pressed to end program
li $v0,4 # code for print_string
la $a0,enterkey # point $a0 to enterkey string
syscall # print enterkey
# wait for input by getting an integer from the user (integer is ignored)
li $v0,5 # code for read_int
syscall #get int from user --> returned in $v0
# All done, thank you!
li $v0,10 # code for exit
syscall # exit program

No comments:

Post a Comment