MIPS system calls — theory with character creation, the number you must save before it vanishes and the Enter that sneaks into strings (and the character who was always 4 years old)

Fifth IC1 lab session. Until then my programs were monologues: the data came written in .data and QtSpim just showed me the result. That day the program had to ask. It looked like the easiest thing in the world: ask for the character’s age with read_int, print a nice label and then the age. This is what I wrote:

# hook.s: the character's age (or so I thought)
        .data
page:   .asciiz "Character age: "
tage:   .asciiz "Age recorded: "
        .text
        .globl main
main:   la $a0, page         # $a0 = the message asking for the age
        li $v0, 4            # print_string
        syscall
        li $v0, 5            # read_int: the age arrives in $v0
        syscall
        la $a0, tage         # before the number, its text
        li $v0, 4            # print_string
        syscall
        move $a0, $v0        # $a0 = the age (or so I thought)
        li $v0, 1            # print_int
        syscall
        li $v0, 10           # exit
        syscall

I loaded it, pressed F5, typed 19 into the console and got this:

Character age: 19
Age recorded: 4

I tried 25. «Age recorded: 4». 80. «Age recorded: 4». My character was 4 years old whatever I said. It took me a good while to see it: the number the user types arrives in $v0… and the li $v0, 4 I wrote to print the label overwrites it before I copy it. The 4 didn’t come from anywhere strange: it was the code of print_string.

The lesson is the most important idea of this topic and you’ll see it in every program: whatever a system call gives back must be saved before you make the next one. Today we learn to talk to the user: the syscall sequence and its table of services, printing with messages people can read, reading integers with read_int, reading text with read_string (and the \n it leaves at the end), read_char and its trap, reading several numbers into an array, turning typed digits into a number and building a menu with a table of addresses. I’m coming from MIPS arrays and strings, so I take arrays, indexing with sll and strings with their '\0' as known. Everything is tested in QtSpim (if you don’t have it handy yet, see how to use QtSpim), and at the end you have the site’s MIPS playground embedded so you can type yourself.

Before you start. You need three things from the earlier topics. First, the difference between an address and a value: la $a0, label puts in $a0 where the data is, and lw $a0, label puts in what is inside (you have it in MIPS program structure and data). Second, .space to reserve bytes, strings that end in '\0' and the index scaled with sll, from arrays and strings in MIPS. Third, reading QtSpim’s Data tab, with the bytes of each word reversed (little endian). The topic goes in this order: first, what a system call is and the usual sequence (arguments, code, syscall, result); then, printing properly; then, the three reads (an integer in $v0, a string in a buffer and a character), each with what it leaves in the registers and in memory; and finally, three exam uses: several numbers into an array, typed digits turned into a number, and a menu. If you get lost at any point, ask yourself two things: where does this service leave what it gives me? And which line is going to overwrite it?

What syscall does

Before the sequence, the idea in words. When my hook.s asks for the age, the program can’t go to the screen and write letters, or go to the keyboard and look at what was pressed. It isn’t forbidden on a whim: the screen and the keyboard belong to every program running at the same time, and each device has its own way of working (waiting for a key to arrive, knowing which column the cursor is in…). If every program handled them its own way, one could overwrite another’s output, and all of them would have to carry the code for every device inside.

That’s why there is a single one in charge of those devices: the operating system. Your program doesn’t touch the screen; it asks the system to write for it. It’s like an online game: your character doesn’t write into the server’s database, it asks for an action and the server does it or not. A system call is that request, and syscall is the instruction that makes it. All your program needs to know is how to ask: which registers it leaves the request in, and where the answer is left for it.

The CPU knows how to add, load and jump, but it knows nothing about keyboards or screens. That’s the operating system’s job (in QtSpim, the simulator’s). syscall is the instruction that hands over the ball: «stop for a moment, system, I need something». And how does the system know what you need? By looking at the registers. Always with the same sequence:

  1. Arguments in $a0 (and $a1 if the service needs two): the number to print, the address of the string or of the buffer, the size…
  2. Service code in $v0: 1 to print an integer, 4 for a string, 5 to read an integer…
  3. syscall.
  4. Result: if the service returns something, it lands in $v0 (or in the buffer, for read_string). Collect it now.
The sequence of a syscall and its servicesFour steps: set up the arguments in $a0 and $a1, put the service code in $v0, run syscall and collect the result, which arrives in the buffer or in $v0. Below, the table of services 1, 4, 5, 8, 10, 11 and 12 with what each one takes and what it returns; the three reads are highlighted.A system call, step by step (read_string of the name)1Argumentsla $a0, nameli $a1, 16where and how much2Codeli $v0, 8which service3syscallsyscallthe system works4Resultin the buffer(or in $v0)collect it nowThe services you will use in QtSpim$v0serviceyou giveyou get back1print_int$a0 = integer—4print_string$a0 = address—5read_int—integer in $v08read_string$a0 = buffer, $a1 = sizetext in the buffer10exit——11print_char$a0 = character—12read_char—character in $v0
The green rows are the reads: what they return lands in $v0 or the buffer, and you have to collect it before the next syscall.

Look at the table in the drawing: the green rows are the reads, the only ones that give you something back. The print services just consume what you give them. There are more services (the floating-point ones, 2, 3, 6 and 7, use the $f registers), but with these seven you can do everything in the lab and in the exams.

