lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

what-happens-before-main.md (1345B)


      1 +++
      2 title = 'What happens before main()'
      3 +++
      4 
      5 # What happens before main()
      6 Lots of things:
      7 1. Loaded calls preinitarray, then `_start`
      8 2. That calls `__libc_start_main`, which calls `__libc_csu_init`, which calls a bunch of other stuff
      9 3. After that, `__libc_start_main` calls `main`
     10 4. And then `exit` happens
     11 
     12 ## Start at `_start`
     13 - often if you have `%ebp`, `%esi`, etc. and relatively small addresses, probably a 32-bit binary (stack used for argument passing)
     14 - `argc` popped into `%esi`
     15 - `argv` moved from to `%ecx`
     16 - stack pointer aligned to boundary
     17 - push arguments and call `__libc_start_main`
     18     - this calls `__libc_init_first`, retrieving global variable `__environ`
     19 
     20 ## `__libc_start_main`
     21 - handles security stuff for setuid/setgid
     22 - starts threading
     23 - registers `fini` and `rtld_fini` arguments to run via `at_exit` for cleanup
     24 - calls `init` argument
     25 - calls `main` with `argc` and `argv`
     26 - calls `exit` with return value of main
     27 
     28 ## `__libc_csu_init`
     29 - the constructor of the program
     30 - calls `_init()`
     31 - calls array of function calls with `argc`, `argv`, and `envp`
     32 
     33 ## `_init`
     34 - does a bunch of stuff, including global constructors (e.g. constructors for static C++ objects)
     35 
     36 ## `exit`
     37 - runs functions registered with `atexit()` (in reverse order of registration)
     38 - runs all functions in `fini_array`
     39 - runs destructors
     40 
     41 
     42