I'm running this program with a Mac computer. It has been 7 months after creating this function and someone is arguing that I'm not properly recreating my cat function. I wanted to know why wouldn't work if I'm calling other functions. My output is correct, but I don't remember why the reasoning of not working.
A while ago, I decided to recreate some of the functions but in NASM. To test my knowledge, I wanted to recreate the cat call that takes in the file descriptor from a source file path by using the open
function. Then call my cat(fd)
assembly function. The output seems satisfying, but the labeling doesn't seem right in my defence.
Here is my assembly cat function file cat.s
:
[bits 64]
global cat
%define SYS_READ 0x2000003
%define SYS_WRITE 0x2000004
%define STDOUT 0x01
%define BUFF_SIZE 0xff
section .bss
buffer resb BUFF_SIZE ; unitialised storage space, basically reserving BUFF_SIZE bytes
section .text
; int my_cat(int fd);
_my_cat:
xor rax, rax
push rbp
mov rbp, rsp
.read:
push rdi ; push rdi stack first before we start reading
lea rsi, [rel buffer]
mov rdx, BUFF_SIZE
mov rax, SYS_READ ; read
syscall
jc end ; jump carry
cmp rax, 0
jle end
.write: ; write the message indicating end of file write
mov rdi, STDOUT ; output fd
mov rdx, rax ; store the destination of rax
mov rax, SYS_WRITE ; write
syscall
pop rdi ; take out our initial rdi stack
jmp .read ; read again
end:
mov rsp, rbp
pop rbp
ret
Then this is the test file I'm running after open()
in my hello.s
file:
[bits 64]
global my_hello
section .data
hello_world db 'Hello World!', 0x0a
section .text
%define SYS_WRITE 0x2000004
%define SYS_EXIT 0x2000001
_my_hello:
mov rax, SYS_WRITE ; syscall write
mov rdi, 1 ; stdout fd (where will it write?)
mov rsi, hello_world ; string address (where does it start?)
mov rdx, 20 ; string length in bytes (how many bytes to write?)
syscall ; system call
mov rax, SYS_EXIT ; exit system call
xor rdi, 0 ; 0 can be replaced with rdi
syscall
main.c file:
extern int my_hello(void);
extern int my_cat(int fd);
int main(void)
{
printf("testing my_cat: \n");
fd = open("src/my_hello.s", O_RDONLY);
ft_cat(fd);
return (0);
}
I have the correct expected value, which it should be the content of hello.s
file. The only part I'm not understanding is that I'm not using the write function properly because I don't take the 3 parameters (descriptor, the content of the string, nbuff_size). Help me to get learn't. For example: how can I see what is doing behind the scene when it's compiled (like using the lldb for my cat.s?) Moving my registers around doesn't help me to understand more.