## mprotect The **mprotect()** function is used to change the access protection of a memory mapping to that specified by _protection_. All whole pages of the process's address space, that were established by the **mmap()** function, addressed from _addr_ continuing for a length of _len_ will be affected by the change of access protection. You may specify PROT_NONE, PROT_READ, PROT_WRITE, or the inclusive or of PROT_READ and PROT_WRITE as values for the _protect_ parameter. Upon successful completion, the **mprotect()** function returns 0. Upon failure, -1 is returned and errno is set to the appropriate error number. [ref]([mprotect()--Change Access Protection for Memory Mapping - IBM Documentation](https://www.ibm.com/docs/en/i/7.4?topic=ssw_ibm_i_74/apis/mprotect.html)) ---- After virtual memory is allocated by a process using `mmap`, `mprotect` can be used to set protection bits and define how different segments of this memory can be accessed. We can specify the following flags: 1. `PROT_WRITE` → On some hardware architectures (e.g., i386), **PROT_WRITE** implies **PROT_READ**. 2. `PROT_READ` → On some architectures, this implies that memory can be executed as well 3. `PROT_EXEC` → Implies that memory can be read and written as well 4. `PROT_NONE` → In this case the flag should be specified on its own. If nothing is, the memory is reserved but it cannot be read, written or executed. ```C int mprotect ((void *address, size_t length, int protection)) /** 0 on success and 1 on failure /** ``` A successful call to the `mprotect` function changes the protection flags of at least length bytes of memory, starting at address. The system page size is the granularity in which the page protection of anonymous memory mappings and most file mappings can be changed. ([Memory Protection (The GNU C Library)](https://www.gnu.org/software/libc/manual/html_node/Memory-Protection.html#index-mprotect)) We cannot do `mrpotect()` on a memory address that is being used by any other process. This is because `mprotect()` takes an address from a space available to the current process' allocated virtual address space. ---- ### Sources 1. [Memory Protection - man pages]([Memory Protection (The GNU C Library)](https://www.gnu.org/software/libc/manual/html_node/Memory-Protection.html))