x86调试支持
软件断点
软件断点指令 INT 3 的机器码为 0xCC,通过该指令可以让 CPU 在代码段上停止下来,但不适用于数据段以及 ROM 中的代码调试。
工作原理: 设置断点后,直接修改执行的程序,在想要暂停的地方添加 0xCC 指令。
Tip
ntdll 是 window 操作系统提供给用户态的内核接口库,即「系统调用」
Tip
通过 non-invasive 的方式,可以用多个 windbg 调试同一程序

硬件断点

硬件断点则是通过CPU的「寄存器」实现
DR0 ~ DR3: 设置需要监视的地址DR7: 设置需要监视的状态DR6: 监视内存的命中状态,检测到地址命中,CPU就抛出断点异常
硬件断点是直接检测「地址」,因此就能对数据访问、IO操作设置断点,且不会修改代码。受物理硬件限制,能设置的硬件断点数量有限。
陷阱标志
单步断点调试就是靠 efl 实现,一次断点调试会将 efl 的第 8 位设置为 1,当 CPU 检测到就会抛出单步异常,并将第 8 位恢复为 0。
JTAG
JTAG (Joint Test Action Group): 在芯片上增加调试接口,然后通过 TAP 控制器采集芯片运行信号,传输给上位机进行调试。主要用于硬件开发

用户态调试
windows 调试

windows 的调试器是基于事件的,调试器会等待内核返回的调试事件。
// 判断目标进程是否存在
if(bTargetProcess){
// 创建一个调试进程
CreateProcess(,DEBUG_PROCESS,);
}else{
// 附加进程
DebugActiveProcess(PID);
}
// 等待调试事件
while(WaitForDebugEvent(&Event, INFINITE)){
// 事件处理
switch(Event.dwDebugEventCode){
case EXIT_PROCESS_DEBUG_EVENT: ...
...
}
ContinueDebugEvent(...);
}调试事件
内核产生调试事件,并将调试事件封装成 debug 对象,存放在内核的一个队列中。用户态的调试器可以通过系统 API 从 debug 对象队列中,获取 debug 对象,并解析调试事件。

事件类型:
typedef struct _DEBUG_EVENT {
DWORD dwDebugEventCode;
DWORD dwProcessId;
DWORD dwThreadId;
union {
EXCEPTION_DEBUG_INFO Exception;// 异常debug事件
CREATE_THREAD_DEBUG_INFO CreateThread; //创建线程debug事件
CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;// 创建进程debug事件
EXIT_THREAD_DEBUG_INFO ExitThread;// 退出线程debug事件
EXIT_PROCESS_DEBUG_INFO ExitProcess; // 退出进程debug事件
LOAD_DLL_DEBUG_INFO LoadDll;// 加载动态链接库debug事件
UNLOAD_DLL_DEBUG_INFO UnloadDll;// 卸载动态链接库debug事件
OUTPUT_DEBUG_STRING_INFO DebugString;// 输出debug内容事件
RIP_INFO RipInfo;
} u;
} DEBUG_EVENT, *LPDEBUG_EVENT;Note
只有异常调试事件 EXCEPTION_DEBUG_INFO 才存在两轮处理
修改事件或异常的状态:
| Command | Status name | Description |
|---|---|---|
| sxe | Break(Enabled) | When this exception occurs, the target immediately breaks into the debugger before any other error handlers are activated. This kind of handling is called first chance handling. |
| sxd | Second chance break(Disabled) | The debugger does not break for a first-chance exception of this type (although a message is displayed). If other error handlers do not address this exception, execution stops and the target breaks into the debugger. This kind of handling is called second chance handling. |
| sxn | Output(Notify) | When this exception occurs, the target application does not break into the debugger at all. However, a message is displayed that notifies the user of this exception. |
| sxi | Ignore | When this exception occurs, the target application does not break into the debugger at all, and no message is displayed. |
不同状态对事件状态的处理:
| Command | Status name | Description |
|---|---|---|
| sxe | Handled | The event is considered handled when execution resumes. |
| sxd,sxn,sxi | Not Handled | The event is considered not handled when execution resumes. |
linux 调试
linux 调试通过 ptrace (process trace) 实现。在 linux 中,父进程能访问子进程的内存信息、监视子进程以及控制子进程等,这就可以使得利用 ptrace 接口将调试进程伪装成目标进程的父进程,实现调试器: 当使用了 ptrace 跟踪后,所有发送给被跟踪的子进程的信号 (除了SIGKILL),都会被转发给父进程,而子进程则会被阻塞,这时子进程的状态就会被系统标注为 TASK_TRACED;而父进程收到信号后,就可以对停止下来的子进程进行检查和修改,然后让子进程继续运行。

