From 7a02913e36503a13514edc4986bd455de726c541 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 2 Jan 2022 16:19:33 +0100 Subject: [PATCH] cat start --- build.sh | 8 +++-- src/cat.asm | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/wc.asm | 1 - 3 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 src/cat.asm diff --git a/build.sh b/build.sh index b2d636e..fc49214 100644 --- a/build.sh +++ b/build.sh @@ -11,7 +11,7 @@ assemble () { echo "Assembling $PROGRAM_NAME" fi - nasm -g -F dwarf -f elf64 "$FILE" -o "./target/$PROGRAM_NAME.o" || return + nasm -g -F dwarf -f elf64 "$FILE" -o "./target/$PROGRAM_NAME.o" } build () { @@ -29,7 +29,11 @@ build () { return fi - assemble "$FILE" "$PROGRAM_NAME" + + if ! assemble "$FILE" "$PROGRAM_NAME"; then + echo "Errors assembling $PROGRAM_NAME" + return + fi if [ "$QUIET" = "false" ]; then echo "Linking $PROGRAM_NAME" diff --git a/src/cat.asm b/src/cat.asm new file mode 100644 index 0000000..77cc96d --- /dev/null +++ b/src/cat.asm @@ -0,0 +1,93 @@ + extern open_file_arg + + global _start + +IO_BUF_SIZE EQU 1024 +STDIN_FD EQU 0 +STDOUT_FD EQU 1 + + section .data +file_not_found_msg: + db 'File not found', 10, 15 +failed_to_read_msg: + db 'Failed to read', 10, 15 +io_buf: times IO_BUF_SIZE db 0 +newline: db 10, 1 + + section .text +_start: + pop rax ; argc + + cmp rax, 1 + je stdin_init ; if we don't have any arguments, read from stdin + + ; we do have at least one argument, open the file + pop rbx ; program name + pop rax ; filename + call open_file_arg + ; test whether there was an error + cmp rax, 0 + jl file_not_found + + mov rdi, rax + jmp init + +stdin_init: + mov rdi, STDIN_FD + +init: + ; the input fd is in rdi at this point + xor r13, r13 +process: + ; read in from the file + mov rax, 0 + mov rsi, io_buf + mov rdx, IO_BUF_SIZE + syscall + + ; test whether it is finished + cmp rax, 0 + jz finish + + ; test whether there was an error + cmp rax, 0 + jl failed_to_read + + ; write to the file + mov rdx, rax + mov rax, 1 + mov rsi, io_buf + mov rdi, STDOUT_FD + syscall + + jmp process + +finish: + ; write a trailing newline + mov rax, 1 + mov rdx, 1 + mov rsi, newline + mov rdi, STDOUT_FD + syscall + +exit_success: + xor rdi, rdi +exit: + mov rax, 60 + syscall + +failed_to_read: + mov rax, 1 ; write + mov rdi, 2 ; stderr + mov rsi, failed_to_read_msg ; buf + mov rdx, 15 ; len + jmp exit + +file_not_found: + mov rax, 1 ; write + mov rdi, 2 ; stderr + mov rsi, file_not_found_msg ; buf + mov rdx, 15 ; len + syscall + mov rdi, 1 + jmp exit diff --git a/src/wc.asm b/src/wc.asm index 078ece1..7965993 100644 --- a/src/wc.asm +++ b/src/wc.asm @@ -1,4 +1,3 @@ - extern itoa extern println_num extern open_file_arg