LINUX内核开发与调试

Similar documents
epub83-1

Windows XP

Oracle Solaris Studio makefile C C++ Fortran IDE Solaris Linux C/C++/Fortran IDE "Project Properties" IDE makefile 1.

Microsoft Word - 11.doc

Microsoft Word - template.doc

1.ai

2 2 3 DLight CPU I/O DLight Oracle Solaris (DTrace) C/C++ Solaris DLight DTrace DLight DLight DLight C C++ Fortran CPU I/O DLight AM

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

Oracle Oracle Solaris Studio IDE makefile C C++ Fortran makefile IDE Solaris Linux C/C++/Fortran Oracle IDE "P

2/80 2


EK-STM32F

PowerPoint 演示文稿

AL-M200 Series

言1.PDF

CC213

Guide to Install SATA Hard Disks

入學考試網上報名指南

untitled

<4D F736F F D C4EAC0EDB9A4C0E04142BCB6D4C4B6C1C5D0B6CFC0FDCCE2BEABD1A15F325F2E646F63>

1. 請 先 檢 查 包 裝 內 容 物 AC750 多 模 式 無 線 分 享 器 安 裝 指 南 安 裝 指 南 CD 光 碟 BR-6208AC 電 源 供 應 器 網 路 線 2. 將 設 備 接 上 電 源, 即 可 使 用 智 慧 型 無 線 裝 置 進 行 設 定 A. 接 上 電 源

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

國 立 政 治 大 學 教 育 學 系 2016 新 生 入 學 手 冊 目 錄 表 11 國 立 政 治 大 學 教 育 學 系 博 士 班 資 格 考 試 抵 免 申 請 表 論 文 題 目 申 報 暨 指 導 教 授 表 12 國 立 政 治 大 學 碩 博 士 班 論

软件测试(TA07)第一学期考试

WinMDI 28

Improved Preimage Attacks on AES-like Hash Functions: Applications to Whirlpool and Grøstl

Chapter 2

ch_code_infoaccess

K7VT2_QIG_v3

2017 CCAFL Chinese in Context

软件自由法律中心 GPL 软件许可证合规指导

A Preliminary Implementation of Linux Kernel Virus and Process Hiding

Preface This guide is intended to standardize the use of the WeChat brand and ensure the brand's integrity and consistency. The guide applies to all d

els0xu_zh_nf_v8.book Page Wednesday, June, 009 9:5 AM ELS-0/0C.8

提纲 1 2 OS Examples for 3

CDWA Mapping. 22 Dublin Core Mapping

ebook140-8

untitled

(Load Project) (Save Project) (OffLine Mode) (Help) Intel Hex Motor

目 录

ebook140-9

ebook70-14

TX-NR3030_BAS_Cs_ indd

Microsoft Word - SupplyIT manual 3_cn_david.doc

IP505SM_manual_cn.doc

K301Q-D VRT中英文说明书141009

mvc

Microsoft Word - Final Exam Review Packet.docx

Microsoft Word - PS2_linux_guide_cn.doc

Microsoft Word - 11月電子報1130.doc

Oracle 4

Logitech Wireless Combo MK45 English

PowerPoint Presentation

NEXT SDT2.51 C:\ARM251 SDT2.51 ARM SDT 2.51 ARM PROJECT MANAGER SDT 2

自动化接口

Some experiences in working with Madagascar: installa7on & development Tengfei Wang, Peng Zou Tongji university

Microsoft Word - linux命令及建议.doc

LSC操作说明

Microsoft Word - HSK使用手册.doc

2015 Chinese FL Written examination

2015年4月11日雅思阅读预测机经(新东方版)

Microsoft PowerPoint - Lecture7II.ppt

Microsoft Word - CX VMCO 3 easy step v1.doc

VASP应用运行优化

Learning Java

AN INTRODUCTION TO PHYSICAL COMPUTING USING ARDUINO, GRASSHOPPER, AND FIREFLY (CHINESE EDITION ) INTERACTIVE PROTOTYPING

ARM JTAG实时仿真器安装使用指南

Bus Hound 5

