zl程序教程

您现在的位置是:首页 >  其他

当前栏目

GDB调试入门指南(一)

调试入门 指南 GDB
2023-09-27 14:26:31 时间

快速链接:
.
👉👉👉 个人博客笔记导读目录(全部) 👈👈👈

在这里插入图片描述

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

在这里插入图片描述