C / Linux:具有不同权限的双映射内存

前端之家收集整理的这篇文章主要介绍了C / Linux:具有不同权限的双映射内存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的程序将数据指针传递给第三方插件,意图数据应该是只读的,因此阻止插件写入数据对象会很好.理想情况下,如果插件尝试写入,则会出现段错误.我听说有一些方法可以对内存区域进行双重映射,这样第二个虚拟地址范围就指向相同的物理内存页面.第二个映射没有写入权限,导出的指针将使用此地址范围而不是原始(可写)地址范围.我宁愿不更改原始内存分配,无论它们是否碰巧使用malloc或mmap或其他.有人可以解释如何做到这一点?

最佳答案
可以获得双映射,但它需要一些工作.@H_404_6@

我知道如何创建这种双映射的唯一方法是使用mmap函数调用.对于mmap,您需要某种文件描述符.幸运的是,Linux允许您获取共享内存对象,因此不需要存储介质上的真实文件.@H_404_6@

这是一个完整的示例,演示如何创建共享内存对象,从中创建读/写和只读指针,然后执行一些基本测试:@H_404_6@

@H_404_6@

#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@H_404_6@

出于某种原因,我得到一个警告,没有声明ftruncate.不知道为什么.代码运行良好.示例输出:@H_404_6@

@H_404_6@

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

我把记忆释放作为读者的练习:-)

原文链接:https://www.f2er.com/c/440951.html

猜你在找的C&C++相关文章