简体   繁体   English

如何使用 GDB 调试共享对象库中的函数?

[英]How can I debug functions in shared object libraries with GDB?

I'm trying to verify the functionality of functions in a shared object library.我正在尝试验证共享对象库中函数的功能。 In programs with a main function, I would simply start the program and gdb would automatically breakpoint on main, but that's obviously not available here.在具有main函数的程序中,我会简单地start程序,gdb 会自动在 main 上断点,但这在这里显然不可用。

Let's say I have some add.c :假设我有一些add.c

long add(long x, long y) {
    return x + y;
}

I compile this with gcc -shared -o libadd.so -fPIC add.c and load it into GDB:我用gcc -shared -o libadd.so -fPIC add.c编译它并将其加载到 GDB 中:

(gdb) file libadd.so
Reading symbols from libadd.so...(no debugging symbols found)...done.
(gdb) start
Function "main" not defined.
Make breakpoint pending on future shared library load? (y or [n])
Starting program: /tmp/minimal/libadd.so

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000001 in ?? ()

Preferably, I would like to be able to use gdb similar to below:最好,我希望能够使用类似于下面的 gdb:

(gdb) file libadd.so
Reading symbols from libadd.so...(no debugging symbols found)...done.
(gdb) call (long)add(5,6)
$1 = 11

But this call results in You can't do that without a process to debug .但是这个调用导致You can't do that without a process to debug

Can I debug libraries like this in GDB?我可以在 GDB 中调试这样的库吗?

You can do so with starti , as shown below:您可以使用starti执行此操作,如下所示:

(gdb) file libadd.so
Reading symbols from libadd.so...(no debugging symbols found)...done.
(gdb) starti
Starting program /tmp/minimal/libadd.so

Program stopped.
0x00007ffff7dfd4a0 in deregister_tm_clones ()
(gdb) call (long)add(5,6)
$1 = 11

You can also do this with binaries containing a main function, as seen in this similar question .您也可以使用包含 main 函数的二进制文件来执行此操作,如this similar question中所示

One way you can do this is by creating a dummy executable that links the shared library:一种方法是创建一个链接共享库的虚拟可执行文件:

#include "thelib.h"

int main(int argc, char** argv) {
    if (argc == 100000) {
        // Call any function from the library, so that the shared library will be used
        sub(0, 0);
    }
}

Then, compile and debug this executable, linking to the shared library:然后,编译和调试这个可执行文件,链接到共享库:

$ gdb dummy
(gdb) start
(gdb) call (long)add(5, 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM