一篇学会Linux ptrace 的实现

系统 Linux
本文介绍这些工具的底层 ptrace 是如何实现的。这里选用了 1.2.13 的早期版本,原理是类似的,新版内核代码过多,没必要陷入过多细节中。

[[438549]]

ptrace 是 Linux 内核提供的非常强大的系统调用,通过 ptrace 可以实现进程的单步调试和收集系统调用情况。比如 strace 和 gdb 都是基于 ptrace 实现的,strace 可以显示进程调用了哪些系统调用,gdb 可以实现对进程的调试。本文介绍这些工具的底层 ptrace 是如何实现的。这里选用了 1.2.13 的早期版本,原理是类似的,新版内核代码过多,没必要陷入过多细节中。

1 进程调试

ptrace 系统调用的实现中包含了很多功能,首先来看一下单步调试的实现。通过 ptrace 实现单步调试的方式有两种。

1. 父进程执行 fork 创建一个子进程,通过 ptrace 设置子进程为 PF_PTRACED 标记,然后执行 execve 加载被调试的程序。

2. 通过 ptrace attach 到指定的 pid 完成对进程的调试(控制)。

首先看一下第一种的实现。

1.1 方式1

  1. pid_t pid = fork();// 子进程if (pid == 0) { 
  2.     ptrace(PTRACE_TRACEME,0,NULL,NULL); 
  3.     // 加载被调试的程序 
  4.     execve(argv[1], NULLNULL); 