If you search online you’ll find programs with li $v0, 36 to print an unsigned number. That’s a MARS service, another simulator. It doesn’t exist in SPIM or QtSpim: you get «Unknown system call: 36». Stick to the table.

Does the order of steps 1 and 2 matter? Not to the system: it only looks at the registers at the moment of the syscall. But get used to setting the arguments first and the li $v0 last, right above the syscall. That way, when you read the code, each li $v0 tells you which service is being requested on that line, and none sneaks in between.

The sequence, line by line

This is how the four steps look in the first six instructions of age.s, the hook once fixed. The user types 19 and presses Enter:

StepLineRegisters afterWhy
1. Argumentla $a0, page$a0 = address of the messageprint_string wants to know where the letters start, not the letters
2. Codeli $v0, 4$v0 = 44 means «print a string»
3. CallsyscallNothing changes; «Character age: » appearsThe system looks at $v0, sees a 4, reads $a0 and prints up to the '\0'
2. Codeli $v0, 5$v0 = 5read_int has no arguments: step 1 is skipped
3. Callsyscall$v0 = 19The system waits for the user to type and press Enter, and leaves the number in $v0, on top of the 5
4. Resultmove $s0, $v0$s0 = 19I get it out before the next li $v0 overwrites it

Look at the fourth column: what the system does depends only on what is in the registers at the moment of the syscall. It doesn’t know which line came before or what you meant to do. If $v0 holds a 1, it prints an integer, even if $a0 holds an address (that’s why a huge number comes out in the error a few lines further down).

The system calls in this topic only change what the last column of the table of services says. The printing ones touch no register; read_int and read_char write to $v0; read_string writes to the buffer’s memory and leaves $v0 as it was (I checked in SPIM: after reading a name, $v0 is still 8). What the system never does is save anything for you somewhere else on its own.

Check you’ve got it: with $a0 = 75, what comes out with li $v0, 1 and what with li $v0, 11?

With li $v0, 1 you get 75: service 1 (print_int) writes the number in decimal. With li $v0, 11 you get a K: service 11 (print_char) takes the same 75 as the code of a character, and 75 is K (you’ll see it again with read_char). The value in $a0 is the same in both cases; what changes is which service $v0 asks for and, therefore, how the system interprets it. Checked in SPIM: the two calls in a row, with a space in between, print 75 K.

Printing messages people can read

In earlier topics we already printed with services 1, 4 and 11. Now it’s time to do it well: output that reads like a character card and not a string of numbers. Three tools:

  • \n inside a string: newline. Put it where you want the next line to start (at the beginning of the next string or at the end of the previous one, but pick one rule).
  • \t: tab. It jumps to the next tab stop (in the outputs of this article, every 8 characters), so it helps line up columns.
  • print_char (service 11) for single characters: a repeated =, a space, a comma. SPIM accepts the character in single quotes as an immediate: li $a0, '='.
# card.s: print data from memory with friendly messages
        .data
level:  .word 1              # the character's level
gold:   .word 250            # gold coins
name:   .asciiz "Kira"
t1:     .asciiz "Character:\t"
t2:     .asciiz "\nLevel:\t\t"
t3:     .asciiz "\nGold:\t\t"
        .text
        .globl main
main:   li $t0, 20           # 20 '=' signs
line1:  li $a0, '='          # $a0 = the character
        li $v0, 11           # print_char
        syscall
        addi $t0, $t0, -1
        bgtz $t0, line1      # repeat while there are some left
        li $a0, '\n'         # newline after the line
        li $v0, 11
        syscall
        la $a0, t1           # "Character:" + tab
        li $v0, 4
        syscall
        la $a0, name         # the stored string
        li $v0, 4
        syscall
        la $a0, t2           # newline, "Level:" and two tabs
        li $v0, 4
        syscall
        lw $a0, level        # print_int wants the VALUE, not the address
        li $v0, 1
        syscall
        la $a0, t3
        li $v0, 4
        syscall
        lw $a0, gold
        li $v0, 1
        syscall
        li $a0, '\n'
        li $v0, 11
        syscall
        li $v0, 10
        syscall
====================
Character:	Kira
Level:		1
Gold:		250

Between the lines:

  • The line of 20 = is a loop with print_char. A .asciiz "====================" would also work, but this way you see that print_char prints whatever is in $a0 as a character: 61, which is =.
  • "\nLevel:\t\t": the newline goes at the start, so each string begins its own line and the previous one doesn’t have to remember to close it. Two tabs because «Level:» has 6 letters: with only one, the 1 would land in column 8 and the name in column 16 (after «Character:», which has 10). With two, all three values end up in column 16.
  • lw $a0, level and not la $a0, level. print_int prints the number in $a0. With la you’d print the address of level (268500992, which is 0x10010000 in decimal). With print_string it’s the other way round: it wants the address, which is why it’s la $a0, name.

la $a0, gold + li $v0, 1. No error: it prints a huge number (the address). If you see 2685009… on the console, you’ve given print_int an address instead of a value.

read_int: the number arrives in $v0 (and leaves quickly)

read_int (service 5) needs no arguments. It waits for the user to type a number and press Enter, and leaves it in $v0. That’s the hook’s problem: $v0 is both the place where you put the service code and where the system leaves you the result. The next syscall you prepare will start with li $v0, …, and at that moment the number disappears.

