Wednesday, July 2, 2014

Writing a running code without main()..!


We all know that main() is the starting point in any C/C++/Java program, But in linux, when a program is executed, always _start() will be called which does cleanup of resources like memory, etc and then calls exit() with main() as it’s argument. Suppose the main() is missing in the program, compiler throws up a undefined reference error to main() function

_start() function can be overriden.

_start function (Inside C)

/usr/lib/gcc/i386-redhat-linux/4.0.0/../../../crt1.o(.text+0x18): In
function `_start':: undefined reference to `main'
collect2: ld returned 1 exit status

Above error definitely means that there is no main() definition in any of the source files of the project. To dig it further, why _start and why collect2?

_start function is the entry point of a C program which makes a call to main()
collect2 is GCC utility which is used to call various utility function during start time. like ld etc.

Going further into it, main() is the starting point of a C program from the programmer's perspective. Before calling main, a process executes a bulk of code to "clean up the room for execution".
_start is the function which gets called first, which then allocates necessary resources and then calls main() which has to be defined by the programmer.

You can override _start and tell the compiler to not to look for main by using "-nostartfiles" option.

#include<stdio.h>
_start()
{
printf("Hello world!!\n");
_exit(0);
}

To Compile : gcc -nostartfiles sampleTest.c -o a.out
Without _exit(0); the program will compile, but encounters a segmentation fault when it's run.


The other ways to write a running program without using main() is to use
  • token pasting operator (Eg: #define fun  m##a##i##n)
  • main being defined in a macro (Eg: #define fun main; int fun() { })

Citations:


No comments:

Post a Comment