'Does mmap changes flags stored in the page table?

To the best of my knowledge,

MMAP can be used to change a protection of mapped memory region.

For example, If I want to add executable permission

to one of my stack page

which is originally set as readable and writable permission

because of the Data execution policy(DEP).

And this permission is reflected on the page table flags such as W/XD in x86 architecture.

So my question is If I change the permission of the specific page using the MMAP,

does it request the kernel change the page table flags?

and does it automatically flush the TLB?

Thanks.



Solution 1:[1]

TL;DR, In C/C++ mmap wraps a system call of the same name. It is used to map a new page-aligned memory to the address space of the caller process. It lazily modifies the page-table meaning it only adds an entry to the vm_area_struct when called. Later on, when you first access the returned memory, a page table modification happens as the result of a page fault. So it only modifies the page table on first access. So it is clear that to allocate new pages (which is what mmap does), their protection flags must be known to mmap.

So as mmap is used to map new memory pages, mprotect is used to modify the protection flags/bits of an already mapped memory. It also modifies the page table so the new protection is known by all threads/processes that share the memory.

As I mentioned before, mmap and mprotect are both system calls that are executed in kernel mode; due to security reasons, no user-space process can modify its page table.

Hope this short answer helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Siavashi