I am posting a message here because I am new to assembly programming. My goal today was to recode a strdup in assembler, so to save my first parameter which is a string (const char*), I have doubts when handling the RSP to reserve space for the string and how I reset it at the end.
However I'm not sure I did well, and I would like to have a review, and advice on what I could improve. Thanks in advance !
extern malloc
extern _ft_strlen
extern _ft_strcpy
section .text
global _ft_strdup
_ft_strdup:
push rbp ; prologue
mov rbp, rsp ; prologue
sub rsp, 8 ; reserve space for string
mov qword [rbp - 8], rdi ; put first param on the stack
call _ft_strlen ; strlen the first param
mov rdi, rax ; put return value on the rdi register
call malloc ; malloc rdi bytes
cmp rax, 0 ; check if malloc failed
je exit_prog
mov rdi, rax ; put malloc address in rdi (DEST)
mov rsi, qword [rbp - 8] ; put source address in rsi (SRC)
call _ft_strcpy ; copy
add rsp, 8 ; reset
pop rbp ; epilogue
ret
exit_prog:
xor rax, rax
add rsp, 8
pop rbp
ret