The age lasts in $v0 until the next li $v0Two columns with the instructions of hook.s and age.s and the value of $v0 after each one. In hook.s, read_int leaves 19 in $v0, but li $v0, 4 changes it to 4 before the move, and 4 is printed. In age.s, move $s0, $v0 right after the syscall saves the 19 and the later li does no harm.What $v0 holds after each line (the age typed is 19)hook.s (wrong)$v0li $v0, 55syscall19the age arrivesla $a0, tage19li $v0, 44the age is lostsyscall4move $a0, $v04$a0 = 4age.s (right)$v0li $v0, 55syscall19the age arrivesmove $s0, $v019$s0 = 19la $a0, tage19li $v0, 44no harm nowmove $a0, $s04$a0 = 19Result: «Age recorded: 4» on the left and «Age recorded: 19» on the right.
$v0 is both the service code and the result of the reads: whatever arrives must be moved out before the next li $v0.

Look at both columns. On the left, my version: the 19 arrives, survives the la (which doesn’t touch $v0) and dies at li $v0, 4. On the right, the good one: the first thing after the syscall is moving it to another register.

# age.s: read an integer and save it before the next syscall
        .data
age:    .word 0              # the age stays here
page:   .asciiz "Character age: "
tage:   .asciiz "Age recorded: "
        .text
        .globl main
main:   la $a0, page
        li $v0, 4            # print_string
        syscall
        li $v0, 5            # read_int
        syscall
        move $s0, $v0        # FIRST of all: get the age out of $v0
        sw $s0, age          # and, if needed, to memory
        la $a0, tage
        li $v0, 4            # now I can overwrite $v0
        syscall
        move $a0, $s0        # the age was safe in $s0
        li $v0, 1            # print_int
        syscall
        li $v0, 10
        syscall
Character age: 19
Age recorded: 19

Two lines fix everything:

  • move $s0, $v0 right after the syscall. I use $s0 because it’s a «saved» register (you’ll see why that matters in the subroutines topic); in a short program a $t works too. What doesn’t work is leaving it in $v0.
  • sw $s0, age: in the lab many tasks ask for the data read to be stored in memory. With a label in .data and an sw you’ve got it, and you can also see the 19 in the Data tab (0x13).

Write the move as part of the same «sentence» as the syscall: li $v0, 5 / syscall / move $s0, $v0. Three lines that always go together. If when reviewing you see a reading syscall without its move (or its sw) underneath, you know where to look.

What if the user types letters instead of a number? read_int gives no error: it keeps the digits at the start (with «12abc» you get 12) and, if there are none, leaves 0. That’s why, when the number has to be within a range (an age, a menu option), you check it yourself with blt/bgt, as you’ll see in the menu.

The age, from $v0 to memory

The two-column drawing follows $v0. What’s missing is where the 19 ends up when the task says «store the data read in memory». In age.s, age is the first label in .data, so it is at 0x10010000:

MomentAddressBytesWhy
On loading0x10010000 – 0x1001000300 00 00 00.word 0 reserves a word set to zero
After the read_int syscallsame00 00 00 00The system leaves the 19 in $v0, not in memory
After move $s0, $v0same00 00 00 00move copies from register to register; memory never finds out
After sw $s0, age0x100100001319 = 0x13, the least significant byte, at the lowest address
0x10010001 – 0x1001000300 00 00The rest of the word

In the Data tab you see it as [10010000] 00000013. What comes from the keyboard always goes through a register before reaching memory: it’s the sw that leaves it in age, not the system call.

Check you’ve got it: if in hook.s I put move $a0, $v0 right below the read_int syscall, is it fixed?

No. The 19 gets out of $v0 in time, but I leave it in $a0, and the next line is la $a0, tage, which needs $a0 to tell print_string where the text is. That’s where the age is lost. Then li $v0, 1 prints whatever is left in $a0: the address of tage. In hook.s, page takes 16 bytes (15 characters and the '\0'), so tage is at 0x10010010, which in decimal is 268501008. It comes out as «Age recorded: 268501008». It’s the same bug as before with another register: a register you are going to use as an argument for the next call is no good for keeping anything. That’s why the age goes to $s0, which no syscall uses.

read_string: the buffer, its size and the \n at the end

To read text, the system needs to know where to leave it and how much fits. Those are the two arguments of read_string (service 8):

RegisterWhat goes inExample
$a0Address of the buffer, a gap reserved with .spacela $a0, name
$a1Size of that buffer in bytesli $a1, 16
$v08li $v0, 8

Why the size? Because, to the system, name is just a number: 0x10010000. It doesn’t know there’s a .space 16 behind it, or where the gap ends, or that the text of pname starts right after. Labels disappear when assembling; only bytes are left in memory. If you don’t tell it how much fits, the system has no way of knowing when to stop. This is the memory of name.s before reading:

AddressContentsBelongs toWhy
0x10010000 – 0x1001000F16 bytes set to 00name.space 16 reserves 16 bytes set to zero: that’s the buffer
0x1001001043 (C)pnameThe next text starts right behind it, with no gap
0x10010011 onwardsh, a, r, a…pname«Character name: » and its '\0'

