How to debug a crash before main?

2020-02-26 09:29发布

My program links statically to many libraries and crashes before getting to main in gdb. How do i diagnose what the problem is?

标签: c gdb
7条回答
Summer. ? 凉城
2楼-- · 2020-02-26 09:59

I haven't run into this in C but if you link to a c++ library static initialization can crash. You can create it easily by having an assert in a constructor of a static scope variable.

查看更多
一夜七次
3楼-- · 2020-02-26 10:02

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).

查看更多
Juvenile、少年°
4楼-- · 2020-02-26 10:03

Start taking the libraries out one by one until it stops crashing. Then examine the culprit.

查看更多
趁早两清
5楼-- · 2020-02-26 10:13

If you can, link your program dynamically instead of statically and follow @denniston.t answer. Maybe debug trace from dynamic linker will help to fix this problem.

查看更多
一纸荒年 Trace。
6楼-- · 2020-02-26 10:17

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.

查看更多
Animai°情兽
7楼-- · 2020-02-26 10:18

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?

查看更多
登录 后发表回答