GDB和GDB Server

2023-04-27,

gdb是linux c编程标配的调试工具,平时接触比较多的可能是本机随gcc一起安装的调试工具。但是,即使是本机的gdb,也经常被printf代替,所以接触也仅限于知道。

简单程序固然可以用printf,但是复杂的,带有图形界面的程序,就不得不使用调试工具,比如,arm的跨平台图形程序调试。幸好Qt Creator支持gdb+gdbserver的方式来进行跨平台调试。

基本原理:

1. 目标板使用gdb-server来启动已经编译好的代码,执行断点、分步等调试动作,同时通过网络反馈调试需要的信息给host。

2. host上运行arm-linux-gdb,解析gdb-server传来的信息,同时,发送断点、分步等动作给目标板。

所以,首要的工作是工具的准备。

arm-linux-gdb 以及 gdb-server 的制作,参考这篇:QtCreator 环境使用 remote debug

gdb 的简单使用,可以参考这篇:gdb 简单使用

在远程调试时,首先,需要在远程使用 gdbserver 打开要调试的程序,有两种方式:

1) 直接用 gdbserver 打开:

gdbserver 192.168.1.230: packet_analyzer

上面一句的意思是,使用 gdbserver 运行程序 packet_analyzer, gdbserver 的监听地址为 192.168.1.230:1234

2) attach 到已经在执行的进程上:

gdbserver --attach localhost: 

上面这句表示,用 attach 的方式打开 gdbserver,调试进程号为 16924 的程序。

然后,在另外一边,使用相应版本的 gdb 来作为 client 与 gdbserver 连接即可:

# arm-linux-gdb
Python Exception <type 'exceptions.ImportError'> No module named gdb: warning:
Could not load the Python gdb module from `/tmp/gdb-7.6/__install/share/gdb/python'.
Limited Python support is available from the _gdb module.
Suggest passing --data-directory=/path/to/gdb/data-directory. GNU gdb (GDB) 7.6
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "--host=i686-pc-linux-gnu --target=arm-linux".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
(gdb) target remote 192.168.1.230:1234
Remote debugging using 192.168.1.230:1234
0x400007c0 in ?? ()
(gdb) file packet_analyzer
A program is being debugged already.
Are you sure you want to change the file? (y or n) y
Reading symbols from /home/luo/Documents/time_analyzer_qt/packet_analyzer...done.

至此,gdb 与 gdbserver 就勾搭上了,可以像在本地调试一样,对远程机器上的程序进行调试。

需要说明的是,在调试过程中,gdbserver 侧是不接受 ctrl-c 来终止程序的。退出 gdbserver 目前知道的就两种方法,在 gdb 侧执行 quit,或者在 remote 侧使用 killall。

GDB和GDB Server的相关教程结束。

《GDB和GDB Server.doc》

下载本文的Word格式文档,以方便收藏与打印。