如何在 C/C++ 中 "use the write() system call to read from the page (writing to a dummy pipe() file descriptor)"?

How to "use the write() system call to read from the page (writing to a dummy pipe() file descriptor)" in C/C++?

我需要测试内存地址是否可读,于是搜索了一下,发现了这个问题: How to test if an address is readable in linux userspace app 正如用户@caf 所说:

The canonical way is to use the write() system call to read from the page (writing to a dummy pipe() file descriptor).

可惜他没有提供任何代码示例,我不能评论(低信誉)也不能给他发消息(至少我不知道如何)。

编辑

我不能通过做类似的事情来省略创建管道吗?

int result = write(0, addr, 1);

@Mats Petersson:在使用函数指针将函数加载到内存后,我正在尝试分析和更改函数(我正在递增指针并逐字节复制其值),以确定它是否仍然这个函数我需要知道内存是否可写和可读(我知道这是一件有点愚蠢的事情)。无论如何我不想改变我的程序的内存 reading/writing 特权,所以你所说的可能是个问题。

编辑 2 @Damon:还有其他确定的方法吗?

首先,创建一个管道对将数据写入:

 int fd[2];
 pipe(fd);

然后尝试将一些数据从您的地址写入管道的写入端:

 int result = write(fd[1], addr, 1);

如果result为1,写入成功,地址可读。如果它为零且 errno == EFAULT,则该地址不可读。如果 errno 是别的东西,那就是别的东西出错了。

完成后一定要关闭管道,当然:

 close(fd[0]);
 close(fd[1]);

我自己从未使用过该方法,但我认为你必须创建一个管道(使用 pipe 系统调用),当 write 到那个提供你想要的地址的管道时检查缓冲区。

假设您要检查地址 0x1000000,那么您可以这样做,例如

int res = write(dummypipe[1], 0x1000000, 1);

如果 res-1 那么您检查 errno == EFAULT 是否表明地址无效。