How to debug a crash before main?

This post has the answer, you have to set a breakpoint before main in the crt0 startup code: Using GDB without debugging symbols on x86?


It's a good bet that LD_DEBUG can help you here. Try this: LD_DEBUG=all ./a.out. This will allow you to easily identify the library which is being loaded when your program crashes.

(Edit: if it wasn't clear, a.out is meant to refer to a generic binary file -- in this case, replace it with the name of your executable).

Edit 2:

To clarify, LD_DEBUG is an environment variable which is examined by the dynamic linker when a program begins execution. If LD_DEBUG is set to some value, the dynamic linker will output a lot of information about the dynamic libraries being loaded during program execution, symbol binding, and so on.

For starters, execute the following on your machine:

LD_DEBUG=help ls

You will see the valid options for LD_DEBUG on your system listed. The most verbose setting is all, which will display all available information.

Now, to use this is as simple as the ls example, only replace ls with the name of your program. There is no need for gdb in order to use LD_DEBUG, as it is functionality provided solely by the dynamic linker, and not by gdb.


It may crash because some component throws an exception and nobody catches it since main() hasn't been entered yet. Set a breakpoint on throwing an exception:

catch throw
run

(If catch throw doen't work the first time you start it, run it once to let it load the dynamic libraries and then do catch throw and run again).


starti

starti breaks at the very first instruction executed, see also: Stopping at the first machine code instruction in GDB

An alternative if your GDB is not new enough:

break _start

if you know the that the name of the entry point method is _start, or:

info files

search for Entry point:

 Entry point: 0x400440

and run:

 break *0x400440

TODO: find out how to compile crt* objects with debug symbols and step into them: How to compile my own glibc C standard library from source and use it?

Tags:

C

Gdb