We already know how to do console output using system calls or using printf. In this chapter, we will again use system calls, not only for display on the screen but also for accepting input from the keyboard.
Working with I/O
console1.asm
The program accepted only ten characters and doesn’t know what to do with the surplus characters, so it throws them back to the operating system. The operating system tries to figure out and interpret the characters as CLI commands but cannot find corresponding commands. Errors!
That’s not nice, but it’s even worse than at first glance. This way of handling input can cause a security breach, where a hacker can break out of a program and gets access to the operating system!
Dealing with Overflows
console2.asm
We modified the prints function so that it first counts the number of characters to display; that is, it counts until it finds a 0 byte. When the length is determined, prints displays the string with a syscall.
The reads function waits for one input character and checks whether it is a new line. If it’s a new line, the character reading from the keyboard stops. Register r14 holds the count of the input characters. The function checks whether the number of characters is larger than inputlen; if not, the character is added to the buffer input. If inputlen is exceeded, the character is ignored, but the reading from the keyboard continues. We require the ASCII code of the character to be 97 or higher and 122 or lower. This will guarantee that only lowercase alphabetic characters are accepted. Note that we saved and restored the callee-saved registers; we used r12 in both functions, prints and reads. In this case, not saving the callee-saved register would not be a problem, but you can imagine that if one function calls another and that one calls yet another, problems could arise.
Debugging console input with SASM is complicated because we are providing input via a syscall. SASM provides its own functionality for I/O, but we didn’t want to use it because we wanted to show how assembly and machine language work without hiding the details. If you get stuck with debugging in SASM, go back to our good old friend GDB.
Summary
Keyboard input using syscall
Validating keyboard input
Debugging with keyboard input, which can be complicated