I'm new to coding with intel asm 64bits and I'm trying to recode strdup from libc and I got a segfault when try to test it in my main in c but I don't understand why I got this error
here is my main.c:
#include "libasm.h"
int main(void)
{
printf(" _____________\n");
printf("// \\\\\n");
printf("|| ft_strdup ||\n");
printf("||_____________||\n");
char *str;
char *dup;
str = "test";
printf("segfault1\n");
dup = ft_strdup(str);
printf("segfault2\n");
printf("str: %s\n", dup);
free(dup);
return 0;
}
WHen I launch my program with the flags -g -fsanitize I got this segfault error on the line where I call ft_strdup:
ASAN:DEADLYSIGNAL
=================================================================
==21414==ERROR: AddressSanitizer: SEGV on unknown address 0x55789815fa80 (pc 0x55789815fa80 bp 0x7ffe98c5e8a0 sp 0x7ffe98c5e3d8 T0)
==21414==The signal is caused by a READ memory access.
ASAN:DEADLYSIGNAL
AddressSanitizer: nested bug in the same thread, aborting.
gdb backtrace:
Program received signal SIGSEGV, Segmentation fault.
0x00005554f7a79140 in ?? ()
(gdb) backtrace
#0 0x00005554f7a79140 in ?? ()
#1 0x0000555555554fb2 in ft_strdup ()
#2 0x000055555555508a in ?? ()
#3 0x0000555555554e69 in main () at main.c:90
here is the instruction 0x0000555555554fb2:
(gdb) x/10i 0x0000555555554fb2
0x555555554fb2 <ft_strdup+18>: pop %rsi
0x555555554fb3 <ft_strdup+19>: mov %rax,%rdi
0x555555554fb6 <ft_strdup+22>: jmpq 0x555555554ef0 <ft_strcpy>
0x555555554fbb <ft_strdup+27>: nopl 0x0(%rax,%rax,1)
0x555555554fc0 <__libc_csu_init>: push %r15
0x555555554fc2 <__libc_csu_init+2>: push %r14
0x555555554fc4 <__libc_csu_init+4>: mov %rdx,%r15
0x555555554fc7 <__libc_csu_init+7>: push %r13
0x555555554fc9 <__libc_csu_init+9>: push %r12
0x555555554fcb <__libc_csu_init+11>: lea 0x200d9e(%rip),%r12 # 0x555555755d70
here is my ft_strdup code:
global ft_strdup
extern malloc
extern ft_strlen
extern ft_strcpy
ft_strdup:
push rdi
call ft_strlen
add rax, 1
mov rdi, rax
call malloc
pop rsi
mov rdi, rax
jmp ft_strcpy
here is my ft_strcpy code:
global ft_strcpy
ft_strcpy:
xor rax, rax
loop:
cmp byte [rsi + rax], 0
jz return
mov dl, [rsi + rax]
mov [rdi + rax], dl
inc rax
jmp loop
return:
mov byte [rdi + rax], 0
mov rax, rdi
ret
and my ft_strlen code:
global ft_strlen
ft_strlen:
xor rcx, rcx
count:
cmp byte [rdi], 0
je ret;
inc rdi
inc rcx
jmp count
ret :
mov rax, rcx
ret
If someone could give me some indications on what could cause this segfault it would really help me!