With $a0 = 0x10010000 and $a1 = 16, the system can write from 0x10010000 to 0x1001000F and nothing more. 0x10010010 already belongs to someone else.

read_string returns nothing in $v0: what is read goes straight into the buffer. Let’s read the character’s name and greet them:

# name.s: read the name with read_string
        .data
name:   .space 16          # buffer: up to 15 characters + '\0'
pname:  .asciiz "Character name: "
hello:  .asciiz "Hello, "
done:   .asciiz "! Your adventure starts now.\n"
        .text
        .globl main
main:   la $a0, pname
        li $v0, 4          # print_string
        syscall
        la $a0, name       # $a0 = where to leave the text
        li $a1, 16         # $a1 = size of the buffer
        li $v0, 8          # read_string
        syscall
        la $a0, hello
        li $v0, 4
        syscall
        la $a0, name       # the name exactly as read_string left it
        li $v0, 4
        syscall
        la $a0, done
        li $v0, 4
        syscall
        li $v0, 10
        syscall
Character name: Kira
Hello, Kira
! Your adventure starts now.

And that newline between «Kira» and the exclamation mark? Look at what read_string left in memory. The buffer is at the start of .data, at 0x10010000:

[10010000]    6172694b  0000000a  00000000  00000000    K i r a . . . . . . . . . . . .

The bytes of the first word, reversed (QtSpim is little endian): 4b K, 69 i, 72 r, 61 a. And the second word starts with 0a: code 10, the newline. When the user presses Enter, that Enter is a character too, and read_string stores it with the rest. Then comes the '\0' that closes the string. When printing it, print_string writes K, i, r, a… and the newline.

What read_string leaves in the bufferThree rows of boxes, one per byte. With Kira and a 16-byte buffer you get K, i, r, a, the newline (0a) and the final zero. After removing the newline there is a 00 in its place. With Alejandrina and an 8-byte buffer only seven letters are stored, A l e j a n d, and the zero: there is no newline.The bytes in the buffer after read_string (real dump)name.syou type Kira + Enter, .space 16K4bi69r72a61\n0a\000\000\000\000\000\000\000\000\000\000\000nonewline.safter finding the \n and doing sb $zeroK4bi69r72a61\000\000\000\000\000\000\000\000\000\000\000\000long.syou type Alejandrina, .space 8A41l6ce65j6aa61n6ed64\000↑ the newline read_string leaves↑ only 7 letters: no room for \n
read_string stores at most N − 1 characters, the \n only if it fits, and always closes with \0.

This is what read_string does with «Kira» and Enter, byte by byte ($a0 = 0x10010000, $a1 = 16):

StepAddressWritesWhy
10x100100004b (K)The first character goes where $a0 points
20x1001000169 (i)One per byte, in order
30x1001000272 (r)
40x1001000361 (a)4 of the 15 characters that fit so far
50x100100040a (\n)Enter is a character too, and it still fits
60x1001000500 ('\0')Closes the string; now it’s an .asciiz
—0x10010006 – 0x1001000FuntouchedThe zeros from .space are still there

The rule under the drawing, in numbers: with $a1 = N, N − 1 characters fit, because the last byte is always for the '\0'. If what you type, counting the Enter, is N − 1 characters or fewer, it goes in whole with its \n. If not, the system cuts at N − 1 and the \n doesn’t go in.

Check you’ve got it: with .space 16 and li $a1, 16, what’s the longest name that fits with its \n? And what happens with a 15-letter one?

16 − 1 = 15 characters fit, plus the '\0'. If you want the \n to go in too, 14 are left for letters: a 14-letter name takes 14 bytes, the \n goes in the 15th (0x1001000E) and the '\0' in the 16th (0x1001000F), the last one in the buffer. With 15 letters the buffer fills up with them and the '\0': the \n doesn’t fit, just like in long.s, and it stays waiting for the next read. Checked in SPIM with ABCDEFGHIJKLMN (14 letters: ends in 10 and 0) and ABCDEFGHIJKLMNO (15 letters: ends in 79, the O, and 0). That’s why nonewline.s has the beqz $t1, trimmed exit: with 15 letters there’s no \n to look for.

Removing the leftover \n

The fix is the one the exam cheat sheet lists in its checklist: walk through the buffer up to the '\n' and write a '\0' on top. The string now ends where the newline was.

# nonewline.s: read the name and remove the '\n' at the end
        .data
name:   .space 16          # buffer: up to 15 characters + '\0'
pname:  .asciiz "Character name: "
hello:  .asciiz "Hello, "
done:   .asciiz "! Your adventure starts now.\n"
        .text
        .globl main
main:   la $a0, pname
        li $v0, 4
        syscall
        la $a0, name
        li $a1, 16
        li $v0, 8          # read_string
        syscall
        la $t0, name       # $t0 walks through the buffer
seek:   lbu $t1, 0($t0)    # current character
        beq $t1, '\n', cut # found the newline: out
        beqz $t1, trimmed  # '\0' with no newline (the text filled the buffer)
        addi $t0, $t0, 1   # next character
        j seek
cut:    sb $zero, 0($t0)   # the '\n' becomes the end of the string
trimmed: la $a0, hello
        li $v0, 4
        syscall
        la $a0, name
        li $v0, 4
        syscall
        la $a0, done
        li $v0, 4
        syscall
        li $v0, 10
        syscall