RAID RAID 0 RAID 1 RAID 5 RAID * ( -1)* ( /2)* No Yes Yes Yes A. B. BIOS SATA C. RAID BIOS RAID ( ) D. SATA RAID/AHCI ( ) SATA M.2 SSD ( )

Microsoft Word - ChineseSATII .doc

Microsoft Word - (web)_F.1_Notes_&_Application_Form(Chi)(non-SPCCPS)_16-17.doc

國立中山大學學位論文典藏.PDF

Cygwin & vim

WebSphere Studio Application Developer IBM Portal Toolkit... 2/21 1. WebSphere Portal Portal WebSphere Application Server stopserver.bat -configfile..

Microsoft Word - TIP006SCH Uni-edit Writing Tip - Presentperfecttenseandpasttenseinyourintroduction readytopublish

Microsoft Word - 3D手册2.doc

coverage2.ppt

Microsoft Word - Front cover_white.doc

HLA-B27軟體

Panaboard Overlayer help

本文由筱驀釹贡献

ebook70-5

Epson

IP Access Lists IP Access Lists IP Access Lists

LH_Series_Rev2014.pdf

Microsoft PowerPoint - Eisenstein_ABET_Presentation_Beijing_Oct_2007-Chinese.ppt [兼容模式]

Chn 116 Neh.d.01.nis

untitled


untitled

錄...1 說...2 說 說...5 六 率 POST PAY PREPAY DEPOSIT 更

声 明 本 人 郑 重 声 明 : 此 处 所 提 交 的 硕 士 学 位 论 文 基 于 等 级 工 鉴 定 的 远 程 考 试 系 统 客 户 端 开 发 与 实 现, 是 本 人 在 中 国 科 学 技 术 大 学 攻 读 硕 士 学 位 期 间, 在 导 师 指 导 下 进 行 的 研 究

Table of Contents Design Concept 03 Copyrights & TradeMark 04 Special Notice 05 Notice to concerned 05 Installation and Registration Introduction 07 s

JCR... 3 JCR... 3 ISI Web of Knowledge... 4 Cross Search... 5 Cross Search... 5 Cross Search ISI Web of Knowledge WOS... 8 Externa

南華大學數位論文

CH01.indd

KDC-U5049 KDC-U4049 Made for ipod, and Made for iphone mean that an electronic accessory has been designed to connect specifically to ipod, or iphone,

SDS 1.3

Ác Åé å Serial ATA ( Sil3132) S A T A (1) SATA (2) BIOS SATA (3)* RAID BIOS RAID (4) SATA (5) SATA (a) S A T A ( S A T A R A I D ) (b) (c) Windows XP

Transcription:

GDB 基础 张银奎 2017/2/14 珠海白石富华里

Richard Matthew Stallman Richard Matthew Stallman is a software developer and software freedom activist. Born in 1953, he attended Harvard starting in 1970 and graduated in 1974 with a Bachelor of Arts in physics. From September 1974 to June 1975 he was a graduate student in physics at MIT. Stallman developed a number of widely used software components of the GNU system: the GNU Compiler Collection, the GNU symbolic debugger (gdb), GNU Emacs, and various others. https://www.stallman.org/

RMS in China, 2000 Beijing -> Chengdu -> JiuZhaiGou -> Wuhan and to Shanghai"

Richard Stallman using his Lemote machine at Indian Institute of Technology Madras, Chennai before his lecture on 'Free Software, Freedom and Education' organized by Free Software Foundation, Tamil Nadu. What hardware do you use? I am using a Lemote Yeelong, a netbook with a Loongson chip and a 9-inch display. This is my only computer, and I use it all the time. I chose it because I can run it with 100% free software even at the BIOS level. https://usesthis.com/interviews/richard.stallman/ https://en.wikipedia.org/wiki /Richard_Stallman

GNU Projects Stallman announced the plan for the GNU operating system in September 1983 on several ARPANET mailing lists and USENET. Stallman was responsible for contributing many necessary tools, including a text editor (Emacs), compiler (GCC), debugger (GNU Debugger), and a build automator (GNU make). In 1991, Linus Torvalds, a Finnish student, used the GNU's development tools to produce the free monolithic Linux kernel. Man ls AUTHOR Written by Richard M. Stallman and David MacKenzie.

