Using scanf and printf in assembly
Notes
- We have used
printf in c++ already
- It takes a pointer to a format string
- And a value or pointer to every argument that matched the format string.
- The call to
scanf works much the same way.
- A pointer to a format string
- Pointers to all arguments.
- We need to be careful with strings, as there is no way to limit the input
- For this reason we will use a different routine for string input.
- In general, this is a band aid solution.
- In any case,
-
rdi contains the address of the format string
-
rsi should contain the first element, or pointer to the first input location.
-
rdx is the third parameter or second element
-
rcx is the fourth parameter or third element
-
r8 is the fifth parameter or fourth element
-
r9 is the sixth parameter or fifth element
- There can be further parameters but
- this is silly
- They are more work, but we will learn how later
- Break your input/output up over several calls.
- In any case,
rax will contain the number of items successfully input or the numbers of bytes output
- Take a look at input.asm.
- For strings, we will use
read
- reference.
-
ssize_t read(int fd, void buf[count], size_t count);
- The return value is the number of bytes read
- The
fd is a file descriptor
- 0 is the standard input by default
- We can deal with others later.
- But this is defined in my file CONSTANTS.h
-
void buf[count] is a pointer to the allocated memory to hold the input.
-
count is the maximum input size, in bytes, to read
-
read is system call 0, see this page
- To read a string
- place SYS_READ in rax
- place STDIN in rdi
- place the address of the buffer in rsi
- place the size in rdx
- Call syscall
- The numbers of bytes read is in
rax
- See the example in input.asm
- This has a problem, but we will address it later.