Character name: Kira
Hello, Kira! Your adventure starts now.

The loop has two exits, and both are needed:

  • beq $t1, '\n', cut: I found the newline. sb $zero, 0($t0) changes it to a 0 and that’s it (second row of the drawing: where there was 0a there’s now 00).
  • beqz $t1, trimmed: I reached the '\0' without seeing any newline. When does that happen? When the text fills the buffer. Without this exit, the loop would keep reading memory beyond the buffer looking for a 10 that isn’t there.
Step$t0 points toByteWhat it does
1name + 04b (K)Not \n or 0: moves on
2name + 169 (i)Moves on
3name + 272 (r)Moves on
4name + 361 (a)Moves on
5name + 40a (\n)Jumps to cut: sb $zero at name + 4

When the text doesn’t fit

What does read_string do if the user types more than fits? It stores at most $a1 − 1 characters and keeps the last byte for the '\0'. With an 8-byte buffer and the name «Alejandrina»:

# long.s: a name that doesn't fit in the buffer
        .data
name:   .space 8             # only 7 characters + '\0' fit
pname:  .asciiz "Character name: "
open:   .asciiz "Stored: ["
close:  .asciiz "]\n"
        .text
        .globl main
main:   la $a0, pname
        li $v0, 4
        syscall
        la $a0, name
        li $a1, 8            # the same size as the .space
        li $v0, 8            # read_string
        syscall
        la $a0, open         # I print it between brackets to see
        li $v0, 4            # exactly where it ends
        syscall
        la $a0, name
        li $v0, 4
        syscall
        la $a0, close
        li $v0, 4
        syscall
        li $v0, 10
        syscall
Character name: Alejandrina
Stored:   [Alejand]
[10010000]    6a656c41  00646e61  72616843  65746361    A l e j a n d . C h a r a c t e

Seven letters (41 6c 65 6a 61 6e 64), a 00 and no newline: it didn’t fit. That’s the third row of the drawing. The rest («rina» and the Enter) isn’t completely lost: it stays waiting and the next read in the program takes it (I checked in QtSpim: a read_int after a name that was too long didn’t even let me type). Moral: reserve buffers with room to spare and put the same number in $a1 as in the .space.

name: .space 8 and li $a1, 16. You tell the system that 16 bytes fit where there are only 8: if the user types a long name, read_string writes over whatever comes next in .data (the next message, a number…). Neither QtSpim nor anyone else warns you.

Forgetting the li $a1 altogether. The system doesn’t complain: it uses whatever is in $a1 at that moment. If it’s 0 or 1, there’s only room for the '\0' and the name comes out empty («Hello, ! Your adventure…»). If it’s a big number, the system believes it. In console spim, at the start of main, $a1 holds 2147453744, so name.s without its li $a1, 16 seems to work… until someone types a long name.

I tried it with «Alejandrina the Valiant»: 23 letters, the \n and the '\0' make 25 bytes. The first 16 fit in name; the next 9 (Valiant, the \n and the '\0') land on top of the start of pname. The greeting comes out fine, but if you print pname afterwards you no longer get «Character name: », but «Valiant». It’s the worst kind of bug: no error, and it shows up far from the line that causes it.

read_char and the Enter key

read_char (service 12) reads one character and leaves it in $v0. It looks perfect for a «Save? (y/n)», but it has a trap that’s best seen with numbers. This program reads two characters in a row and prints their codes:

# key.s: two read_char in a row
        .data
p1:     .asciiz "Character initial: "
p2:     .asciiz "Guild initial: "
t1:     .asciiz "Codes read: "
t2:     .asciiz " and "
        .text
        .globl main
main:   la $a0, p1
        li $v0, 4
        syscall
        li $v0, 12           # read_char: the character arrives in $v0
        syscall
        move $s0, $v0
        la $a0, p2
        li $v0, 4
        syscall
        li $v0, 12           # read_char again
        syscall
        move $s1, $v0
        la $a0, t1
        li $v0, 4
        syscall
        move $a0, $s0        # I print the CODES, not the characters,
        li $v0, 1            # to see exactly what arrived
        syscall
        la $a0, t2
        li $v0, 4
        syscall
        move $a0, $s1
        li $v0, 1
        syscall
        li $v0, 10
        syscall

I type a K and press Enter:

Character initial: K
Guild initial: Codes read: 75 and 10

K is 75. And the second one? 10: the Enter. The program didn’t even let me type the guild initial, because the newline was already waiting and the second read_char took it.

I checked it in QtSpim 9.1.24, the one in the lab: there read_char takes the key as soon as you press it, without waiting for Enter. If you only press K and then G, all is well. But if you press Enter out of habit (and almost everyone does after typing something), that Enter is the character the next read gets. In the site’s MIPS playground you always type a line and press Send, so the newline always arrives.

The same problem shows up when mixing reads: a read_char followed by a read_int or a read_string. The leftover Enter reaches the next read, which takes it as an empty line.

The safe way to ask y/n

For a yes/no question there’s a way that works the same in QtSpim, on the web and whatever the user presses: read the whole line with read_string into a small buffer and only look at the first letter. The Enter stays inside the buffer, where it does no harm.

