一篇學會Linux ptrace 的實現(xiàn)
ptrace 是 Linux 內核提供的非常強大的系統(tǒng)調用,通過 ptrace 可以實現(xiàn)進程的單步調試和收集系統(tǒng)調用情況。比如 strace 和 gdb 都是基于 ptrace 實現(xiàn)的,strace 可以顯示進程調用了哪些系統(tǒng)調用,gdb 可以實現(xiàn)對進程的調試。本文介紹這些工具的底層 ptrace 是如何實現(xiàn)的。這里選用了 1.2.13 的早期版本,原理是類似的,新版內核代碼過多,沒必要陷入過多細節(jié)中。
1 進程調試
ptrace 系統(tǒng)調用的實現(xiàn)中包含了很多功能,首先來看一下單步調試的實現(xiàn)。通過 ptrace 實現(xiàn)單步調試的方式有兩種。
1. 父進程執(zhí)行 fork 創(chuàng)建一個子進程,通過 ptrace 設置子進程為 PF_PTRACED 標記,然后執(zhí)行 execve 加載被調試的程序。
2. 通過 ptrace attach 到指定的 pid 完成對進程的調試(控制)。
首先看一下第一種的實現(xiàn)。
1.1 方式1
- pid_t pid = fork();// 子進程if (pid == 0) {
 - ptrace(PTRACE_TRACEME,0,NULL,NULL);
 - // 加載被調試的程序
 - execve(argv[1], NULL, NULL);
 - }
 
執(zhí)行 fork 創(chuàng)建子進程后,通過 ptrace 的 PTRACE_TRACEME 指示操作系統(tǒng)設置子進程為被調試(設置 PF_PTRACED 標記)。來看一下這一步操作系統(tǒng)做了什么事情。
- asmlinkage int sys_ptrace(long request, long pid, long addr, long data){
 - if (request == PTRACE_TRACEME) {
 - current->flags |= PF_PTRACED;
 - return 0;
 - }
 - }
 
這一步非常簡單,接著看 execve 加載程序到內存執(zhí)行時又是如何處理的。
- int do_execve(char * filename, char ** argv, char ** envp, struct pt_regs * regs) {
 - // 加載程序
 - for (fmt = formats ; fmt ; fmt = fmt->next) {
 - int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary;
 - retval = fn(&bprm, regs);
 - }
 - }
 
do_execve 邏輯非常復雜,不過我們只關注需要的就好。do_execve 通過鉤子函數(shù)加載程序,我們看看 formats 是什么。
- struct linux_binfmt {
 - struct linux_binfmt * next;
 - int *use_count;
 - int (*load_binary)(struct linux_binprm *, struct pt_regs * regs);
 - int (*load_shlib)(int fd);
 - int (*core_dump)(long signr, struct pt_regs * regs);
 - };
 - static struct linux_binfmt *formats = &aout_format;int register_binfmt(struct linux_binfmt * fmt){
 - struct linux_binfmt ** tmp = &formats;
 - if (!fmt)
 - return -EINVAL;
 - if (fmt->next)
 - return -EBUSY;
 - while (*tmp) {
 - if (fmt == *tmp)
 - return -EBUSY;
 - tmp = &(*tmp)->next;
 - }
 - *tmp = fmt;
 - return 0;
 - }
 
可以看到 formats 是一個鏈表??梢酝ㄟ^ register_binfmt 函數(shù)注冊節(jié)點。那么誰調用了這個函數(shù)呢?
- struct linux_binfmt elf_format = {
 - NULL, NULL, load_elf_binary, load_elf_library, NULL};int init_module(void) {
 - register_binfmt(&elf_format);
 - return 0;
 - }
 
所以最終調用了 load_elf_binary 函數(shù)加載程序。同樣我們只關注相關的邏輯。
- if (current->flags & PF_PTRACED)
 - send_sig(SIGTRAP, current, 0);
 
