我正在完成一项任务,我必须在其中实现 strace
喜欢使用 ptrace
的功能.到目前为止,我已经找到了如何提取系统调用号和返回值,如下所示:
//In parent process
struct user_regs_struct regs;
ptrace( PTRACE_GETREGS, child_pid, 0, ®s );
//child_pid is the pid of child process executing the required program
//or system call passed as command line arguments
syscall_num = regs.orig_rax;
syscall_retval = regs.rax;
但我一直无法找到如何提取系统调用名称和参数。
任何人都可以提出一种方法吗?
最佳答案
要获取系统调用的参数,您必须一一读取寄存器。为此,您需要知道哪些寄存器将存储系统调用的哪些参数。几个月前,我自己编写了一个这样的程序。基本上每个寄存器存储的是这样的:
regs.rdi - Stores the first argument
regs.rsi - Stores the second argument
regs.rdx - Stores the third argument
regs.r10 - Stores the fourth argument
regs.r8 - Stores the fifth argument
regs.r9 - Stores the sixth argument
此 table提供了更详细的描述(请注意,它特定于 x86-64 体系结构)。
现在,您必须阅读每个系统调用的文档以分别理解它们并为其编写代码。阅读不同的论点有不同的方法。
让我们拿
read()
系统调用来演示这一点。 我们将看到不同类型的参数并了解如何访问它们。
1st argument (int fd)
因为是数字所以会直接保存在寄存器
regs.rdi
中.在我的代码中,我需要获取
fd
所在的文件指向所以我使用了以下代码。sprintf(fdpath,"/proc/%u/fd/%llu",proc,regs.rdi);
size = readlink(fdpath, filepath, 256); //this gives the filepath for a particular fd
filepath[size] = '\0';
printf("File-%s-\n", filepath);
2nd argument (void *buf) ptr to input buffer
要阅读本文,您需要使用
PTRACE_PEEKDATA
/PTRACE_PEEKTEXT
请求( ptrace()
的第一个参数)读取字节。自 ptrace()
仅读取和返回 8
一次字节,您需要使用 long
迭代地执行此操作多变的。应该还有一个 char *
指向内存的开头,稍后将用于读取字符串。我使用的代码如下。
char message[1000];
char* temp_char2 = message;
int j = 0;
long temp_long;
while( j < (regs.rdx/8) ) //regs.rdx stores the size of the input buffer
{
temp_long = ptrace(PTRACE_PEEKDATA, proc, regs.rsi + (j*8) , NULL);
memcpy(temp_char2, &temp_long, 8);
temp_char2 += sizeof(long);
++j;
}
message[regs.rdx] = '\0';
printf("Message-%s-\n\n", message);
这就是我能说的。我猜你可以通过这种方式读取大多数系统调用的几乎所有参数。
至于系统调用的名称。我的OS映射并做了手册
switch
case 获取系统调用的名称。希望这可以帮助。 :)
关于c - 使用 ptrace 提取系统调用名称和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33431994/