start of examples

This commit is contained in:
Perry Kivolowitz 2022-12-18 23:54:50 -06:00
parent 8013290d04
commit b3045c07ba
2 changed files with 79 additions and 0 deletions

View file

@ -0,0 +1,9 @@
# Section 1 / Examples of calling common C runtime functions
This chapter gives examples of calling common C runtime functions from
assembly language.
## Low level file operations
The following example shows `open()`, `close()`, `read()`, `write()`
and `lseek()`.

View file

@ -0,0 +1,70 @@
/* Perry Kivolowitz
Example of file operations.
*/
.text
.global main
.align 2
/* This program will
* open() a file in the current directory,
* write() some text to it,
* seek back to the beginning of the file,
* read() each line, printing it
* close() the file
*/
retval .req w27
fd .req w28
main: stp x29, x30, [sp, -16]!
stp x27, x28, [sp, -16]!
bl open_file
cbz x0, 1f
// If we get here, the open has failed. Use perror() to
// print a meaningful error and exit.
bl open_fail
b 99f
1: // When we get here, the file is open.
// When we get here, we are done. Close the file.
mov w0, fd
bl close
mov retval, wzr
99: ldp x27, x28, [sp], 16
ldp x29, x30, [sp], 16
mov w0, retval
ret
/* This function attempts to open a file for both reading and
writing. Return values will be checked to ensure the file is
opened. If successful, 0 is returned (and the file descriptor
is squirreled away in register "fd".
*/
open_file:
stp x29, x30, [sp, -16]!
ldp x29, x30, [sp], 16
mov x0, 1
ret
/* This function uses perror to print a meaningful error
message in the event of an open failure.
*/
open_fail:
stp x29, x30, [sp, -16]!
ldr x0, =fname
bl perror
mov retval, 1
ldp x29, x30, [sp], 16
ret
.data
prog: .asciz "file_ops"
fname: .asciz "test.txt"
.end