load_elf_binary 中會判斷如果進程設置了 PF_PTRACED 標記,那么會給當前進程發(fā)送一個 SIGTRAP 信號。接著看信號處理函數(shù)的相關邏輯。
- if ((current->flags & PF_PTRACED) && signr != SIGKILL) {
 - current->exit_code = signr;
 - // 修改當前進程(被調試的進程)為暫停狀態(tài)
 - current->state = TASK_STOPPED;
 - // 通知父進程
 - notify_parent(current);
 - // 調度其他進程執(zhí)行
 - schedule();
 - }
 
所以程序被加載到內存后,根本沒有機會執(zhí)行就直接被修改為暫停狀態(tài)了,接下來看看 notify_parent 通知父進程干什么。
- void notify_parent(struct task_struct * tsk){
 - // 給父進程發(fā)送 SIGCHLD 信號
 - if (tsk->p_pptr == task[1])
 - tsk->exit_signal = SIGCHLD;
 - send_sig(tsk->exit_signal, tsk->p_pptr, 1);
 - wake_up_interruptible(&tsk->p_pptr->wait_chldexit);
 - }
 
父進程收到信號后,可以通過 sys_ptrace 控制子進程,sys_ptrace 還提供了很多功能,比如讀取子進程的數(shù)據(jù)。
- // pid 為子進程 id
 - num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL);
 
這個就不展開了,主要是內存的校驗和數(shù)據(jù)讀取。這里講一下 PTRACE_SINGLESTEP 命令,這個命令控制子進程單步執(zhí)行的。
- case PTRACE_SINGLESTEP: { /* set the trap flag. */
 - long tmp;
 - child->flags &= ~PF_TRACESYS;
 - // 設置 eflags 的單步調試 flag
 - tmp = get_stack_long(child, sizeof(long)*EFL-MAGICNUMBER) | TRAP_FLAG;
 - put_stack_long(child, sizeof(long)*EFL-MAGICNUMBER,tmp);
 - // 修改子進程狀態(tài)為可執(zhí)行
 - child->state = TASK_RUNNING;
 - child->exit_code = data;
 - return 0;
 - }
 
PTRACE_SINGLESTEP 讓子進程重新進入運行狀態(tài),但是有一個很關鍵的是,設置好了單步調試 flag。我們看看 trap flag 是什么。
- A trap flag permits operation of a processor in single-step mode. If such a flag is available, debuggers can use it to step through the execution of a computer program.
 
也就是說,子進程執(zhí)行一個指令后,就會被中斷,然后系統(tǒng)會給被調試進程發(fā)送 SIGTRAP 信號。同樣,被調試進程在信號處理函數(shù)里,通知父進程,從而控制權又回到了父進程手中,如此循環(huán)。
1.2 方式2
除了開始時通過 ptrace 設置進程調試,也可以通過 ptrace 動態(tài)設置調試進程的能力,具體是通過 PTRACE_ATTACH 命令實現(xiàn)的。
- if (request == PTRACE_ATTACH) {
 - // 設置被調試標記
 - child->flags |= PF_PTRACED;
 - // 設置和父進程的關系
 - if (child->p_pptr != current) {
 - REMOVE_LINKS(child);
 - child->p_pptr = current;
 - SET_LINKS(child);
 - }
 - // 給被調試進程發(fā)送 SIGSTOP 信號
 - send_sig(SIGSTOP, child, 1);
 - return 0;
 - }
 
