DanielHsH
DanielHsH

Reputation: 4453

program execution is not started at main()

I developed many years in C and only now discovered that a program can execute code prior to main() function. Here is a code example

int generateNum(){
    // Some malicious code here...
    return 5;
}

static int someArray[] = {generateNum(),generateNum()}  

int main(){
     // Some code here...
}

The function generateNum() is called twice before main().

My questions are

  1. Who calls generateNum()? I know that on Windows it is crtexe()
  2. Is this behavior standardized on different platforms: Windows/Linux/Android/iOS?
  3. How can I get more information about this behavior? I want to search in Google, but I don't know how to describe it.
  4. Can I do anything I want inside the generateNum()? I mean, can I call malloc()? What about fopen() and fwrite()? Can I open a socket and send information over UDP? Eventually I can abuse this function and even call to main() from it :-)

Upvotes: 7

Views: 410

Answers (2)

creichen
creichen

Reputation: 1768

  1. C++ guarantees that such initialisations take place before main. This can be taken care of by the operating system loader/linker, or by some special module linked against the object file that contained main. For gcc, this is described here: http://gcc.gnu.org/onlinedocs/gccint/Initialization.html
  2. Not quite. C++11, 3.6.2.4 (basic.start.init): It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. Note that initialization takes place before you can ever access that value, though, especially before there is any notion of reference to an entity in the same compilation unit.
  3. [basic.start.init] in the language standard is what you want to have a look at. The behaviour here is dynamic initialization for variables with static storage duration.

Upvotes: 7

Sadique
Sadique

Reputation: 22821

A program shall contain a global function called main, which is the designated start of the program.

It doesn't say that no code executes before main is called. Full quote:

3.6.1 Main function [basic.start.main]

1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [Note: in a freestanding environment, start-up and termination is implementation-defined; start-up contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. ]

Upvotes: 7

Related Questions