Reputation: 101
My asm function segfaults at return.
Here is the function prototype : void ft_cat(int fd);
Basically it get a fd from a C main and act like cat shell command.
I get no problem if I removed read and write parts so maybe the problem is around syscalls. I just can't tell. I already spent hours and hours looking for it.
Any clue ?
%define MACH_SYSCALL(nb) 0x2000000 | nb
%define READ 3
%define WRITE 4
%define LSEEK 19
%define STDOUT 1
%define SEEK_CUR 1
section .text
global _ft_cat
_ft_cat:
push rbp ; save base pointer
mov rbp, rsp ; place base pointer on stack
sub rsp, 16 ; align stack to keep 16 bytes for buffering
push rdi ; save function parameter (int fd)
read:
mov rdi, [rsp] ; 1st param - get fd from stack
mov rsi, rbp ; 2nd param - buffer
mov rdx, 16 ; 3rd param - buffer size
mov rax, MACH_SYSCALL(READ)
syscall
cmp rax, 0 ; if read return <= 0 jump to end
jng end
write:
push rax ; save read return
mov rdi, STDOUT ; 1st param
mov rsi, rbp ; 2nd param - buffer
mov rdx, rax ; 3rd param - read return
mov rax, MACH_SYSCALL(WRITE)
syscall
pop rax
cmp rax, 16 ; if read return < 16 then it is finished
je read
end:
mov rsp, rbp ; restore stack and base pointers
pop rbp ;
ret ; return >> segfault
Upvotes: 0
Views: 837
Reputation: 58762
Your allocated buffer is 16 bytes below ebp
but you pass ebp
to the read
syscall so you overwrite the saved rbp
, the return address and other things in the caller's frame. You want lea rsi, [rbp-16]
instead.
Upvotes: 1