Just entriely out of fun and for learning, after all how many times you get to wake up and say to yourself, "I am going to rewite the C standard library"
Writing this was a little fun challange for me, and also an excuse to use assembly ( not AT&T ) I am going to try my best to demonstrate what i did so you can get started on your own, or understand what's going on
what you need to get started is a bit of understanding innot to much stuff, just a bit
The purpose of this Writing isn't a follow through tutorial but to showcase my process. This isnt a tutorial if you want one there are probably many online. I was going to write a bit of tutorial basic Assembly, but found a stunning one by this kind random internet stranger : Assembly tutorial.
we start off main.c in our root directory with a void _start(){}
you can compile it by using:
gcc -nostdlib main.c -o main
this uses gcc to compile but without the standard library aka libc after compiling and running we get this :
[1] 153003 segmentation fault (core dumped) ./main
A segfault . Why? because the program didn't know where to stop. To tell it where we stop there's a syscall in linux called exit take a look here to see all of syscalls : chromium syscall docs
in the exit syscall it takes 2 arguments,
We write it up using inline assmebly in c. Incase you have no knowlegde about inline assembly in c, here's another kind stranger's work on inline assembly : Inline Assembly
#define SYSEXIT 60 void _start() { __asm__ inline( "movl $0 ,%%edi;" "xorl %%eax, %%eax;" "movl %1, %%eax;" "syscall" :: "r"(SYSEXIT)); }
this will make our code exit normally, you can see from here that we placed 0 into edi(rsi) and moved SYSEXIT(60) into eax(rax) and then we called syscall to carry out the function
This is how basic syscall is written, grab the arguments and parse it and pass it in the respective resgisters then call syscall
you can make this more clean by extracting it to it's own function, and in another file then call it when needed That's how my directory structure basically is
This is how I went about writing libc with syscalls, you implement all the syscalls you need ( eg read, write ) then write higher functions ( eg printf ) with them. I hope this non technical guide was of help to you. Again this wasn't a tutorial, I gave you the resources i used and they are structured and way better than i could ever do it. Cheers.
"Imagine all the people..."
- John Lennon, Yoko's husband
Inspired by the geniuses behind Links posted above : Pradyun Gedam and Derick Swanepoel ☺