Writing the shortest valid C quineIf you enjoy my work, please donate! I work hard keeping oxasploits running!
Bitcoin Donation Address:
You can also sponsor me on GitHub!
Thank you so much and happy hacking!
For a while, I have had a fascination with code poetry (also things like “perl golf”). Elegance is quite beautiful, really.
What is a quine?
In short, it is a program that prints its own source code, without having access to the source itself. This is a quine written in C, by an unknown programmer. Supposedly it was written in the margin of a book by Ray Toal, a professor from Loyola Marymount University, in the 80s.
Ray’s much more in-depth webpage on quines. Check it out, it’s great.
Note: Since writing the article I read that a computer scientist named Szymon Rusinkiewicz won the IOCCC contest for this same quine in 1994: smr.c.
If you compile the code, you will probably get a bunch of warnings, but as expected, when executed, it prints it’s own source. You can verify that it isn’t just reading the source code file by removing the .c file.
My foray into writing the shortest C quine
I have quite a bit of code, some of it works… most of it, sadly, does not.
So why not cut the code?
I wondered if
gcc would compile an empty file! Could it be?
So I went ahead and did
echo > qui.c, then I ran
gcc qui.c -o quine
and… the compiler promptly projectile vomited all over my workstation. I get to look at what it says, and realize it’s not actually the C compiler, it is the linker
ld, trying to make a call to the function
main(), while… we have none.
Let’s try this again, the short explanation is I’m going to tell the compiler to only generate an object, and not try to link it yet, then manually link the object to dead space in memory:
Note: This was originally written using
echo > qg.c, however, morb reminded me that echo spits out a newline by default. Using
touch is shorter.
So actually, this program will print output to standard error, but it is actually the operating system throwing an exception after my code tries to call undefined memory, and segfaults, but it does, in fact, print nothing to standard out, as it should. You can see what makes up a completely bare-bones ELF like this, which is interesting:
Note: The linker will spit out
ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000, which I think is a default entry point that the registers can point to, since I did not define it. I’ll have to keep this in mind for future exploit development that the linker will default to this entry address…
We can now run our code. You’ll see the segfault, but if you want you can direct the stderr file descriptor to
/dev/null, to see if it does, indeed, print its own source code.