DEV Community

Cover image for Gdb Black Magics
jinhua luo
jinhua luo

Posted on

Gdb Black Magics

Without questioin, gdb is a brilliant weapon to debug our program. However, the reality is complex. We need black magics to handle these cases.

Magic1: optimized out?

Your program is normally compiled in optimized mode (e.g. -O2), sometimes even without debug info!

With optimized option, gcc would most likely use registers instead of the stack to store the function arguments and local variables. In some circumstances, gdb would said they are , then you could not inspect their values. Even worse, in the flow of the code, those registers would be overrided, so it’s impossible to check their original values anymore!

Normally, to tackle these issues, you have to recompile your program without optimized options.

But what if you could not? Think about you’re facing your client’s production environment.

You would be frustrated, isn’t it?

Then the only way is to read the assembly codes and inspect everything you need at the right places!

Magic2: gdb script

gdb has builtin scripting. You could use it to define variables to r/w the program symbols and do some control flows upon them. It’s really useful when you want to inspect complex context infomation.

Magic3: gdb python

Besides basic scripting, if you want more magic, use python!

Python could be used to define customized command, breakpoint or function.

Magic4: set source path

Mostly it’s necessary to map the debug steps to the lines of source codes.

In fact, normally, your binary, if not stripped, would contains DWARF sections, which contains the path of the source codes. So all you need to do is to download the matching source codes and specify a correct perfix.

Please check the my blog post for detail:

http://luajit.io/post/2022/gdb-black-magics/

Top comments (0)