# yesno.s: a y/n question reading the whole line
        .data
ans:    .space 8           # plenty of room for "y", "yes", "no"...
quest:  .asciiz "Save the game? (y/n): "
yes:    .asciiz "Game saved.\n"
no:     .asciiz "Nothing is saved.\n"
        .text
        .globl main
main:   la $a0, quest
        li $v0, 4
        syscall
        la $a0, ans
        li $a1, 8
        li $v0, 8          # read_string: takes the Enter too
        syscall
        lbu $t0, ans       # I only look at the first letter
        beq $t0, 'y', save
        beq $t0, 'Y', save # also in capitals
        la $a0, no
        j out
save:   la $a0, yes
out:     li $v0, 4
        syscall
        li $v0, 10
        syscall
Save the game? (y/n): y
Game saved.

lbu $t0, ans loads the first byte of the buffer, and two beq compare with 'y' and 'Y' (SPIM accepts the quoted character as an immediate). Anything else («n», «no», an empty line) goes the «no» way. An 8-byte buffer so that answers like «yes» fit with their Enter and nothing is left over for the next read.

Reading N numbers into an array

It’s what the exam’s optional parts ask for most: «modify the program so that the user enters the elements of the array from the keyboard». With topic 4 you already have almost everything: a loop with the index, sll for the offset and, instead of loading, storing what arrives in $v0.

# stats.s: read 4 numbers into an array and show it
        .data
stats:  .word 0, 0, 0, 0     # strength, magic, agility, health
n:      .word 4
pstat:  .asciiz "Stat "
colon:  .asciiz ": "
tvec:   .asciiz "Stats: ["
comma:  .asciiz ", "
tend:   .asciiz "]\nTotal: "
        .text
        .globl main
main:   lw $s1, n            # $s1 = 4
        li $s0, 0            # i = 0
read:   beq $s0, $s1, display
        la $a0, pstat        # "Stat "
        li $v0, 4
        syscall
        addi $a0, $s0, 1     # the user counts from 1
        li $v0, 1
        syscall
        la $a0, colon        # ": "
        li $v0, 4
        syscall
        li $v0, 5            # read_int
        syscall
        sll $t0, $s0, 2      # offset = i * 4
        sw $v0, stats($t0)   # stats[i] = what was read (before another syscall)
        addi $s0, $s0, 1
        j read
display: la $a0, tvec
        li $v0, 4
        syscall
        li $s0, 0            # i = 0
        li $s2, 0            # total = 0
walk:    beq $s0, $s1, final
        beqz $s0, number     # no comma before the first one
        la $a0, comma
        li $v0, 4
        syscall
number: sll $t0, $s0, 2
        lw $a0, stats($t0)   # $a0 = stats[i]
        add $s2, $s2, $a0    # total += stats[i]
        li $v0, 1
        syscall
        addi $s0, $s0, 1
        j walk
final:  la $a0, tend
        li $v0, 4
        syscall
        move $a0, $s2
        li $v0, 1
        syscall
        li $v0, 10
        syscall

I type 6, 9, 3 and 2:

Stat 1: 6
Stat 2: 9
Stat 3: 3
Stat 4: 2
Stats: [6, 9, 3, 2]
Total: 20

The important bits:

  • sw $v0, stats($t0) right after the syscall. No move needed here: the sw already takes the number out of $v0 and puts it in its place before another syscall overwrites it.
  • addi $a0, $s0, 1 before print_int: the user counts from 1 («Stat 1»), the array from 0. You add when printing; you don’t change the index.
  • The comma. To get [6, 9, 3, 2] and not [6, 9, 3, 2, ], the comma goes before every number except the first (beqz $s0, number skips it when i = 0). That’s easier than trying to know which one is the last.
Passi ($s0)OffsetI typestats afterwards
10066, 0, 0, 0
21496, 9, 0, 0
32836, 9, 3, 0
431226, 9, 3, 2

Total: 6 + 9 + 3 + 2 = 20, the one on the console.

If the array is made of bytes (.byte), what you read is stored with sb $v0, v($t0) and without sll, because each element takes one. Watch the range: a signed byte only holds numbers from −128 to 127, and reading it back with lb gives you the same value. If the user types 300, only the low byte is stored (300 − 256 = 44).

From text to number

Sometimes the number arrives as text. That happens when you read with read_string because you want to check what the user typed character by character (a code, an account number, a numeric PIN), or because you need each digit separately. The buffer doesn’t hold the number 2048: it holds the characters '2', '0', '4', '8', which are codes 50, 48, 52 and 56.

Two ideas solve it:

  • Character → digit: subtract the code of '0', which is 48. '2' (50) − 48 = 2.
  • Digits → number: go from left to right doing n = n · 10 + digit. Each pass shifts what you already had one place to the left.
# number.s: from the characters "2048" to the number 2048
        .data
buf:    .space 12
pcode:  .asciiz "Invitation code: "
tnum:   .asciiz "Number: "
tdbl:   .asciiz "\nDouble it: "
terr:   .asciiz "Only digits are allowed.\n"
        .text
        .globl main
main:   la $a0, pcode
        li $v0, 4
        syscall
        la $a0, buf
        li $a1, 12
        li $v0, 8            # read_string: CHARACTERS arrive
        syscall
        la $t0, buf          # pointer to the text
        li $s0, 0            # n = 0
        li $t3, 10
