0

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
1
  • 1
    That's what I thought but then why no problem when i remove read and write blocks ? What in them modifies stack alignement ? In read i dont where i touch the stack and in write i push then pop. Commented Mar 29, 2015 at 20:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually both for the read and the write syscall where you set up mov rsi, rbp ; 2nd param - buffer.
Thank you it works. I don't really understand why yet but l'll try to figure out. How comes we need to save ebp at start but it keeps reseting at each syscall. And also if my MOV were bad how can I read all of my file and it crash only at return. Thank you again ;)
ebp does not reset. You allocated your buffer at ebp-16 so you need to pass that as address, otherwise you will overwrite the return address on the stack. That will fault at the ret because that will try to grab it from the stack and jump there.
alriiight. I get it now. Thanks a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.