前面说了很多,现在简单来说断点就是一个部署在 CPU 上的特殊中断,叫 int 3。int 是一个 “中断指令”的 x86 术语,该指令是对一个预定义中断处理的调用。x86 支持 8 位的 int 指令操作数,决定了中断的数量,所以理论上可以支持 256 个中断。前 32 个中断为 CPU 自己保留,而 int 3 就是本文关注的 —— 它被叫做 “调试器专用中断”。
> The INT 3 instruction generates a special one byte opcode (CC) that is intended for calling the debug exception handler. (This one byte form is valuable because it can be used to replace the first byte of any instruction with a breakpoint, including other one byte instructions, without over-writing other code).
实际上,实现非常简单。一旦你的程序执行了 int 3 指令,操作系统就会停止程序 [[3]][21]。在 Linux(这也是本文比较关心的地方) 上,操作系统会发送给进程一个信号 —— SIGTRAP。
That's all there is to it - honest! Now recall from the first part of the series that a tracing (debugger) process gets notified of all the signals its child (or the process it attaches to for debugging) gets, and you can start getting a feel of where we're going.
That's it, no more computer architecture 101 jabber. It's time for examples and code.
### 手动设置断点
现在我要演示在程序里设置断点的代码。我要使用的程序如下:
```
section .text
; The _start symbol must be declared for the linker (ld)
global _start
_start:
; Prepare arguments for the sys_write system call:
; - eax: system call number (sys_write)
; - ebx: file descriptor (stdout)
; - ecx: pointer to string
; - edx: string length
mov edx, len1
mov ecx, msg1
mov ebx, 1
mov eax, 4
; Execute the sys_write system call
int 0x80
; Now print the other message
mov edx, len2
mov ecx, msg2
mov ebx, 1
mov eax, 4
int 0x80
; Execute sys_exit
mov eax, 1
int 0x80
section .data
msg1 db 'Hello,', 0xa
len1 equ $ - msg1
msg2 db 'world!', 0xa
len2 equ $ - msg2
```
我现在在使用汇编语言,是为了当我们面对 C 代码的时候,能清楚一些编译细节。上面代码做的事情非常简单,就是在一行打印出“hello,”,然后在下一行打印出“world!”。这与之前文章中的程序非常类似。
现在我想在第一次打印和第二次打印之间设置一个断点。我们看到在第一条 int 0x80 后面,指令 mov edx,len2。首先,我们需要知道该指令所映射的地址。运行 objdump -d:
坦白说,0x8048096 本身没多大意义,仅仅是偏移可执行 text 部分开端的一些字节。如果你看上面导出来的列表,你会看到 text 部分从地址 0x08048080\ 开始。这告诉操作系统在分配给进程的虚拟地址空间里,将该地址映射到 text 部分开始的地方。在 Linux 上面,这些地址可以是绝对地址(i.e. 当这些),因为通过虚拟地址系统,每个进程获得自己的一块内存,并且将整个 32 位地址空间看着自己的(称为 “线性” 地址)。
然后,当调试器要求 OS 运行该进程的时候(通过上一次文章中提过的 PTRACE_CONT),进程就会跑起来直到遇到 int 3,此处进程会停止运行,并且 OS 会发送一个信号给调试器。这里调试器会收到一个信号表明其子进程(或者说被追踪进程)停止了。调试器可以做以下工作:
1. 在目标地址,用原来的正常执行指令替换掉 int 3 指令
2. Roll the instruction pointer of the traced process back by one. This is needed because the instruction pointer now points_after_theint3, having already executed it.
3. 允许用户在某些地方可以与进程交互,, since the process is still halted at the desired target address。这里你的调试器可以让你取得变量值,调用栈等等。
4. 当用户想继续运行,调试器会小心地把断点放回目标地址去,除非用户要求取消该断点。
让我们来看看,这些步骤是如何翻译成具体代码的。我们会用到 part 1 里的调试器 “模板”(fork 一个子进程并追踪它)。任何情况下,文末会有一个完整样例源代码的链接
> This one byte form is valuable because it can be used to replace the first byte of any instruction with a breakpoint, including other one byte instructions, without over-writing other code
int 指令在 x86 机器上占两个字节 —— 0xcd 紧跟在中断数后 [[6]][24]。int 3 已经编码为 cd 03,但是为其还保留有一个单字节指令 —— 0xcc。
为什么这样呢?因为这可以允许我们插入一个断点,而不需要重写多余的指令。这非常重要,考虑下面的代码:
```
.. some code ..
jz foo
dec eax
foo:
call bar
.. some code ..
```
假设你想在 dec eax 这里放置一个断点。这对应一个单字节指令(操作码为 0x48)。由于替换断点的指令长于一个字节,我们不得不强制覆盖掉下个指令(call)的一部分,这就会篡改 call 指令,并很可能导致一些完全不合理的事情发生。这样一来 jz foo 会导致什么?都不用说在 dec eax 这里停止,CPU 就已经直接去执行后面一些未知指令了。
而有了单字节的 int 3 指令,这个问题就解决了。一个字节在 x86 上面的其他指令短得多,这样我们可以保证仅在我们想停止的指令处有改变。
### 封装一些晦涩的细节
很多上述章节样例代码的底层细节,都可以很容易封装在方便使用的 API 里。我已经做了很多封装的工作,将它们都放在一个叫做 debuglib 的通用库里 —— 文末可以去下载。这里我仅仅是想展示它的用法示例,但是绕了一圈。下面我们将追踪一个用 C 写的程序。
### 追踪一个 C 程序地址和入口
目前为止,为了简单,我把注意力放在了目标汇编代码。现在是时候往上一个层次,去看看我们如何追踪一个 C 程序。
事实证明没那么简单 —— 找到放置断点位置的难度增加了。考虑下面样例程序:
```
#include <stdio.h>
void do_stuff()
{
printf("Hello, ");
}
int main()
{
for (int i = 0; i <4;++i)
do_stuff();
printf("world!\n");
return 0;
}
```
假设我想在 do_stuff 入口处放置一个断点。我会先使用 objdump 反汇编一下可执行文件,但是打印出的东西太多。尤其看到很多无用,也不感兴趣的 C 程序运行时的初始化代码。所以我们仅看一下 do_stuff 部分:
/* Wait for child to stop on its first instruction */
wait(0);
procmsg("child now at EIP = 0x%08x\n", get_child_eip(child_pid));
/* Create breakpoint and run to it*/
debug_breakpoint* bp = create_breakpoint(child_pid, (void*)0x080483e4);
procmsg("breakpoint created\n");
ptrace(PTRACE_CONT, child_pid, 0, 0);
wait(0);
/* Loop as long as the child didn't exit */
while (1) {
/* The child is stopped at a breakpoint here. Resume its
** execution until it either exits or hits the
** breakpoint again.
*/
procmsg("child stopped at breakpoint. EIP = 0x%08X\n", get_child_eip(child_pid));
procmsg("resuming\n");
int rc = resume_from_breakpoint(child_pid, bp);
if (rc == 0) {
procmsg("child exited\n");
break;
}
else if (rc == 1) {
continue;
}
else {
procmsg("unexpected: %d\n", rc);
break;
}
}
cleanup_breakpoint(bp);
}
```
为了避免去处理 EIP 标志位和目的进程的内存空间太麻烦,我们仅需要调用 create_breakpoint,resume_from_breakpoint和cleanup_breakpoint。让我们来看看追踪上面的 C 代码样例会输出啥:
```
$ bp_use_lib traced_c_loop
[13363] debugger started
[13364] target started. will run 'traced_c_loop'
[13363] child now at EIP = 0x00a37850
[13363] breakpoint created
[13363] child stopped at breakpoint. EIP = 0x080483E5
[13363] resuming
Hello,
[13363] child stopped at breakpoint. EIP = 0x080483E5
[13363] resuming
Hello,
[13363] child stopped at breakpoint. EIP = 0x080483E5
[13363] resuming
Hello,
[13363] child stopped at breakpoint. EIP = 0x080483E5
[13363] resuming
Hello,
world!
[13363] child exited
```
如预期一样!
### 样例代码
[这里是][25]本文用到的完整源代码文件。在归档中你可以找到:
* debuglib.h and debuglib.c - the simple library for encapsulating some of the inner workings of a debugger
* bp_manual.c - the "manual" way of setting breakpoints presented first in this article. Uses thedebugliblibrary for some boilerplate code.
* bp_use_lib.c - usesdebuglibfor most of its code, as demonstrated in the second code sample for tracing the loop in a C program.
### 引用
在准备本文的时候,我搜集了如下的资源和文章:
* [How debugger works][12]
* [Understanding ELF using readelf and objdump][13]
* [Implementing breakpoints on x86 Linux][14]
* [NASM manual][15]
* [SO discussion of the ELF entry point][16]
* [This Hacker News discussion][17]of the first part of the series
* [GDB Internals][18]
[1] On a high-level view this is true. Down in the gory details, many CPUs today execute multiple instructions in parallel, some of them not in their original order.
[2] The bible in this case being, of course, Intel's Architecture software developer's manual, volume 2A.
[3] How can the OS stop a process just like that? The OS registered its own handler for int 3 with the CPU, that's how!
[4] Wait, int again? Yes! Linux uses int 0x80 to implement system calls from user processes into the OS kernel. The user places the number of the system call and its arguments into registers and executes int 0x80. The CPU then jumps to the appropriate interrupt handler, where the OS registered a procedure that looks at the registers and decides which system call to execute.
[5] ELF (Executable and Linkable Format) is the file format used by Linux for object files, shared libraries and executables.
[6] An observant reader can spot the translation of int 0x80 into cd 80 in the dumps listed above.