digit:  lbu $t1, 0($t0)      # c = current character
        beq $t1, '\n', ready # end of what was typed
        beqz $t1, ready      # or end of the string
        blt $t1, '0', error  # outside the range '0'..'9'
        bgt $t1, '9', error
        addi $t1, $t1, -48   # c - '0': the character '2' (50) becomes 2
        mul $s0, $s0, $t3    # n = n * 10 ...
        add $s0, $s0, $t1    # ... + the new digit
        addi $t0, $t0, 1
        j digit
ready:  la $a0, tnum
        li $v0, 4
        syscall
        move $a0, $s0
        li $v0, 1
        syscall
        la $a0, tdbl         # proof that it's a real number
        li $v0, 4
        syscall
        add $a0, $s0, $s0
        li $v0, 1
        syscall
        j quit
error:  la $a0, terr
        li $v0, 4
        syscall
quit:   li $v0, 10
        syscall
Invitation code: 2048
Number: 2048
Double it: 4096
From four characters to one numberTable by columns for the characters 2, 0, 4 and 8: their ASCII code (50, 48, 52, 56), the digit after subtracting 48 and the running value n = n·10 + digit, which goes 2, 20, 204 and 2048. The newline (10) ends the loop.number.s: the buffer holds "2048\n"; n starts at 0charactercodec − '0'n · 10 + cn'2'5020·10 + 22'0'4802·10 + 020'4'52420·10 + 4204'8'568204·10 + 82048'\n'10stopIf something outside '0'..'9' turns up (a space, a letter), the program jumps to error instead of adding garbage.
Each pass shifts the earlier digits one place to the left (× 10) and adds the new one on the right.

The double (4096) is there to prove that $s0 holds a real number you can do maths with. If you forget the −48, the loop does sums with the codes: 50, 50·10 + 48 = 548… and the result looks nothing like it.

The two range checks (blt $t1, '0' and bgt $t1, '9') are what save you from a space or a letter: without them, an «a» (97) would turn into the digit 49 and the number would come out absurd with no warning.

The opposite direction (from a number to its digits as characters) isn’t needed in QtSpim to print, because print_int already does it. But if you have digits stored as numbers (0 to 9) and want to print them together, a print_int for each works; if you want to put them into a string, add 48.

A menu with a table of addresses

Last ingredient: the menu. The user picks a number and the program answers with a different text for each option. You could do it with a chain of beq (if it’s 1, print this; if it’s 2, that…), but with many options it goes on forever. The lab trick is a table of addresses: an array of words where each element is the address of a string.

classes: .word cg, cm, ca    # three words: three ADDRESSES

When assembling, SPIM replaces each label with its address. The chosen option becomes an index and lw brings the address of the string, ready for print_string.

# menu.s: choose a class with a table of addresses
        .data
classes: .word cg, cm, ca     # table: the ADDRESS of each name
cg:     .asciiz "Warrior"
cm:     .asciiz "Mage"
ca:     .asciiz "Archer"
pmenu:  .asciiz "Choose a class:\n 1) Warrior\n 2) Mage\n 3) Archer\nOption: "
tbad:   .asciiz "Invalid option.\n"
tclass: .asciiz "Chosen class: "
        .text
        .globl main
main:   la $a0, pmenu
        li $v0, 4
        syscall
        li $v0, 5             # read_int: 1, 2 or 3
        syscall
        move $s0, $v0
        blt $s0, 1, bad       # validate BEFORE using it as an index
        bgt $s0, 3, bad
        addi $t0, $s0, -1     # the user counts from 1; the table, from 0
        sll $t0, $t0, 2       # each address takes 4 bytes
        lw $s1, classes($t0)  # $s1 = address of the chosen name
        la $a0, tclass
        li $v0, 4
        syscall
        move $a0, $s1         # print_string with the address from the table
        li $v0, 4
        syscall
        li $v0, 10
        syscall
bad:    la $a0, tbad
        li $v0, 4
        syscall
        j main                # ask again

I type a 7 first and then a 2:

Choose a class:
 1) Warrior
 2) Mage
 3) Archer
Option: 7
Invalid option.
Choose a class:
 1) Warrior
 2) Mage
 3) Archer
Option: 2
Chosen class: Mage

In the Data tab you can see the three addresses at the start of the segment, followed by the texts:

[10010000]    1001000c  10010014  10010019  72726157    . . . . . . . . . . . . W a r r
[10010010]    00726f69  6567614d  63724100  00726568    i o r . M a g e . A r c h e r .
A table of addresses for the menuOn the left, the three words of the classes table with the real addresses of the strings; each one points with an arrow to its string. On the right, the calculation for option 2: subtract 1, multiply by 4 with sll and load with lw the address of the second string, which goes to $a0 for print_string.menu.s: the classes table stores addresses, not text+00x1001000cclasses[0]0x1001000c"Warrior"+40x10010014classes[1]0x10010014"Mage"+80x10010019classes[2]0x10010019"Archer"Option: 2addi $t0, $s0, -1 # 1sll $t0, $t0, 2 # 4lw $s1, classes($t0)move $a0, $s1li $v0, 4$a0 = 0x10010014
lw does not bring the text: it brings where it is. print_string does the rest.

