I'm trying to alocate memory on the heap without using libc and using linux system calls. I've tried using mmap and brk but brk doesn't return the end of heap like I've read it does for most systems, sbrk won't work because it doesn't exist as a syscall, and mmap just causes a segfault.
_start.c
#define PROT_READ 0x1
#define PROT_WRITE 0x2
#define MAP_PRIVATE 0x2
#define MAP_ANONYMOUS 0x20
extern void *mmap(void *addr, unsigned long sz, int prot, int mode, int fd, unsigned long offset);
extern void exit(int exit_code);
int _start()
{
void *mem = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*(int*)mem = 4;
exit(*(int*)mem);
}
The reason I am trying to do this is because I am working on a replacement libc (obviously not a competent one if I don't know how to do this, it's mainly a learning exercise/fun project) and I need to figure out how to actually allocate on the heap. I've looked for a while but I still have no clue how it works.
syscalls.s
.text
.global mmap
mmap:
mov $9, %rax
syscall
ret
.global exit
exit:
mov $60, %rax
syscall
ret
The compile command I'm using is gcc -nostdlib _start.c syscalls.s
.
Like I said, I am running Linux. Specifically: Ubuntu 20.04 LTS with kernel 5.11.0-43-generic.