GDB GNU Debugger 1986 年,Richard Stallman 创建 1900-1993,John Gilmore 维护 目前在 GDB Steering Committee It was modeled after the DBX debugger, which came with Berkeley Unix distributions 支持很多种 CPU architecture A29K, ARC, ETRAX CRIS, D10V, D30V, FR-30, FR-V, Intel i960, M32R, 68HC11, Motorola 88000, MCORE, MN10200, MN10300, NS32K, Stormy16, V850, Z8000 and many more 默认为命令行界面, 有很多 GUI 的前端 (Add-on) 7

官网 https://www.gnu.org/software/gdb/

Contributors to gdb

ChangeLog

/gdb/readme README for GDB release This is GDB, the GNU source-level debugger. A summary of new features is in the file `gdb/news'. Check the GDB home page at http://www.gnu.org/software/gdb/ for up to date release information, mailing list links and archives, etc. The file `gdb/problems' contains information on problems identified late in the release cycle. GDB's bug tracking data base at http://www.gnu.org/software/gdb/bugs/ contains a more complete list of bugs.

RMS's gdb Debugger Tutorial http://www.unknownroa d.com/rtfm/gdbtut/gdbt oc.html

Document 学习 GDB 的最好教材 Tenth Edition, for gdb version 7.11.1 33 章, 多个附录,790 页

概览 1 A Sample gdb Session 2 Getting In and Out of gdb 2.1 Invoking gdb 2.1.1 Choosing Files 2.1.2 Choosing Modes 2.1.3 What gdb Does During Startup 2.2 Quitting gdb 2.3 Shell Commands 2.4 Logging Output 3 gdb Commands 3.1 Command Syntax 3.2 Command Completion 3.3 Getting Help

在 GDB 下运行程序 4 Running Programs Under gdb 4.1 Compiling for Debugging 4.2 Starting your Program 4.3 Your Program's Arguments 4.4 Your Program's Environment 4.5 Your Program's Working Directory 4.6 Your Program's Input and Output 4.7 Debugging an Already-running Process 4.8 Killing the Child Process 4.9 Debugging Multiple Inferiors and Programs 4.10 Debugging Programs with Multiple Threads 4.11 Debugging Forks 4.12 Setting a Bookmark to Return to Later 4.12.1 A Non-obvious Benefit of Using Checkpoints

5 Stopping and Continuing 5.1 Breakpoints, Watchpoints, and Catchpoints 5.1.1 Setting Breakpoints 5.1.2 Setting Watchpoints 5.1.3 Setting Catchpoints 5.1.4 Deleting Breakpoints 5.1.5 Disabling Breakpoints 5.1.6 Break Conditions 5.1.7 Breakpoint Command Lists 5.1.8 Dynamic Printf 5.1.9 How to save breakpoints to a file 5.1.10 Static Probe Points 5.1.11 Cannot insert breakpoints 5.1.12 Breakpoint address adjusted... 5.2 Continuing and Stepping 5.3 Skipping Over Functions and Files 5.4 Signals 5.5 Stopping and Starting Multi-thread Programs 5.5.1 All-Stop Mode 5.5.2 Non-Stop Mode 5.5.3 Background Execution 5.5.4 Thread-Specific Breakpoints 5.5.5 Interrupted System Calls 5.5.6 Observer Mode 停止和继续

炫酷功能 6 Running programs backward 7 Recording Inferior's Execution and Replaying It

查看栈 源代码 8 Examining the Stack 8.1 Stack Frames 8.2 Backtraces 8.3 Selecting a Frame 8.4 Information About a Frame 8.5 Management of Frame Filters. 9 Examining Source Files 9.1 Printing Source Lines 9.2 Specifying a Location 9.2.1 Linespec Locations 9.2.2 Explicit Locations 9.2.3 Address Locations 9.3 Editing Source Files 9.3.1 Choosing your Editor 9.4 Searching Source Files 9.5 Specifying Source Directories 9.6 Source and Machine Code

