gdb无源码调试

Endless_daydream Lv4

首先尝试获取源码文件的信息,如果能找到在哪里是最好。

  1. 查看源代码文件名和编译目录

    1
    info source

    输出类似这样:

    1
    2
    3
    4
    5
    6
    7
    8
    (gdb) info source
    Current source file is /mnt/d/cpp/main.cpp
    Compilation directory is /mnt/d
    Source language is c++.
    Producer is GNU C++ 5.4.0 20160609 -mtune=generic -march=x86-64 -g -fstack-protector-strong.
    Compiled with DWARF 2 debugging format.
    Does not include preprocessor macro info.
    (gdb)

    这些是在编译的时候记录在二进制文件里的。
    由此可知编译的时候,源文件路径为/mnt/d/cpp/main.cpp,编译目录为/mnt/d
    但有可能之后移动过,源码不在那里了。

  2. 查看源码搜索路径

    如果找到了源码,要把源码目录加入搜索路径,使用

    1
    dir your/path/to/code

    附:

    gdb搜索源码的原理:

    1
    show dir

    默认情况输出如下

    1
    Source directories searched: $cdir:$cwd

    其中的$cdir就是上面的/mnt/d。$cwd就是当前工作目录,可以用gdb的cd命令改变。因此现在有两个搜索目录。假设再加入我们设定的目录/abc

    按上面的源码路径/mnt/d/cpp/main.cpp,将会搜索以下路径的文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    /mnt/d/cpp/main.cpp

    $cdir/mnt/d/cpp/main.cpp
    $cwd/mnt/d/cpp/main.cpp
    /abc/mnt/d/cpp/main.cpp

    $cdir/main.cpp
    $cwd/main.cpp
    /abc/main.cpp

只有带调试信息的可执行文件。

命令 功能 命令完整形式
i locals 查看函数局部变量名 info locals
i var 查看全局变量名 info variables
i line [number] | [addr] 查看指定行号/地址的汇编信息,会打印所在函数名 info line
pt VAR 查看变量名所属类型的定义 ptype VAR
wha EXP 查看表达式类型,相比ptype的输出更简单 whatis EXP
bt 查看栈信息,查看入参的值 breaktrace

善用print

1
2
3
p sizeof(var/type) # 查看变量/类型所占内存大小
p/x $rbp-$rsp # 查看当前栈大小
printf "%d\n", var # 调用printf输出格式

参考:

gdb调试解决找不到源代码的问题

  • Title: gdb无源码调试
  • Author: Endless_daydream
  • Created at : 2024-04-06 22:44:23
  • Updated at : 2024-04-06 23:53:54
  • Link: https://endless_daydream.gitee.io/2024/04/06/cpp/gdb无源码调试/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
gdb无源码调试