PTRACE(2) Linux Programmer's Manual PTRACE(2)
NAME
ptrace - process trace
SYNOPSIS
#include <sys/ptrace.h>
long ptrace(enum __ptrace_request request, pid_t pid,
void *addr, void *data);
DESCRIPTION
The ptrace() system call provides a means by which one process (the "tracer") may observe and control the exe‐
cution of another process (the "tracee"), and examine and change the tracee's memory and registers. It is
primarily used to implement breakpoint debugging and system call tracing.WAIT(2) Linux Programmer's Manual WAIT(2)
NAME
wait, waitpid, waitid - wait for process to change state
SYNOPSIS
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);
pid_t waitpid(pid_t pid, int *wstatus, int options);
int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
/* This is the glibc and POSIX interface; see
NOTES for information on the raw system call. */
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
waitid():
Since glibc 2.26: _XOPEN_SOURCE >= 500 ||
_POSIX_C_SOURCE >= 200809L
Glibc 2.25 and earlier:
_XOPEN_SOURCE
|| /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
|| /* Glibc versions <= 2.19: */ _BSD_SOURCE
DESCRIPTION
All of these system calls are used to wait for state changes in a child of the calling process, and obtain in‐
formation about the child whose state has changed. A state change is considered to be: the child terminated;
the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child,
performing a wait allows the system to release the resources associated with the child; if a wait is not per‐
formed, then the terminated child remains in a "zombie" state (see NOTES below).实操
随便附加一个进程
异常
介绍
来源
CPU 异常:
- 执行指令时产生的异常,例如除0
- Machine Check Exceptions
Int 3断点异常
程序异常:
RaiseRxception系统 API 用于抛出异常throw
异常类型
- SEH 异常类型
#define STILL_ACTIVE STATUS_PENDING
#define EXCEPTION_ACCESS_VIOLATION STATUS_ACCESS_VIOLATION
#define EXCEPTION_DATATYPE_MISALIGNMENT STATUS_DATATYPE_MISALIGNMENT
#define EXCEPTION_BREAKPOINT STATUS_BREAKPOINT // 断点异常
#define EXCEPTION_SINGLE_STEP STATUS_SINGLE_STEP // 单步异常
#define EXCEPTION_ARRAY_BOUNDS_EXCEEDED STATUS_ARRAY_BOUNDS_EXCEEDED
#define EXCEPTION_FLT_DENORMAL_OPERAND STATUS_FLOAT_DENORMAL_OPERAND
#define EXCEPTION_FLT_DIVIDE_BY_ZERO STATUS_FLOAT_DIVIDE_BY_ZERO
#define EXCEPTION_FLT_INEXACT_RESULT STATUS_FLOAT_INEXACT_RESULT
#define EXCEPTION_FLT_INVALID_OPERATION STATUS_FLOAT_INVALID_OPERATION
#define EXCEPTION_FLT_OVERFLOW STATUS_FLOAT_OVERFLOW
#define EXCEPTION_FLT_STACK_CHECK STATUS_FLOAT_STACK_CHECK
#define EXCEPTION_FLT_UNDERFLOW STATUS_FLOAT_UNDERFLOW
#define EXCEPTION_INT_DIVIDE_BY_ZERO STATUS_INTEGER_DIVIDE_BY_ZERO
#define EXCEPTION_INT_OVERFLOW STATUS_INTEGER_OVERFLOW
#define EXCEPTION_PRIV_INSTRUCTION STATUS_PRIVILEGED_INSTRUCTION
#define EXCEPTION_IN_PAGE_ERROR STATUS_IN_PAGE_ERROR
#define EXCEPTION_ILLEGAL_INSTRUCTION STATUS_ILLEGAL_INSTRUCTION
#define EXCEPTION_NONCONTINUABLE_EXCEPTION STATUS_NONCONTINUABLE_EXCEPTION
#define EXCEPTION_STACK_OVERFLOW STATUS_STACK_OVERFLOW
#define EXCEPTION_INVALID_DISPOSITION STATUS_INVALID_DISPOSITION
#define EXCEPTION_GUARD_PAGE STATUS_GUARD_PAGE_VIOLATION
#define EXCEPTION_INVALID_HANDLE STATUS_INVALID_HANDLE
#define EXCEPTION_POSSIBLE_DEADLOCK STATUS_POSSIBLE_DEADLOCK
#define CONTROL_C_EXIT STATUS_CONTROL_C_EXIT-
CLR 异常:异常代码
0xe0434f4d,即.COM -
C++ 异常:异常代码
0xe06d7363,即.msc
SEH 处理机制
SEH (struct exception handling)
, 即结构化异常处理机,是微软为 c 定义的一套异常处理机制,语法为 __try - __except
异常分发
异常分发由内核中的 ntoskrnl!KiDispatchException 实现
// first chance handling. 第一轮异常分发
if(FirstChance){
// 1. 检测有没有用户态调试器,没有的话又检测要不分发给内核态调试器
if(PsGetCurrentProcess()->DebugPort == 0 ||
KdlsTHisAKdTrap(Tf, &Context)){
// 内核态调试器接收异常,则退出分发
if(KiDebugRoutine && KiDebugRoutine(Tf, Reserved, Er, &Context, PreviousMode, FirstChane) != 0) return;
}
// 2. 分发给用户态调试器,主要处理断点异常,但是其他异常不处理,还有第二轮
if(DbgkForwardException(TrapFrame, DebugEvent, FistChanece) != 0) return;
// 3. 将异常传递给用户态,让用户态的 try-catch __try-__except 进行处理
if(valid_user_mode_stack_with_enough_space){
// copy context and exception record to user_stack
// 从内核态跳转到用户态的 KeUserExceptionDispatcher 异常分发函数
TrapFrame->Eip = KeUserExceptionDispatcher;
return;
}
}
// second chance handling. 第二轮分发给调试器
if(DbgForwardException(Tf, True, LastChanece) != 0) return;
// 让目标进程崩溃退出,没人处理异常
if(DbgForwardException(Tf, FALSE, LastChanece) != 0) return;
// 目标进程连崩溃退出都没办法,内核来直接杀死进程
ZwTerminateProcess(NtCurrentThread(), Er->ExceptionCode);