查看数据 10 Examining Data 10.1 Expressions 10.2 Ambiguous Expressions 10.3 Program Variables 10.4 Artificial Arrays 10.5 Output Formats 10.6 Examining Memory 10.7 Automatic Display 10.8 Print Settings 10.9 Pretty Printing 10.9.1 Pretty-Printer Introduction 10.9.2 Pretty-Printer Example 10.9.3 Pretty-Printer Commands 10.10 Value History 10.11 Convenience Variables 10.12 Convenience Functions 10.13 Registers 10.14 Floating Point Hardware 10.15 Vector Unit 10.16 Operating System Auxiliary Information 10.17 Memory Region Attributes 10.17.1 Attributes 10.17.1.1 Memory Access Mode 10.17.1.2 Memory Access Size 10.17.1.3 Data Cache 10.17.2 Memory Access Checking 10.18 Copy Between Memory and a File 10.19 How to Produce a Core File from Your Program 10.20 Character Sets 10.21 Caching Data of Targets 10.22 Search Memory 10.23 Value Sizes

11 Debugging Optimized Code 11.1 Inline Functions 11.2 Tail Call Frames 12 C Preprocessor Macros 13 Tracepoints 13.1 Commands to Set Tracepoints 13.1.1 Create and Delete Tracepoints 13.1.2 Enable and Disable Tracepoints 13.1.3 Tracepoint Passcounts 13.1.4 Tracepoint Conditions 13.1.5 Trace State Variables 13.1.6 Tracepoint Action Lists 13.1.7 Listing Tracepoints 13.1.8 Listing Static Tracepoint Markers 13.1.9 Starting and Stopping Trace Experiments 13.1.10 Tracepoint Restrictions 13.2 Using the Collected Data 13.2.1 tfind n 13.2.2 tdump 13.2.3 save tracepoints filename 13.3 Convenience Variables for Tracepoints 13.4 Using Trace Files 跟踪点

查看符号表和改变执行目标 16 Examining the Symbol Table 17 Altering Execution 17.1 Assignment to Variables 17.2 Continuing at a Different Address 17.3 Giving your Program a Signal 17.4 Returning from a Function 17.5 Calling Program Functions 17.6 Patching Programs 17.7 Compiling and injecting code in gdb 17.7.1 Compilation options for the compile command 17.7.2 Caveats when using the compile command 17.7.3 Compiler search for the compile command

指定文件和控制 GDB 18 gdb Files 18.1 Commands to Specify Files 18.2 File Caching 18.3 Debugging Information in Separate Files 18.4 Debugging information in a special section 18.5 Index Files Speed Up gdb 18.6 Errors Reading Symbol Files 18.7 GDB Data Files 22 Controlling gdb 22.1 Prompt 22.2 Command Editing 22.3 Command History 22.4 Screen Size 22.5 Numbers 22.6 Configuring the Current ABI 22.7 Automatically loading associated files 22.7.1 Automatically loading init file in the current directory 22.7.2 Automatically loading thread debugging library 22.7.3 Security restriction for auto-loading 22.7.4 Displaying files tried for auto-load 22.8 Optional Warnings and Messages 22.9 Optional Messages about Internal Happenings 22.10 Other Miscellaneous Settings

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

Syntax A gdb command is a single line of input. There is no limit on how long it can be. You can repeat certain gdb commands by typing just RET. You can also use the TAB key to get gdb to fill out the rest of a word in a command # comment

缩写和别名 You can abbreviate a gdb command to the first few letters of the command name, if that abbreviation is unambiguous; (GDB) info > I (GDB) continue > c 很多命令有简单的别名 (GDB) backtrace > bt (GDB) ptype > pt

Convenience Variables GDB 维护的违变量以 $ 开头 $ most recent displayed value $n nth displayed value $$ displayed value previous to $ $$n nth displayed value back from $ 可以使用 set 命令定义 set $foo = *object_ptr

$_ 和 $ The variable $_ is automatically set by the x command to the last address examined. The variable $ is automatically set by the x command to the value found in the last address examined. Its type is chosen to match the format in which the data was printed

