Skip to content

Commit 94dbad2

Browse files
committed
add mman::mprotect
1 parent 1b98979 commit 94dbad2

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
@@ -23,6 +23,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
2323
([#1010](https://github.com/nix-rust/nix/pull/1010))
2424
- Added `nix::sys::signal::signal`.
2525
([#817](https://github.com/nix-rust/nix/pull/817))
26+
- Added an `mprotect` wrapper.
27+
([#991](https://github.com/nix-rust/nix/pull/991))
2628

2729
### Changed
2830
### Fixed

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)