[英]How to “use the write() system call to read from the page (writing to a dummy pipe() file descriptor)” in C/C++?
I need to test if memory address is readable, so I searched and found this question: How to test if an address is readable in linux userspace app As user @caf stated: 我需要测试内存地址是否可读,因此我搜索并发现了以下问题: 如何在Linux用户空间应用程序中测试地址是否可读如用户@caf所述:
The canonical way is to use the write() system call to read from the page (writing to a dummy pipe() file descriptor). 规范的方法是使用write()系统调用从页面读取(写入哑管道()文件描述符)。
Unfortunatelly he didn't provide any code example, and I can't comment (low reputation) nor send him a message (at least I don't know how). 不幸的是,他没有提供任何代码示例,并且我无法评论(信誉低下),也无法向他发送消息(至少我不知道如何)。
EDIT 编辑
Can't I just omit creating the pipe by doing something like that? 我不能只通过做类似的事情来创建管道吗?
int result = write(0, addr, 1);
@Mats Petersson: I'm trying to analyze and change a function after already loading it to memory using function pointer (I'm incrementing the pointer and copying its value byte by byte), so to determine whether it's still this function i need to know if the memory is writeable and readable (it's a little stupid thing to do, I know). @Mats Petersson:我已经尝试使用函数指针将其加载到内存中之后分析和更改一个函数(我正在递增指针并逐字节复制其值),以便确定它是否仍然是该函数,我需要知道内存是否可写和可读(我知道这有点愚蠢)。 Anyhow I'd like to not change my program's memory reading/writing privileges, so what you've said might be a problem. 无论如何,我不想更改程序的内存读取/写入权限,所以您所说的可能是个问题。
EDIT 2 @Damon: so is there any other sure way to do this? 编辑2 @Damon:那么还有其他确定的方法吗?
First, create a pipe pair to write the data to: 首先,创建一个管道对以将数据写入:
int fd[2];
pipe(fd);
Then try to write some data from your address to the write side of the pipe: 然后尝试将一些数据从您的地址写入管道的写入端:
int result = write(fd[1], addr, 1);
If result
is 1, the write succeeded, so the address was readable. 如果result
为1,则写入成功,因此该地址可读取。 If it's zero and errno == EFAULT
, the address is not readable. 如果为零且errno == EFAULT
,则该地址不可读。 If errno
is something else, something else went wrong. 如果errno
是其他问题,则其他地方出了问题。
Make sure to close the pipes once you're done, of course: 当然,请确保完成后关闭管道:
close(fd[0]);
close(fd[1]);
I've never used that method myself, but I think that yo have to create a pipe (using the pipe
system call), when write
to that pipe providing the address you want to check as the buffer. 我自己从未使用过该方法,但是我认为您必须创建一个管道(使用pipe
系统调用),然后在write
该管道时提供您要检查的地址作为缓冲区。
So lets say you want to check address 0x1000000
, then you do eg 因此,假设您要检查地址0x1000000
,然后执行例如
int res = write(dummypipe[1], 0x1000000, 1);
If res
is -1
then you check if errno == EFAULT
which indicates that the address is not valid. 如果res
为-1
则检查errno == EFAULT
是否表示该地址无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.