Crate region [] [src]

A library for manipulating memory regions

This crate provides several functions for handling memory pages and regions. It is implemented using platform specific APIs. The library exposes both low and high level functionality for manipulating pages.

Not all OS specific quirks are abstracted away. For instance; some OSs enforce memory pages to be readable whilst other may prevent pages from becoming executable (i.e DEP).

Note: a region is a collection of one or more pages laying consecutively in memory, with the same properties.

Installation

This crate is on crates.io and can be used by adding region to your dependencies in your project's Cargo.toml.

[dependencies]
region = "0.3"

and this to your crate root:

extern crate region;

Examples

  • Cross-platform equivalents.

    let ret5 = [0xB8, 0x05, 0x00, 0x00, 0x00, 0xC3];
    
    // Page size
    let pz = region::page::size();
    
    // VirtualQuery | '/proc/self/maps'
    let q  = region::query(ret5.as_ptr())?;
    let qr = region::query_range(ret5.as_ptr(), ret5.len())?;
    
    // VirtualProtect | mprotect
    region::protect(ret5.as_ptr(), ret5.len(), Protection::ReadWriteExecute)?;
    
    // VirtualLock | mlock
    let guard = region::lock(ret5.as_ptr(), ret5.len())?;
  • Using View to retrieve and change the state of memory pages.

    let data = vec![0xFF; 100];
    let mut view = View::new(data.as_ptr(), data.len()).unwrap();
    
    // Change memory protection to Read | Write | Execute
    unsafe { view.set_prot(Protection::ReadWriteExecute).unwrap() };
    assert_eq!(view.get_prot(), Some(Protection::ReadWriteExecute));
    
    // Restore to the previous memory protection
    unsafe { view.set_prot(Access::Previous).unwrap() };
    assert_eq!(view.get_prot(), Some(Protection::ReadWrite));
    
    // Temporarily change memory protection
    unsafe {
        view.exec_with_prot(Protection::Read, || {
            // This would result in a memory violation
            // data[0] = 0xCC;
        }).unwrap();
    }
    
    // Lock the memory page(s) to RAM
    let _guard = view.lock().unwrap();

Modules

page

Page related functions.

Structs

LockGuard

An RAII implementation of a "scoped lock". When this structure is dropped (falls out of scope), the virtual lock will be unlocked.

Protection

Memory page protection constants.

Region

A descriptor for a memory region

View

A view aligned to page boundaries.

Enums

Access

View protection access.

Error

A collection of possible errors.

Functions

lock

Locks one or more memory regions to RAM.

protect

Changes the memory protection of one or more pages.

query

Queries the OS with an address, returning the region it resides within.

query_range

Queries the OS with a range, returning the regions it contains.

unlock

Unlocks one or more memory regions from RAM.

Type Definitions

Result

The result type used by this library.