Behaviour of PROT_READ and PROT_WRITE with mprotect

前端 未结 2 1485
梦如初夏
梦如初夏 2020-12-18 01:30

I\'ve been trying to use mprotect against reading first, and then writing.

Is here my code

#include 
#include 

        
2条回答
  •  温柔的废话
    2020-12-18 01:41

    Most operating systems and/or cpu architectures automatically make something readable when it writeable, so PROT_WRITE most often implies PROT_READ as well. It's simply not possible to make something writeable without making it readable. The reasons can be speculated on, either it's not worth the effort to make an additional readability bit in the MMU and caches, or as it was on some earlier architectures, you actually need to read through the MMU into a cache before you can write, so making something unreadable automatically makes it unwriteable.

    Also, it's likely that printf tries to allocate from memory that you damaged with mprotect. You want to allocate a full page from libc when you're changing its protection, otherwise you'll be changing the protection of a page that you don't own fully and libc doesn't expect it to be protected. On your MacOS test with PROT_READ this is what happens. printf allocates some internal structures, tries to access them and crashes when they are read only.

提交回复
热议问题