什么是 GDB
ptrace 系统调用
$ man ptrace
简易的 GDB
1. 调试可执行文件
$ gdb ./example
更多linux内核视频教程文档资料免费领取后台私信【内核】自行获取. Linux内核源码/内存调优/文件系统/进程管理/设备驱动/网络协议栈-学习视频教程-腾讯课堂 第一步:创建被调试子进程
int main(int argc, char** argv){ pid_t child_pid; if (argc < 2) { fprintf(stderr, 'Expected a program name as argument\n'); return -1; } child_pid = fork(); if (child_pid == 0) { // 1) 子进程:被调试进程 load_executable_file(argv[1]); // 加载可执行文件 } else if (child_pid > 0) { // 2) 父进程:调试进程 send_debug_command(child_pid); // 发送调试命令 } else { perror('fork'); return -1; } return 0;}
第二步:加载被调试程序
void load_executable_file(const char *target_file){ /* 1) 运行跟踪(debug)当前进程 */ ptrace(PTRACE_TRACEME, 0, 0, 0); /* 2) 加载并且执行被调试的程序可执行文件 */ execl(target_file, target_file, 0);}
long ptrace(long request, pid_t pid, void *addr, void *data);
ptrace(PTRACE_TRACEME, 0, 0, 0);
第三步:向被调试进程发送调试命令
void send_debug_command(pid_t debug_pid){ int status; int counter = 0; struct user_regs_struct regs; unsigned long long instr; printf('Tiny debugger started...\n'); /* 1) 等待被调试进程(子进程)发送信号 */ wait(&status); while (WIFSTOPPED(status)) { counter++; /* 2) 获取当前寄存器信息 */ ptrace(PTRACE_GETREGS, debug_pid, 0, ®s); /* 3) 获取 EIP 寄存器指向的内存地址的值 */ instr = ptrace(PTRACE_PEEKTEXT, debug_pid, regs.rip, 0); /* 打印当前执行中的指令信息 */ printf('[%u. EIP = 0x%08llx. instr = 0x%08llx\n', counter, regs.rip, instr); /* 4) 将被调试进程设置为单步调试,并且唤醒被调试进程 */ ptrace(PTRACE_SINGLESTEP, debug_pid, 0, 0); /* 5) 等待被调试进程(子进程)发送信号 */ wait(&status); } printf('Tiny debugger exited...\n');}
测试程序
$ gcc tdb.c -o. tdb
$ ./tdb 要调试的程序可执行文件
$ ./tdb /bin/lsTiny debugger started...[1. EIP = 0x7f47efd6a0d0. instr = 0xda8e8e78948[2. EIP = 0x7f47efd6a0d3. instr = 0xc4894900000da8e8[3. EIP = 0x7f47efd6ae80. instr = 0xe5894855fa1e0ff3[4. EIP = 0x7f47efd6ae84. instr = 0x89495741e5894855[5. EIP = 0x7f47efd6ae85. instr = 0xff89495741e58948[6. EIP = 0x7f47efd6ae88. instr = 0x415641ff89495741[7. EIP = 0x7f47efd6ae8a. instr = 0x4155415641ff8949[8. EIP = 0x7f47efd6ae8d. instr = 0x4853544155415641[9. EIP = 0x7f47efd6ae8f. instr = 0xec83485354415541[10. EIP = 0x7f47efd6ae91. instr = 0xf38ec8348535441[11. EIP = 0x7f47efd6ae93. instr = 0x48310f38ec834853[12. EIP = 0x7f47efd6ae94. instr = 0xc148310f38ec8348[13. EIP = 0x7f47efd6ae98. instr = 0x94820e2c148310f[14. EIP = 0x7f47efd6ae9a. instr = 0x48d0094820e2c148[15. EIP = 0x7f47efd6ae9e. instr = 0xcfe0158d48d00948[16. EIP = 0x7f47efd6aea1. instr = 0x480002cfe0158d48[17. EIP = 0x7f47efd6aea8. instr = 0x480002c5d1058948[18. EIP = 0x7f47efd6aeaf. instr = 0x490002cfd2058b48[19. EIP = 0x7f47efd6aeb6. instr = 0xd140252b4cd48949...[427299. EIP = 0x7fec65592b30. instr = 0x6616eb0000003cba[427300. EIP = 0x7fec65592b35. instr = 0x841f0f6616eb[427301. EIP = 0x7fec65592b4d. instr = 0xf0003d48050ff089[427302. EIP = 0x7fec65592b4f. instr = 0xfffff0003d48050fTiny debugger exited...
|
|
来自: imnobody2001 > 《Linux pgm》