Skip to content

Commit 0d20c37

Browse files
committed
add mman::mprotect
1 parent c2923ea commit 0d20c37

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
1414
- Added `symlinkat` wrapper.
1515
([#997](https://github.com/nix-rust/nix/pull/997))
1616

17+
- Added an `mprotect` wrapper.
18+
([#991](https://github.com/nix-rust/nix/pull/991))
1719
### Changed
1820
### Fixed
1921
### Removed

src/sys/mman.rs

+29
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,35 @@ pub unsafe fn madvise(addr: *mut c_void, length: size_t, advise: MmapAdvise) ->
258258
Errno::result(libc::madvise(addr, length, advise as i32)).map(drop)
259259
}
260260

261+
/// Set protection of memory mapping.
262+
///
263+
/// See [`mprotect(3)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mprotect.html) for
264+
/// details.
265+
///
266+
/// # Safety
267+
///
268+
/// Calls to `mprotect` are inherently unsafe, as changes to memory protections can lead to
269+
/// SIGSEGVs.
270+
///
271+
/// ```
272+
/// # use nix::libc::size_t;
273+
/// # use nix::sys::mman::{mmap, mprotect, MapFlags, ProtFlags};
274+
/// # use std::ptr;
275+
/// const ONE_K: size_t = 1024;
276+
/// let mut slice: &mut [u8] = unsafe {
277+
/// let mem = mmap(ptr::null_mut(), ONE_K, ProtFlags::PROT_NONE,
278+
/// MapFlags::MAP_ANON | MapFlags::MAP_PRIVATE, -1, 0).unwrap();
279+
/// mprotect(mem, ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE).unwrap();
280+
/// std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K)
281+
/// };
282+
/// assert_eq!(slice[0], 0x00);
283+
/// slice[0] = 0xFF;
284+
/// assert_eq!(slice[0], 0xFF);
285+
/// ```
286+
pub unsafe fn mprotect(addr: *mut c_void, length: size_t, prot: ProtFlags) -> Result<()> {
287+
Errno::result(libc::mprotect(addr, length, prot.bits())).map(drop)
288+
}
289+
261290
pub unsafe fn msync(addr: *mut c_void, length: size_t, flags: MsFlags) -> Result<()> {
262291
Errno::result(libc::msync(addr, length, flags.bits())).map(drop)
263292
}

0 commit comments

Comments
 (0)