I am posting a message here because I am new to assembly programming. My goal today was to re-code strdup in assembly, so to save my first parameter which is a string (const char*), I have doubts when handling 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.
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 return
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
return:
xor rax, rax
add rsp, 8
pop rbp
ret
sub rsp, 8as “reserve space for string” when, in fact, its purpose is to maintain the required 16-bit alignment of the stack pointer in the System V ABI. The string is stored on the heap, and it is never safe to return a pointer to data on the current stack frame. No one who knew to subtract eight bytes after pushing eight bytes would think thatmallocstored the string in them. \$\endgroup\$rbpwith apush rdi. \$\endgroup\$