实操
#include <iostream>
#include <stdio.h>
#include <Windows.h>
/* 过滤器 */
int filter(LPEXCEPTION_POINTERS pInfo, DWORD nCode){
int nRes = EXCEPTION_CONTINUE_SEARCH;
printf("code %x\n", nCode);
if(pInfo->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO){
nRes = EXCEPTION_EXECUTE_HANDLER;
}
return nRes;
}
int main(int argc, char const *argv[])
{
int a = 10;
int c = 0;
__try{
int b = a/ c;
}
__except(filter(GetExceptionInformation(), GetExceptionCode())){
// 修复除0异常
c = 1;
}
return 0;
}编译器的调试支持
pdb 文件
windows 通过 pdb 文件储存调试信息,格式保密,但是能通过API访问。编译器会为每一个 .c .cpp 源文件生成一个 pdb 文件,并通过连接器,将所有的 pdb 文件进行合并。

Note
pdb 即 program database ,其本质就是存储调试信息的数据库

调试器实现断点定位,就是在二进制代码执行时,会对代码的汇编地址与 pdb 里面存储的行地址区间进行比对,就能知道当前汇编代码所对应的源码行号。当汇编地址超出行地址区间时,就能判断当前二进制代码执行完成了该行。
符号服务器
符号文件具有日期和时间戳。调试器始终查找与它所调试的二进制文件上的时间戳匹配的符号。若时间戳对应不上,就会导致符号文件加载失效(就算什么源码都没修改的情况下,重新编译二进制)。微软三天两头修复 bug ,会重新编译操作系统部分组件并发布,这就导致 pdb 文件会经常变动。为了方便对符号文件管理,微软就为 windows 操作系统提供了「符号服务器」,可以下载不同版本的 pdb 文件。
linux 符号支持
linux 的符号支持是靠 DWARF 标准
实现,会直接存储到 ELF 文件,即直接保存到 linux 目标程序,并不会另外生成一个符号文件。
错误检查
- 编译期间
- 语法错误
- 静态分析
- 运行期间 Run-Time Error Check (RTC) : 往编译的程序添加额外的检查逻辑
- 栈指针被破坏
- 局部缓冲区越界
- 栈被破坏
- 依赖未初始化的局部变量
附加
辅助工具
- Process Explorer : 比任务管理器更适合用来程序开发,可查看的进程信息更多且可以查看堆栈信息