Input & output

Input & output

All input/output goes through ecall. Think of ecall (environment call) as the mechanism your assembly code uses to request services from the operating system or simulator. Your program cannot directly control the screen or keyboard hardware; it must pause and ask the host system for permission and assistance.

Put the service number in a7, any argument in a0, then trigger ecall. The services this simulator knows:

Services (a7)
1   print integer   (a0 = number)
4   print string    (a0 = address of text)
5   read integer    (result returned in a0)
10  exit program
32  sleep           (a0 = milliseconds)
Read a number, double it, print it
li a7, 5         # read integer -> a0
ecall

add a0, a0, a0   # double it

li a7, 1         # print integer
ecall

li a7, 10
ecall

Read it line by line. li a7, 5 selects read-integer and ecall pauses for input, returning your number in a0. add a0, a0, a0 adds a0 to itself, doubling it in place. Then li a7, 1 and ecall print the result, and li a7, 10 and ecall exit. When you Run it, the simulator pops up an input box; type a number and watch it come back doubled.

Printing text

Two new words first. A section is a labeled region of your program: instructions live in the .text section, while fixed data like text lives in the .data section. And an address is just a number that identifies one slot in memory. Instead of carrying a whole string around, a register can carry the address where the string begins, and the print service reads from there.

Text lives in the data section. You give it a label, then load that label's address with la ("load address") and print with service 4.

Hello, RISC-V
.data
msg: .string "Hello, RISC-V!\n"

.text
la a0, msg       # a0 = address of the text
li a7, 4         # print string
ecall

li a7, 10
ecall

Here .data reserves the text and labels it msg; .string stores the characters plus \n, a newline. In .text, la a0, msg loads the address of that text into a0, li a7, 4 selects print-string, and ecall prints from that address until it reaches the end of the string. Then the usual exit.