Ptracing系统调用

时间:2012-03-18 15:37:57

标签: c system-calls ptrace

我有以下代码:

void
attach_to_pid (int pid, char *username, int pts)
{
  int sys_call_nr = 0;
  struct user_regs_struct regs;
  ptrace (PTRACE_ATTACH, pid, 0, 0);
  waitpid (pid, 0, WCONTINUED);
  ptrace (PTRACE_SETOPTIONS, pid, 0,
          PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT);
  while (true)
    {
      ptrace (PTRACE_SYSCALL, pid, 0, 0);
      int status;
      waitpid (pid, &status, WCONTINUED);
      if (status == (SIGTRAP | PTRACE_EVENT_EXIT << 8))
        break;
      ptrace (PTRACE_GETREGS, pid, 0, &regs);
#ifdef __i386__
      sys_call_nr = regs.eax;
#elif __x86_64__
      sys_call_nr = regs.rax;
#else
#error "Unsupported architecture."
#endif
      if (sys_call_nr == __NR_write)
        {
          printf ("read!");
        }
      ptrace (PTRACE_SYSCALL, pid, 0, 0);
      waitpid (pid, &status, WCONTINUED);
ptrace(PTRACE_GETREGS,pid,0,&regs);
printf("%d = %d\n",sys_call_nr,regs.eax);
//ptrace(PTRACE_CONT, pid, 0 , 0);
    }
  ptrace (PTRACE_DETACH, pid, 0, 0);
}

我得到了奇怪的结果,如下:

-514 = -38
-514 = -38
1 = -38
0 = -38
...

通常,当使用strace sshd会话时,我总是在写入shell时获得对读写系统调用的调用。但是有了这个功能,我没有得到(假设我猜)系统调用,只有(你可以看到):1,等等......

任何人都可以帮助我吗?感谢。

2 个答案:

答案 0 :(得分:1)

即使我在同一个问题上挣扎。而您的问题与this完全相同 答案有更精美的解释。这是我的版本:
您的程序需要区分系统调用条目和系统调用退出。
为此保留一个变量。看看这个code。变量in_syscall在这里也是如此。希望这会对你有所帮助。
下次在发布问题之前,先在这里进行基础研究(重新搜索)。节省了很多时间;)我们也是:D

答案 1 :(得分:1)

这是我的解决方案:

  struct user_regs_struct regs /*_on_entry, regs_on_exit*/ ;
  ptrace (PTRACE_ATTACH, pid, 0, 0);
  waitpid (pid, 0, WCONTINUED);
  while (true)
    {
      ptrace (PTRACE_SYSCALL, pid, 0, 0);
      int status;
      wait (&status);
#ifdef __i386__
      int eax = ptrace (PTRACE_PEEKUSER, pid, ORIG_EAX * 4, 0);
      ptrace (PTRACE_GETREGS, pid, 0, &regs);
      ptrace (PTRACE_SYSCALL, pid, 0, 0);
      waitpid (pid, &status, WCONTINUED);
      if (eax == __NR_read && regs.ebx == 10)
        {
          int *buffer = (int *) malloc (regs.eax + 3);
          int i = 0;
          for (int j = 0; i < regs.eax; i += 4, j++)
            {
              buffer[j] = ptrace (PTRACE_PEEKTEXT, pid, regs.ecx + i, 0);
            }
          if (regs.edx % 4)     // rest of chunk.
            {
              buffer[i] =
                ptrace (PTRACE_PEEKUSER, pid, regs.ecx + 2 * i - regs.eax, 0);
            }
          write (1, buffer, regs.eax);
          free (buffer);
        }
#elif __x86_64__
#else
#error "Unsupported architecture."
#endif
    }

感谢您的回复!

相关问题