使用来自多线程应用程序的ptrace

Using ptrace from multithreaded applications

本文关键字:应用程序 ptrace 多线程      更新时间:2023-10-16

我想使用ptrace来检查由我的程序生成的程序的系统调用。我从本教程开始,因为它在回答我之前的问题时进行了解释。我修改了代码,使其适应我使用的平台(SLES 11 64位),并将以下测试代码组合在一起,打印出派生进程进行的每个系统调用:

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/reg.h>
#include <sys/syscall.h>   /* For SYS_write etc */
pid_t child;
void run()
{
long orig_eax;
int status;
while(1) {
int pid = wait(&status);
if (pid == -1) {
perror("wait");
kill(child, SIGKILL);
return;
}
printf("Got event from %d.n", pid);
if(WIFEXITED(status))
break;
orig_eax = ptrace(PTRACE_PEEKUSER,
pid, 8 * ORIG_RAX, NULL);
if (orig_eax == -1) {
perror("ptrace");
kill(child, SIGKILL);
return;
} else {
printf("Syscall %ld called.n", orig_eax);
}
ptrace(PTRACE_SYSCALL,
pid, NULL, NULL);
}
}
int main(int /*argc*/, char* argv[])
{
child = fork();
if(child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execl(argv[1], argv[1], NULL);
}
else {
printf("Child process id = %d.n", child);
run();
}
return 0;
}

它工作得很好:它打印程序进行的系统调用的id(实际上,它将每个调用打印两次,一次在入口,一次用于出口,但现在这无关紧要)。然而,除了检查系统调用之外,我的程序还需要做其他事情,所以我决定将检查转移到一个单独的线程(我对C++比C更熟悉,所以我用C++的方式做了,但我认为这无关紧要)。当然,在这个最新的程序中,我只启动线程,然后加入它

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/reg.h>
#include <sys/syscall.h>   /* For SYS_write etc */
#include <boost/thread.hpp>

pid_t child;
void run()
{
long orig_eax;
int status;
while(1) {
int pid = wait(&status);
if (pid == -1) {
perror("wait");
kill(child, SIGKILL);
return;
}
printf("Got event from %d.n", pid);
if(WIFEXITED(status))
break;
orig_eax = ptrace(PTRACE_PEEKUSER,
pid, 8 * ORIG_RAX, NULL);
if (orig_eax == -1) {
perror("ptrace");
kill(child, SIGKILL);
return;
} else {
printf("Syscall %ld called.n", orig_eax);
}
ptrace(PTRACE_SYSCALL,
pid, NULL, NULL);
}
}
int main(int /*argc*/, char* argv[])
{
child = fork();
if(child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execl(argv[1], argv[1], NULL);
}
else {
printf("Child process id = %d.n", child);
boost::thread t(run);
t.join();
}
return 0;
}

这次我收到一条错误消息:

Child process id = 24682.
Got event from 24682.
ptrace: No such process

为什么会这样?我试着寻找答案,但没有找到这样的答案。我发现ptrace不会跟踪子进程启动的线程,但这是以后需要处理的另一件事。这甚至可以从不同的治疗中检查孩子的过程吗?

另一件奇怪的事情是,在我的实际应用程序中,我基本上做同样的事情(但来自更复杂的上下文:类、互斥体等),但我会得到不同类型的错误。ptrace没有返回错误,wait甚至不会返回子进程上的系统调用(子进程甚至不会停止)。另一方面,当子进程退出时,wait按预期工作。

据我所知,ptrace每个进程只允许一个跟踪器。这意味着,如果您尝试附加(可以尝试使用PTRACE_ATTACH强制执行),您将收到一个错误,告知ptrace无法附加到指定的进程。

因此,出现错误是因为您的线程没有附加到子进程,这样,当您尝试ptrace时,它会失败,从而发送-ESRCH代码。

此外,你可以在这里看看这篇文章,它可能会回答除此之外的其他一些问题。