执行 fork 创建子进程后,通过 ptrace 的 PTRACE_TRACEME 指示操作系统设置子进程为被调试(设置 PF_PTRACED 标记)。来看一下这一步操作系统做了什么事情。

  1. asmlinkage int sys_ptrace(long request, long pid, long addr, long data){ 
  2.     if (request == PTRACE_TRACEME) { 
  3.         current->flags |= PF_PTRACED; 
  4.         return 0; 
  5.     } 

这一步非常简单,接着看 execve 加载程序到内存执行时又是如何处理的。

  1. int do_execve(char * filename, char ** argv, char ** envp, struct pt_regs * regs) { 
  2.     // 加载程序 
  3.     for (fmt = formats ; fmt ; fmt = fmt->next) { 
  4.         int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary; 
  5.         retval = fn(&bprm, regs); 
  6.     } 

do_execve 逻辑非常复杂,不过我们只关注需要的就好。do_execve 通过钩子函数加载程序,我们看看 formats 是什么。

  1. struct linux_binfmt { 
  2.     struct linux_binfmt * next
  3.     int *use_count; 
  4.     int (*load_binary)(struct linux_binprm *, struct  pt_regs * regs); 
  5.     int (*load_shlib)(int fd); 
  6.     int (*core_dump)(long signr, struct pt_regs * regs); 
  7. }; 
  8.  
  9. static struct linux_binfmt *formats = &aout_format;int register_binfmt(struct linux_binfmt * fmt){ 
  10.     struct linux_binfmt ** tmp = &formats; 
  11.  
  12.     if (!fmt) 
  13.         return -EINVAL; 
  14.     if (fmt->next
  15.         return -EBUSY; 
  16.     while (*tmp) { 
  17.         if (fmt == *tmp) 
  18.             return -EBUSY; 
  19.         tmp = &(*tmp)->next
  20.     } 
  21.     *tmp = fmt; 
  22.     return 0;    

可以看到 formats 是一个链表。可以通过 register_binfmt 函数注册节点。那么谁调用了这个函数呢?

  1. struct linux_binfmt elf_format = { 
  2.  
  3. NULLNULL, load_elf_binary, load_elf_library, NULL};int init_module(void) { 
  4.  
  5. register_binfmt(&elf_format); 
  6.  
  7. return 0; 
  8.  

所以最终调用了 load_elf_binary 函数加载程序。同样我们只关注相关的逻辑。

  1. if (current->flags & PF_PTRACED) 
  2.         send_sig(SIGTRAP, current, 0); 

load_elf_binary 中会判断如果进程设置了 PF_PTRACED 标记,那么会给当前进程发送一个 SIGTRAP 信号。接着看信号处理函数的相关逻辑。

  1. if ((current->flags & PF_PTRACED) && signr != SIGKILL) { 
  2.     current->exit_code = signr; 
  3.     // 修改当前进程(被调试的进程)为暂停状态 
  4.     current->state = TASK_STOPPED; 
  5.     // 通知父进程 
  6.     notify_parent(current); 
  7.     // 调度其他进程执行 
  8.     schedule(); 

所以程序被加载到内存后,根本没有机会执行就直接被修改为暂停状态了,接下来看看 notify_parent 通知父进程干什么。

  1. void notify_parent(struct task_struct * tsk){    
  2.     // 给父进程发送 SIGCHLD 信号 
  3.     if (tsk->p_pptr == task[1]) 
  4.         tsk->exit_signal = SIGCHLD; 
  5.     send_sig(tsk->exit_signal, tsk->p_pptr, 1); 
  6.     wake_up_interruptible(&tsk->p_pptr->wait_chldexit); 

父进程收到信号后,可以通过 sys_ptrace 控制子进程,sys_ptrace 还提供了很多功能,比如读取子进程的数据。

  1. // pid 为子进程 id 
  2.  
  3. num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL); 

这个就不展开了,主要是内存的校验和数据读取。这里讲一下 PTRACE_SINGLESTEP 命令,这个命令控制子进程单步执行的。

  1. case PTRACE_SINGLESTEP: {  /* set the trap flag. */ 
  2.         long tmp; 
  3.         child->flags &= ~PF_TRACESYS; 
  4.         // 设置 eflags 的单步调试 flag 
  5.         tmp = get_stack_long(child, sizeof(long)*EFL-MAGICNUMBER) | TRAP_FLAG; 
  6.         put_stack_long(child, sizeof(long)*EFL-MAGICNUMBER,tmp); 
  7.         // 修改子进程状态为可执行 
  8.         child->state = TASK_RUNNING; 
  9.         child->exit_code = data; 
  10.         return 0; 

PTRACE_SINGLESTEP 让子进程重新进入运行状态,但是有一个很关键的是,设置好了单步调试 flag。我们看看 trap flag 是什么。

  1. 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. 

也就是说,子进程执行一个指令后,就会被中断,然后系统会给被调试进程发送 SIGTRAP 信号。同样,被调试进程在信号处理函数里,通知父进程,从而控制权又回到了父进程手中,如此循环。

1.2 方式2

除了开始时通过 ptrace 设置进程调试,也可以通过 ptrace 动态设置调试进程的能力,具体是通过 PTRACE_ATTACH 命令实现的。

  1. if (request == PTRACE_ATTACH) { 
  2.         // 设置被调试标记 
  3.         child->flags |= PF_PTRACED; 
  4.         // 设置和父进程的关系 
  5.         if (child->p_pptr != current) { 
  6.             REMOVE_LINKS(child); 
  7.             child->p_pptr = current
  8.             SET_LINKS(child); 
  9.         } 
  10.         // 给被调试进程发送 SIGSTOP 信号 
  11.         send_sig(SIGSTOP, child, 1); 
  12.         return 0; 

前面已经分析过,信号处理函数里会设置进程为暂停状态,然后通知主进程,主进程就可以控制子进程,具体和前面流程一样。

2 跟踪系统调用

ptrace 处理追踪进程执行过程之外,还可以实现跟踪系统调用。具体是通过 PTRACE_SYSCALL 命令实现。

  1. case PTRACE_SYSCALL: 
  2. case PTRACE_CONT: { 
  3.     long tmp; 
  4.     // 设置 PF_TRACESYS 标记 
  5.     if (request == PTRACE_SYSCALL) 
  6.         child->flags |= PF_TRACESYS; 
  7.     child->exit_code = data; 
  8.     child->state = TASK_RUNNING; 
  9.     // 清除 trap flag 标记 
  10.     tmp = get_stack_long(child, sizeof(long)*EFL-MAGICNUMBER) & ~TRAP_FLAG; 
  11.     put_stack_long(child, sizeof(long)*EFL-MAGICNUMBER,tmp); 
  12.     return 0; 

看起来很简单,就是设置了一个新的标记 PF_TRACESYS。看看这个标记有什么用。

  1. // 调用 syscall_trace 函数 
  2. 1:  call _syscall_trace 
  3.     movl  
  4.     movl ORIG_EAX(%esp),%eax 
  5.     // 调用系统调用 
  6.     call _sys_call_table(,%eax,4) 
  7.     movl %eax,EAX(%esp)     # save the return value 
  8.     movl _current,%eax 
  9.     movl errno(%eax),%edx 
  10.     negl %edx 
  11.     je 1f 
  12.     movl %edx,EAX(%esp) 
  13.     orl $(CF_MASK),EFLAGS(%esp) # set carry to indicate error 
  14. // 调用 syscall_trace 函数 
  15. 1:  call _syscall_trace 

可以看到在系统调用的前后都有一个 syscall_trace 的逻辑,所以在系统调用前和后,我们都可以做点事情。来看看这个函数做了什么。

  1. asmlinkage void syscall_trace(void){ 
  2.     // 暂停子进程,通知父进程,并调度其他进程执行 
  3.     current->exit_code = SIGTRAP; 
  4.     current->state = TASK_STOPPED; 
  5.     notify_parent(current); 
  6.     schedule(); 

这里的逻辑就是把逻辑切换到主进程中,然后主进程就可以通过命令获取被调试进程的系统调用信息。下面是一个追踪进程所有系统调用的例子。

  1. /* 
  2.   use ptrace to find all system call that call by certain process 
  3. */ 
  4. #include <sys/ptrace.h> 
  5. #include <unistd.h> 
  6. #include <stdlib.h> 
  7. #include <sys/wait.h> 
  8. #include <stdio.h> 
  9. #include <sys/reg.h> 
  10.  
  11. int main(int argc, char *argv[]) { 
  12.     pid_t pid = fork(); 
  13.     if (pid < 0) { 
  14.         printf("fork failed"); 
  15.         exit(-1); 
  16.     } else if (pid == 0) { 
  17.         // set state of child process to PTRACE 
  18.         ptrace(PTRACE_TRACEME,0,NULL,NULL); 
  19.         // child will change to stopped state when in execve call, then send the signal to parent 
  20.         execve(argv[1], NULLNULL); 
  21.     } else { 
  22.         int status; 
  23.         int bit = 1; 
  24.         long num; 
  25.         long ret; 
  26.         // wait for child 
  27.         wait(&status); 
  28.         if(WIFEXITED(status)) 
  29.             return 0; 
  30.         // this is for execve call which will not returnand for os of 64-it => ORIG_RAX * 8 or os of 32-it => ORIG_EAX * 4 
  31.         num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL); 
  32.         printf("system call num = %ld\n", num); 
  33.         ptrace(PTRACE_SYSCALL, pid, NULLNULL); 
  34.         while(1) { 
  35.             wait(&status); 
  36.             if(WIFEXITED(status)) 
  37.                 return 0; 
  38.             // for enter system call 
  39.             if(bit) { 
  40.                 num = ptrace(PTRACE_PEEKUSER, pid, ORIG_RAX * 8, NULL); 
  41.                 printf("system call num = %ld", num); 
  42.                 bit = 0; 
  43.             } else { // for return of system call 
  44.                 ret = ptrace(PTRACE_PEEKUSER, pid, RAX*8, NULL); 
  45.                 printf("system call return = %ld \n", ret); 
  46.                 bit = 1; 
  47.             } 
  48.             // let this child process continue to run until call next system call 
  49.             ptrace(PTRACE_SYSCALL,pid,NULL,NULL); 
  50.         } 
  51.     } 

总结

 

ptrace 功能复杂而强大,理解它的原理对理解其他技术和工具都非常有意义,本文大概做了一个介绍,有兴趣的同学可以自行查看源码。

 

责任编辑:武晓燕 来源: 编程杂技
相关推荐

2022-05-17 08:02:55

GoTryLock模式

2021-10-29 07:35:32

Linux 命令系统

2022-03-17 19:29:04

CSS切角自适应

2024-04-02 12:36:01

2022-01-02 08:43:46

Python

2021-08-01 07:19:16

语言OpenrestyNginx

2022-06-30 22:53:18

数据结构算法

2021-07-06 08:59:18

抽象工厂模式

2021-05-11 08:54:59

建造者模式设计

2021-07-05 22:11:38

MySQL体系架构

2023-01-03 08:31:54

Spring读取器配置

2021-07-02 09:45:29

MySQL InnoDB数据

2022-08-26 09:29:01

Kubernetes策略Master

2022-08-23 08:00:59

磁盘性能网络

2023-11-28 08:29:31

Rust内存布局

2022-02-07 11:01:23

ZooKeeper

2022-01-12 07:36:01

Java数据ByteBuffer

2021-12-01 06:59:27

Linux发行版Manjaro

2021-10-26 10:40:26

代理模式虚拟

2021-12-07 08:50:40

字母区间字符串
点赞
收藏

51CTO技术栈公众号