mirror of
https://github.com/pkivolowitz/asm_book.git
synced 2026-06-23 01:26:53 +08:00
start of examples
This commit is contained in:
parent
8013290d04
commit
b3045c07ba
2 changed files with 79 additions and 0 deletions
9
section_1/funcs/README3.md
Normal file
9
section_1/funcs/README3.md
Normal 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()`.
|
||||||
70
section_1/funcs/file_ops.s
Normal file
70
section_1/funcs/file_ops.s
Normal 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
|
||||||
Loading…
Reference in a new issue