前面已經(jīng)分析過,信號處理函數(shù)里會設置進程為暫停狀態(tài),然后通知主進程,主進程就可以控制子進程,具體和前面流程一樣。
2 跟蹤系統(tǒng)調用
ptrace 處理追蹤進程執(zhí)行過程之外,還可以實現(xiàn)跟蹤系統(tǒng)調用。具體是通過 PTRACE_SYSCALL 命令實現(xiàn)。
- case PTRACE_SYSCALL:
 - case PTRACE_CONT: {
 - long tmp;
 - // 設置 PF_TRACESYS 標記
 - if (request == PTRACE_SYSCALL)
 - child->flags |= PF_TRACESYS;
 - child->exit_code = data;
 - child->state = TASK_RUNNING;
 - // 清除 trap flag 標記
 - tmp = get_stack_long(child, sizeof(long)*EFL-MAGICNUMBER) & ~TRAP_FLAG;
 - put_stack_long(child, sizeof(long)*EFL-MAGICNUMBER,tmp);
 - return 0;
 - }
 
看起來很簡單,就是設置了一個新的標記 PF_TRACESYS。看看這個標記有什么用。
- // 調用 syscall_trace 函數(shù)
 - 1: call _syscall_trace
 - movl
 - movl ORIG_EAX(%esp),%eax
 - // 調用系統(tǒng)調用
 - call _sys_call_table(,%eax,4)
 - movl %eax,EAX(%esp) # save the return value
 - movl _current,%eax
 - movl errno(%eax),%edx
 - negl %edx
 - je 1f
 - movl %edx,EAX(%esp)
 - orl $(CF_MASK),EFLAGS(%esp) # set carry to indicate error
 - // 調用 syscall_trace 函數(shù)
 - 1: call _syscall_trace
 
可以看到在系統(tǒng)調用的前后都有一個 syscall_trace 的邏輯,所以在系統(tǒng)調用前和后,我們都可以做點事情。來看看這個函數(shù)做了什么。
- asmlinkage void syscall_trace(void){
 - // 暫停子進程,通知父進程,并調度其他進程執(zhí)行
 - current->exit_code = SIGTRAP;
 - current->state = TASK_STOPPED;
 - notify_parent(current);
 - schedule();
 - }
 
這里的邏輯就是把邏輯切換到主進程中,然后主進程就可以通過命令獲取被調試進程的系統(tǒng)調用信息。下面是一個追蹤進程所有系統(tǒng)調用的例子。
- /*
 - use ptrace to find all system call that call by certain process
 - */
 - #include <sys/ptrace.h>
 - #include <unistd.h>
 - #include <stdlib.h>
 - #include <sys/wait.h>
 - #include <stdio.h>
 - #include <sys/reg.h>
 - int main(int argc, char *argv[]) {
 - pid_t pid = fork();
 - if (pid < 0) {
 - printf("fork failed");
 - exit(-1);
 - } else if (pid == 0) {
 - // set state of child process to PTRACE
 - ptrace(PTRACE_TRACEME,0,NULL,NULL);
 - // child will change to stopped state when in execve call, then send the signal to parent
 - execve(argv[1], NULL, NULL);
 - } else {
 - int status;
 - int bit = 1;
 - long num;
 - long ret;
 - // wait for child
 - wait(&status);
 - if(WIFEXITED(status))
 - return 0;
 - // this is for execve call which will not return, and for os of 64-it => ORIG_RAX * 8 or os of 32-it => ORIG_EAX * 4
 - num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL);
 - printf("system call num = %ld\n", num);
 - ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
 - while(1) {
 - wait(&status);
 - if(WIFEXITED(status))
 - return 0;
 - // for enter system call
 - if(bit) {
 - num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL);
 - printf("system call num = %ld", num);
 - bit = 0;
 - } else { // for return of system call
 - ret = ptrace(PTRACE_PEEKUSER, pid, RAX*8, NULL);
 - printf("system call return = %ld \n", ret);
 - bit = 1;
 - }
 - // let this child process continue to run until call next system call
 - ptrace(PTRACE_SYSCALL,pid,NULL,NULL);
 - }
 - }
 - }
 
總結
ptrace 功能復雜而強大,理解它的原理對理解其他技術和工具都非常有意義,本文大概做了一個介紹,有興趣的同學可以自行查看源碼。















 
 
 












 
 
 
 