$_thread Gdb provides two convenience variables, $_thread and $_gthread (the latter being pretty new), which can be used in conditions to refer to the current thread. So, once the worker thread has started, you can use info thread to find its number. Then you can change your breakpoint (supposing for this example that it is breakpoint 2) like: (gdb) cond 2 $_thread!= 57

Gdb variables (gdb) set $foo = 4 (gdb) p $foo $3 = 4

Register Variables (gdb) break write if $rsi == 2

表达式归纳 expr an expression in C, C++, or Modula-2(including function calls), or: addr@len an array of len elements beginning at addr file::nm a variable or function nm defined in file {type}addr read memory at addr as specied type $ most recent displayed value $n nth displayed value $$ displayed value previous to $ $$n nth displayed value back from $ $_ last address examined with x $ value at address $_ $var convenience variable; assign any value show values [n] show last 10 values [or surrounding $n] show conv display all convenience variables

Shell Commands shell command-string!command-string

Info and show info -- Generic command for showing things about the program being debugged show -- Generic command for showing things about the debugger

Debug the debugger set debug -- Generic command for setting gdb debugging flags

Logging Output

常用调试命令对照表 WinDBG 命令 GDB 命令 功能 bp break 或 b 设置软件断点 ba watch 设置硬件断点 k backtrace 或 bt 显示函数调用序列 ( 栈回溯 ) g continue 或 c 恢复执行 p/t next/step 或 n/s 单步跟踪 d x 观察内存 dv info locals 观察局部变量 dt pt 观察数据类型 ( 结构 ) gu finish 执行到函数返回.frame frame 切换当前栈帧 lm i shared 列模块 36

更多常用命令 命令行 run xxx set args xx xx show args 观察类型 ptype whatis print v@10 管理断点 源代码 info/disable/delete break list 3,8 info line/source/sources show conv 37

Get help help(h) help class apropos args complete args

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

调试模式 调试模式 交互式调试 转储分析 gdb --core=<file> 调试新进程 调试已经运行的进程 内核调试 gdb <exe> gdb --args <exe> [args] gdb --pid=<n>

调试新进程 命令行指定 exe gdb <exe> 命令行指定 exe 和参数 gdb --args <exe> [args] 使用命令 gdb file <exe> run [args]

示例 1 gdb file <exe> run [args]

示例 2 gdb --args gcc -O2 -c foo.c

args... [~]$ gdb --args pizzamaker --deep-dish --toppings=pepperoni (gdb) show args Argument list to give program being debugged when it is started is " --deep-dish --toppings=pepperoni". (gdb) b main Breakpoint 1 at 0x45467c: file oven.c, line 123.... (gdb) run

设置和显示程序参数 set args Specify the arguments to be used the next time your program is run. If set args has no arguments, run executes your program with no arguments. Once you have run your program with arguments, using set args before the next run is the only way to run it again without arguments. show args Show the arguments to give your program when it is started.

环境变量 path directory show paths show environment [varname] set environment varname [=value]

工作目录 继承 GDB 的当前目录 cd [directory] Set the gdb working directory to directory. If not given, directory uses ~. pwd Print the gdb working directory.

输入输出 info terminal run > outfile tty /dev/ttyb

inferior n. 部下, 下属 ; 次品 ; 晚辈 ;[ 印 ] 下角码 [ɪnˈfɪriə(r)] gdb represents the state of each program execution with an object called an inferior. An inferior typically corresponds to a process, but is more general and applies also to targets that do not have processes. Inferiors may be created before a process runs, and may be retained after a process exits. 下程

显示下程信息 (gdb) info inferiors Num Description Executable * 1 <null> /home/ge/work/llaolao3/baner 描述部分的 null 表示进程退出或者没有运行, 或者已经 detach

克隆下程 (gdb) clone-inferior -copies 2 Added inferior 2. Added inferior 3. (gdb) info inferiors Num Description Executable 3 <null> /home/ge/work/llaolao3/baner 2 <null> /home/ge/work/llaolao3/baner * 1 <null> /home/ge/work/llaolao3/baner

切换下程 inferior infno Make inferior number infno the current inferior. The argument infno is the inferior number assigned by gdb, as shown in the first field of the info inferiors display.

增加下程 add-inferior [ -copies n ] [ -exec executable ]

