我的程序将数据指针传递给第三方插件,意图数据应该是只读的,因此阻止插件写入数据对象会很好.理想情况下,如果插件尝试写入,则会出现段错误.我听说有一些方法可以对内存区域进行双重映射,这样第二个虚拟地址范围就指向相同的物理内存页面.第二个映射没有写入权限,导出的指针将使用此地址范围而不是原始(可写)地址范围.我宁愿不更改原始内存分配,无论它们是否碰巧使用malloc或mmap或其他.有人可以解释如何做到这一点?
最佳答案
可以获得双映射,但它需要一些工作.
我知道如何创建这种双映射的唯一方法是使用mmap函数调用.对于mmap,您需要某种文件描述符.幸运的是,Linux允许您获取共享内存对象,因此不需要存储介质上的真实文件.
这是一个完整的示例,演示如何创建共享内存对象,从中创建读/写和只读指针,然后执行一些基本测试:
#include dio.h>
#include Failed\n");
return 0;
}
// Now get two pointers. One with read-write and one with read-only.
// These two pointers point to the same physical memory but will
// have different virtual addresses:
char * rw_data = mmap(0,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
char * ro_data = mmap(0,PROT_READ,0);
printf ("rw_data is mapped to address %p\n",rw_data);
printf ("ro_data is mapped to address %p\n",ro_data);
// ===================
// Simple test-bench:
// ===================
// try writing:
strcpy (rw_data,"hello world!");
if (strcmp (rw_data,"hello world!") == 0)
{
printf ("writing to rw_data test passed\n");
} else {
printf ("writing to rw_data test Failed\n");
}
// try reading from ro_data
if (strcmp (ro_data,"hello world!") == 0)
{
printf ("reading from ro_data test passed\n");
} else {
printf ("reading from ro_data test Failed\n");
}
printf ("now trying to write to ro_data. This should cause a segmentation fault\n");
// trigger the segfault
ro_data[0] = 1;
// if the process is still alive something didn't worked.
printf ("writing to ro_data test Failed\n");
return 0;
}
编译:gcc test.c -std = c99 -lrt
出于某种原因,我得到一个警告,没有声明ftruncate.不知道为什么.代码运行良好.示例输出:
file descriptor is 3
rw_data is mapped to address 0x7f1778d60000
ro_data is mapped to address 0x7f1778385000
writing to rw_data test passed
reading from ro_data test passed
now trying to write to ro_data. This should cause a segmentation fault
Segmentation fault
我把记忆释放作为读者的练习:-)