Step by step, with option 2:

  1. Validate: blt $s0, 1, bad and bgt $s0, 3, bad. If it isn’t between 1 and 3, message and ask again with j main. This goes before working anything out.
  2. Index: 2 − 1 = 1, because the user counts from 1 and the table from 0.
  3. Offset: 1 · 4 = 4 with sll, because each address is a word.
  4. lw $s1, classes($t0): loads the word at classes + 4, which is 0x10010014, the address of "Mage".
  5. print_string with that address in $a0.

Why is step 1 so important? Because lw doesn’t know where your table ends. With a 7 it would load the word at classes + 24, which sits in the middle of the texts, and print_string would get a meaningless address. In the exercises there’s a whole snippet devoted to that mistake.

The table can have as many columns as you like with the same index: a table of names, another of descriptions, another of prices… All in the same order, and the same offset works for all three. You’ll see it in the practice.

When the console does strange things

SymptomLikely causeFix
The number read shows as 1, 4, 5, 8 or 11Another syscall overwrote $v0 before it was savedmove or sw right after the reading syscall
A newline in the middle of the greetingThe \n that read_string leavesFind it and sb $zero on top
The name comes out cut shortThe buffer or $a1 are too small.space with room to spare and the same number in $a1
A read doesn’t let you typeAn Enter (or text that didn’t fit) was left over from the previous readRead whole lines with read_string; big buffers
A huge number shows up (268500…)print_int with an address (la) instead of the value (lw)lw $a0, label
A menu prints the wrong text or gives a memory errorUnvalidated option used as an indexblt/bgt before the sll
«Unknown system call: 36»A MARS serviceIt doesn’t exist in QtSpim; use the table of seven services
Check you’ve got it: this fragment should read the name and then the age, and print the age. What two bugs does it have?
        la $a0, name
        li $v0, 8            # read_string
        syscall
        li $v0, 5            # read_int
        syscall
        la $a0, tage
        li $v0, 4            # print_string
        syscall
        move $a0, $v0
        li $v0, 1            # print_int
        syscall

The first: li $a1, 16 is missing before the first call. read_string will use whatever is in $a1: it may read nothing or write beyond the buffer, as in the «Alejandrina the Valiant» error. The second: the age gets overwritten. It arrives in $v0 in the second call and nobody takes it out; li $v0, 4 crushes it, and move $a0, $v0 copies that 4. It’s the hook again: «Age recorded: 4» comes out whatever the age. The fixes are the ones in the table: li $a1, 16 (the same number as the .space) between la $a0, name and li $v0, 8, and move $s0, $v0 right below the second syscall, with move $a0, $s0 before the print_int.

Try it in QtSpim (or right here)

This is the '\n' program. Open it in QtSpim or in the playground below: when you press Run, the console will ask for the name and you can type whatever you like.

Loading the MIPS playground… If it doesn’t appear, copy nonewline.s into your QtSpim.

Things to look at:

  1. Run it and type your name. Then open the Data tab: at 0x10010000 are your letters and, where the 0a was, a 00.
  2. Set a breakpoint on sb $zero, 0($t0) and run again: when it stops, $t0 holds the address of the newline (0x10010000 + the number of letters in your name).
  3. Type a name of 15 letters or more. The loop leaves through beqz without going through cut: there was no newline to remove.
  4. Change li $a1, 16 to li $a1, 4 and type «Kira»: only three letters are stored.
  5. Delete the six lines of the loop (from la $t0, name to cut:) and keep only the trimmed: label. Run again: the greeting splits over two lines, as in the first version.

Summary

ConceptThe essentials
SequenceArguments in $a0/$a1 → li $v0, code → syscall → collect the result
Services1 print_int, 4 print_string, 5 read_int, 8 read_string, 10 exit, 11 print_char, 12 read_char (36 is MARS)
Printingprint_int wants the value (lw), print_string the address (la); \n and \t for the layout
read_intThe number arrives in $v0: move or sw before the next syscall
read_string$a0 buffer, $a1 size; stores up to $a1 − 1 characters, the \n if it fits and the '\0'
Removing the \nLoop with lbu up to 10 (or 0) and sb $zero on top
read_charOne character in $v0; Enter is a character too (10)
Array from the keyboardread_int + sll + sw $v0, v($t0) on each pass
Text → numberdigit = c − 48; n = n · 10 + digit; check '0'..'9'
Menu.word labels table; validate, (option − 1) · 4, lw and print_string

Three ideas to take away

  1. $v0 is a mailbox that empties itself. Whatever a read gives you must be taken out of there (with move or sw) before the next syscall, because that syscall starts by writing to $v0.
  2. What the user types includes the Enter. In read_string it shows up as a \n inside the string and in read_char as one more character. Remove it, or read in a way where it doesn’t get in the way.
  3. The user can type anything. Check ranges and characters before using what was read as an index or a digit: MIPS won’t warn you.

In the system calls practice we create the full character in three programs: the sheet with name, guild and age, the class menu with description and confirmation, and sharing 20 points among four attributes with bars drawn on the console.

Next step: practiceMIPS system calls — practice in QtSpim: the character sheet, a class menu that can’t be fooled and 20 points to share out (and the greeting that split over two lines)

Did this article help you? Here is how you can support SergioLearns →