快速链接:
.
👉👉👉 个人博客笔记导读目录(全部) 👈👈👈
1、前提准备工作
(1)、准备一段小代码
#include <stdio.h>
int main()
{
int a = 0,b=0, s=0;
printf("1111111111111---%s enter\n",__func__);
a=100;
b=20;
s = a + b;
printf("2222222222222i---s=%d\n",s);
while(1);
printf("3333333333333333\n");
while(1);
printf("444444444444444444\n");
return 0;
}
(2)、编译出两个版本
-
编译不带
-g
参数的
gcc main.c -o hello1
-
编译带
-g
参数的
gcc main.c -g -o hello2
2、查看一个程序能否被调试
(1)通过GDB查看程序是否带调试信息
命令 : gdb helloworld
- 不带调试信息的
hello1
将输出(No debugging symbols found in hello1)
- 带调试信息的
hello2
将输出Reading symbols from hello2...
(2)通过readelf 查看程序是否带调试信息
命令 : readelf -S hello2 | grep debug
- 产看不带调试信息的
hello1
:命令readelf -S hello1 | grep debug
将什么都不会输出。 - 产看带调试信息的
hello2
:命令readelf -S hello2 | grep debug
将输出debug信息
(3)查看strip状况
命令 : file hello2
,如果显示不是not stripped
, 那么也是不能调试的。
hello2: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=1c6a91df87921a8ec9bcef2a0187040d77b6f965, for GNU/Linux 3.2.0, with debug_info, not stripped
3、调试方式运行程序
(1). 启动无参数调试
$ gdb hello2
(gdb)
接下来按run
命令,即可运行程序
(2). 启动有参数调试
$ gdb hello2
(gdb)run paramaters
$ gdb hello2
(gdb) set args paramaters
(gdb) run
4、调试core文件
敲击ulimit -c
的结果如果是0,那么程序不会产生core dump。当程序异常时我们需要能够产生core dump文件, 可以使用ulimit -c 10
,调整core dump
产生的限制。
$ ulimit -c
$ ulimit -c 10 //设置core dump最大的大小,单位为块,一块默认为512字节
$ gdb hello2 core文件名
5、调试已运行程序
(1)、查看运行程序的PID
$ ps -ef | grep hello2
(2) attach这个PID
$ gdb
(gdb) attach 2453
如果出现ptrace: Operation not permitted.
解决方法,切换到root用户:
将/etc/sysctl.d/10-ptrace.conf中的kernel.yama.ptrace_scope = 1
改为kernel.yama.ptrace_scope = 0
,然后继续root模式下调试。
或者这样
-
gdb attach 2680
-
gdb hello2 2680
-
gdb hello2 --pid 2680
6、已运行程序没有调试信息
$ gdb
(gdb) file hello1
Reading symbols from hello…done.
(gdb)attach 20829