更多关于下程的命令 remove-inferiors infno... detach inferior infno... kill inferiors infno...

file 命令 Use FILE as program to be debugged. It is read for its symbols, for getting the contents of pure memory, and it is the program executed when you use the `run' command. If FILE cannot be found as specified, your execution directory path ($PATH) is searched for a command of that name. No arg means to have no executable file and no symbols.

文件命令 file 指定执行文件和符号文件 文件名作为参数, 不带参数则清除此类信息 exec-file 指定执行文件 symbol-file 指定符号文件

开始运行 run Start debugged program. You may specify arguments to give it. Args may include "*", or "[...]"; they are expanded using "sh". Input and output redirection with ">", "<", or ">>" are also allowed. With no arguments, uses arguments last specified (with "run" or "set args"). To cancel previous arguments and run with no arguments, use "set args" without arguments.

附加到已经运行的进程 命令行参数 gdb --pid=<n> 使用 attach 命令 attach process-id

终止调试会话 分离 - detach 杀死 - quit

Quit gdb use the quit command (abbreviated q) type an end-of-file character (usually Ctrl-d)

进程跟踪 Process Trace,Ptrace 最早实现在 1979 发布的 Unix V7 Unix/Linux 用户态调试的主要依据 63 父进程 fork 子进程 waitpid 调试器 / 养父进程 ptrace

ptrace #include <sys/ptrace.h> long int ptrace(enum ptrace_request request, pid_t pid, void * addr, void * data) PTRACE_ATTACH/ PTRACE_DETACH PTRACE_PEEKTEXT, PTRACE_PEEKDATA, PTRACE_PEEKUSER PTRACE_POKETEXT, PTRACE_POKEDATA, PTRACE_POKEUSER PTRACE_SINGLESTEP PTRACE_KILL 系统调用 64

waitpid #include <sys/types.h> #include <sys/wait.h> pid_t waitpid(pid_t pid, int *status, int options); WIFEXITED(status): 子进程正常退出 WEXITSTATUS(status): 子进程的退出码 WIFSIGNALED(status): SIGINT, CTRL-C WTERMSIG(status): 终止信号编号 WIFSTOPPED(status): SIGSTOP, CTRL-Z WSTOPSIG(status): 停止信号编号 65

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

设置代码断点 软件断点硬件断点 break 普通 tbreak 一次性 rbreak 接受正则表达式成批设置 hbreak thbreak 一次性

两类断点 软件断点 基于 CPU 的断点指令, 如 x86 的 INT 3 ( 机器码 0xCC) 替换断点位置的指令 CPU 执行到此时触发断点异常 没有数量限制 硬件断点 基于 CPU 的调试寄存器, 如 x86 的 DR0 DR7 不需要修改程序代码, 可以针对 EEPROM 上的代码设置 有数量限制

指定位置 (Location) Linespec locations 行号 -/+ 偏移行 文件名 : 行号 函数名 函数 : 标号 文件名 : 函数名 标号 Explicit locations -source filename -function function -label label -line number Address locations *address

示例 对函数名和地址设断点

示例 对源代码行设断点 第二个断点 +2 意为相对当前代码行之后 (after)2 行, 上个 list 命令会影响当前代码行的位置 For the list command, the current line is the last one printed; for the breakpoint commands, this is the line at which execution stopped

硬件断点 VBOX 虚拟机中设置失败

管理断点 info b delete 1 #Delete breakpoint 1 disable 1 # Disable the breakpoint 1 enable 1 # Enable breakpoint 1 delete #Delete all breakpoints clear sum #Clear any breakpoints at the entry to function sum

扩展断点 监视点 watchpoint 断点 追踪点 tracepoint 捕捉点 catchpoint

监视点 监视表达式, 值变化时中断 The expression may be as simple as the value of a single variable, or as complex as many variables combined by operators. watch a*b + c/d watch *(int *)0x12345678 watch *global_ptr 数据断点 (data breakpoint)

监视点示例

实现 硬件平台相关 X86 上是使用硬件寄存器, 数量有限制, 最多 4 个

自动删除

访问监视点 rwatch [-l -location] expr [thread thread-id] [mask maskvalue] Set a watchpoint that will break when the value of expr is read by the program. awatch [-l -location] expr [thread thread-id] [mask maskvalue] Set a watchpoint that will break when expr is either read from or written into by the program.

访问监视点示例 写 fd 触发实际上是 61 行的写操作触发硬件断点, 事后报告, 导致 gdb 行号报告为 62 行 fd = open(name, O_RDWR); 读 fd 触发 读 fd 触发 读 n 做比较时触发, 写时没有触发

线程约束 thread <threadno> 进档指定线程遇到断点时才中断 适用于各类断点

线程约束示例 (gdb) b hd_ioctl thread 1 Breakpoint 10 at 0x8048603: file baner.c, line 16.

附加条件 直接使用 if 关键字附加在断点命令后 或者 condition bnum expression condition bnum 没有参数则删除之前设置的条件

条件断点示例

附件命令示例

例 2 (gdb) b do_mmap_pgoff Breakpoint 1 at 0xffffffff8111a441: file mm/mmap.c, line 940. (gdb) command 1 Type commands for when breakpoint 1 is hit, one per line. End with a line saying just "end". >print addr >print len >print prot >end (gdb)

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

单步跟踪 stepi #Execute one instruction stepi 4 # Execute four instructions nexti # Like stepi, but proceed through function calls without stopping step # Execute one C statement

汇编级跟踪 set disassemble-next-line on

汇编 窗口 (gdb)layout asm (gdb) focus asm (gdb) ni

Oops (gdb) show version GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04 Copyright (C) 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.ht ml> 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 "x86_64-linux-gnu".

观察机器码 echo 'asm("mov $400835, %rax\n jmp *%rax\n");' > test.c gcc -c test.c objdump -d test.o display /3i $pc

恢复执行 continue # Resume execution until the next breakpoint until 3 # Continue executing until program hits breakpoint 3 finish # Resume execution until current function returns

调用函数 call sum(1, 2) # Call sum(1,2) and print return value

强制返回 return expression You can cancel execution of a function call with the return command. If you give an expression argument, its value is used as the function s return value.

触发中断 CTRL + C Suspending execution is done with the interrupt command when running in the background,or Ctrl-c during foreground execution.

反向单步 # reverse-step, reverse-next, reverse-continue (rc) # target record # target record-full http://stackoverflow.com/questions/1206872/go-to-previous-line-in-gdb

利用 RTIT 反向单步 Real time instruction trace, 又叫 intel processor trace Gdb 7.10 supports PT for backwards debugging (reverse-step) Uses perf interface, works as non root

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

调试符号 编译器对调试的重大贡献 编译过程的副产品 衔接二进制程序与源程序的桥梁 对调试有着重要意义 源代码级调试必须 二进制跟踪时的灯塔

DWARF DWARF Debugging Information Format http://www.dwarfstd.org 功莫大焉

再看 ELF

段表

感受 DWARF 编译单元

TAG( 标签 )

产生符号 $ gcc g o baner baner.c -g --gen-debug generate debugging information

Ubuntu 的符号服务器 http://ddebs.ubuntu.com/pool/main/l/linux/

服务器的根目录

下载内核符号文件 http://askubuntu.com/questions/197016/how-to-install-a-package-that-contains-ubuntu-kernel-debug-symbols

示例 2

libc

学习用虚拟机 - gebox

加载符号文件 file 或者 symbol-file [ filename ] Read symbol table information from file filename. PATH is searched when necessary. Use the file command to get both symbol table and program to run from the same file.

案例

符号文件信息

两阶段读取 对于大多数符号文件,GDB 先是快速扫描符号文件, 然后根据需要读取详细数据 可以使用 readnow 选项来强制读取所有符号信息

显示符号 info variables regexp info classes regexp info functions regexp info types regexp

查找函数 info functions regexp

符号命令归纳 info address s #show where symbol s is stored info func [regex] #show names, types of defined functions (all, or matching regex) info var [regex] #show names, types of global variables (all, or matching regex) whatis [expr] #show data type of expr [or $] without evaluating; ptype [expr] #ptype gives more detail ptype type #describe type, struct, union, or enum

符号和地址互查

观察虚函数表 或

查看源代码

源文件信息

Install source files from Ubuntu [~/src]$ apt-get source coreutils [~/src]$ sudo apt-get install coreutils-dbgsym [~/src]$ gdb /bin/ls GNU gdb (GDB) 7.1-ubuntu (gdb) list main 1192 ls.c: No such file or directory. in ls.c (gdb) directory ~/src/coreutils-7.4/src/ Source directories searched: /home/nelhage/src/coreutils-7.4:$cdir:$cwd (gdb) list main 1192 } 1193 }

安装 libc 源文件 sudo apt-get source libc6-dev /home/ge/eglibc-2.15

设置搜索路径 Add directory dirname to the front of the source path. Several directory names may be given to this command, separated by : ( ; on MS-DOS and MSWindows, where : usually appears as part of absolute file names) or whitespace. $cdir to refer to the compilation directory $cwd to refer to the current working directory

安装内核源文件 [~/src]$ apt-get source linux-image-2.6.32-25-generic [~/src]$ sudo apt-get install linux-image-2.6.32-25-generic-dbgsym [~/src]$ gdb /usr/lib/debug/boot/vmlinux-2.6.32-25-generic (gdb) list schedule 5519 /build/buildd/linux-2.6.32/kernel/sched.c: No such file or directory. in /build/buildd/linux-2.6.32/kernel/sched.c (gdb) set substitute-path /build/buildd/linux-2.6.32 /home/nelhage/src/linux-2.6.32/ (gdb) list schedule 5519 5520 static void put_prev_task(struct rq *rq, struct task_struct *p) 5521 {

常用命令

概览 命令基础 用户态会话 断点 执行控制 符号 读写调试目标 高级技巧

观察寄存器

修改寄存器 (gdb)set $<name>=<value>

栈回溯 backtrace

参数和局部变量

切换栈帧 frame <no>

观察变量和内存

x [~]$ grep saved_command /proc/kallsyms ffffffff81946000 B saved_command_line (gdb) x/s 0xffffffff81946000 ffffffff81946000 <>: "root=/dev/sda1 quiet

示例

@ (gdb) p *&a[0]@10 $1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} to view elements 550-553 in a long vector, all you do is 'p *&a[550]@4'

修改内存 (gdb) set <var>=<exp> (gdb) help set variable Evaluate expression EXP and assign result to variable VAR, using assignment syntax appropriate for the current language (VAR = EXP or VAR := EXP for example). VAR may be a debugger "convenience" variable (names starting with $), a register (a few standard names starting with $), or an actual variable in the program being debugged. EXP is any valid expression. This may usually be abbreviated to simply "set".

反汇编

x/i (gdb) x/5i schedule 0xffffffff8154804a <schedule>: push %rbp 0xffffffff8154804b <schedule+1>: mov $0x11ac0,%rdx 0xffffffff81548052 <schedule+8>: mov %gs:0xb588,%rax 0xffffffff8154805b <schedule+17>: mov %rsp,%rbp 0xffffffff8154805e <schedule+20>: push %r15 x/10i sum Examine first 10 instructions of function sum https://blogs.oracle.com/ksplice/entry/8_gdb_tricks_you_should

X86 汇编语言 INTEL 语法 先是目标, 然后是源, 也就是从右向左赋值 Windows 上流行 AT&T 语法 先是源, 然后是目标, 也就是从左向右赋值 Unix 和 Linux 上流行

概览 命令基础 用户态会话 断点 执行控制 符号 查看调试目标 高级技巧

信号

处理规则

改变信号处理规则 handle SIGPIPE nostop print

多线程调试

info threads * 代表当前线程

切换线程 thread thread-id

对多个线程执行命令 thread apply [thread-id-list all [-ascending]] command

命名 thread name [name]

命令文件 https://sourceware.org/gdb/onlinedocs/gdb/command-files.html

Q&A

拍案惊奇 软件调试实战训练营 软件调试高级研习班 2017 庐山秀峰站 HTTP://001001.ORG/GEDU/ADVDBG2017.PDF

切问而近思 欢迎关注格友公众号