Friday, December 12, 2014

main function in C

As this is my first post, let's start with main function which is entry point of every C program. Let's try to do something fun with it and write program without any "real" function. Only one limitation is environment: GCC and Linux. But what's interesting about program "entry point"? GCC compiler (linker to be precise) is searching for main symbol and symbol is not necessarily a function. We can try it in simple program:
We see that this program compiles, runs and... well, crashes. The reason of crash is that "main" is variable and it's put into non executable part of our program. Jump to this location cause segmentation fault. When using gcc you can cheat a little bit and tell compiler to move your variable into .text (code) section by annotating it with section attribute. Still segmentation fault. It happens because 0x0 isn't really an useful (at least in this context) CPU instruction. We can tune this piece of software by changing 0 to "0xFEEB". After compiling and running you should see.. nothing. This is what was expected. Integer value 0xFEEB translates to "jump two bytes back" (0xEB - jmp [offset], 0xFE - minus 2) - in simple words it's never-ending loop, while(true); ;). Note that this code is extremely not portable, it depends almost on anything: compiler, linker, OS, endianness and CPU architecture. So please, don't use it. :)

No comments:

Post a Comment