Function region::protect

source ·
pub unsafe fn protect<T>(
    address: *const T,
    size: usize,
    protection: Protection
) -> Result<()>
Expand description

Changes the memory protection of one or more pages.

The address range may overlap one or more pages, and if so, all pages spanning the range will be modified. The previous protection flags are not preserved (if you desire to preserve the protection flags, use protect_with_handle).

§Parameters

  • The range is [address, address + size)
  • The address is rounded down to the closest page boundary.
  • The size may not be zero.
  • The size is rounded up to the closest page boundary, relative to the address.

§Errors

  • If an interaction with the underlying operating system fails, an error will be returned.
  • If size is zero, Error::InvalidParameter will be returned.

§Safety

This function can violate memory safety in a myriad of ways. Read-only memory can become writable, the executable properties of code segments can be removed, etc.

§Examples

  • Make an array of x86 assembly instructions executable.
use region::Protection;
let ret5 = [0xB8, 0x05, 0x00, 0x00, 0x00, 0xC3u8];

let x: extern "C" fn() -> i32 = unsafe {
  region::protect(ret5.as_ptr(), ret5.len(), region::Protection::READ_WRITE_EXECUTE)?;
  std::mem::transmute(ret5.as_ptr())
};

assert_eq!(x(), 5);