linux – 只写映射O_WRONLY打开的文件应该工作吗?

mmap()是否应该能够创建O_WRONLY打开文件的只写映射?

我问,因为在Linux 4.0.4 x86-64系统上失败了(strace log):

mkdir("test",0700)          = 0
open("test/foo",O_WRONLY|O_CREAT,0666) = 3
ftruncate(3,11)                        = 0
mmap(NULL,11,PROT_WRITE,MAP_SHARED,3,0) = -1 EACCES (Permission denied)

errno等于EACCESS.

用O_RDWR替换open-flag O_WRONLY会产生成功的映射.

Linux mmap手册页将errno记录为:

06001

因此,用第二句记录了这种行为.

但它背后的原因是什么?

是POSIX允许的吗?

它是内核还是库限制? (快速浏览一下,我在Linux / mm / mmap.c中找不到任何明显的东西)

解决方法

编辑

IEEE Std 1003.1,2004 Edition (POSIX.1 2004)似乎禁止它.

An implementation may permit accesses other than those specified by prot; however,if the Memory Protection option is supported,the implementation shall not permit a write to succeed where PROT_WRITE has not been set or shall not permit any access where PROT_NONE alone has been set. The implementation shall support at least the following values of prot: PROT_NONE,PROT_READ,PROT_WRITE,and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. If the Memory Protection option is not supported,the result of any access that conflicts with the specified protection is undefined. The file descriptor fildes shall have been opened with read permission,regardless of the protection options specified. If PROT_WRITE is specified,the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is specified in the flags parameter as described below.

(重点补充)

此外,在x86上,不可能具有只写内存,这是页表条目的限制.页面可以标记为只读或读写,并且可以是可执行的或不可执行的,但不能是只写的.此外,mprotect()的手册页说:

Whether PROT_EXEC has any effect different from PROT_READ is architecture- and kernel version-dependent. On some hardware architectures (e.g.,i386),PROT_WRITE implies PROT_READ.

在这种情况下,您已经打开了一个没有读取权限的文件描述符,但mmap()将通过为您提供PROT_READ权限来绕过O_WRONLY.相反,它将完全拒绝EACCESS.

相关文章

在Linux系统中,设置ARP防火墙可以通过多种方法实现,包括使...
在Linux环境下,使用Jack2进行编译时,可以采取以下策略来提...
`getid`命令在Linux系统中用于获取当前进程的有效用户ID(EU...
在Linux环境下,codesign工具用于对代码进行签名,以确保其完...
Linux中的`tr`命令,其英文全称是“transform”,即转换的意...
Linux中的ARP防火墙是一种用于防止ARP欺骗攻击的安全措施,它...