simple/
simple.rs

1/*!
2Simple example demonstrating usage of the `os-memlock` crate.
3
4Build & run (from workspace root):
5
6    cargo run -p os-memlock --example simple --features locked-memory
7
8Notes:
9- This example shows the minimal unsafe calls and handles the "unsupported" case
10  gracefully (the crate intentionally returns `io::ErrorKind::Unsupported` when
11  the platform or build configuration does not provide the underlying syscalls).
12- The functions here are unsafe; callers must uphold the safety contract documented
13  in the crate README (valid pointer/length, region remains mapped, etc).
14*/
15
16use std::io;
17use std::thread;
18use std::time::Duration;
19
20fn main() -> io::Result<()> {
21    // Simple buffer representing secret data. Use a page-sized allocation for clarity.
22    // On many systems a page is 4096 bytes; this example uses that common size.
23    const PAGE_LEN: usize = 4096;
24    let mut secret = vec![0u8; PAGE_LEN];
25
26    // Put some dummy secret bytes (for demo only).
27    secret[..16].copy_from_slice(b"super-secret-data");
28
29    let ptr = secret.as_ptr() as *const std::os::raw::c_void;
30
31    let len = secret.len();
32
33    println!("Attempting to lock {} bytes at {:p}", len, ptr);
34
35    // Try to mlock the buffer. This is unsafe and may return Unsupported on some builds/platforms.
36    match unsafe { os_memlock::mlock(ptr, len) } {
37        Ok(()) => println!("mlock succeeded"),
38        Err(e) if e.kind() == io::ErrorKind::Unsupported => {
39            println!("mlock is unsupported on this platform/build; continuing without page-lock")
40        }
41        Err(e) => return Err(e),
42    }
43
44    // Best-effort: on Linux and FreeBSD, advise the kernel not to include the mapping in core dumps.
45    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
46    {
47        let mut_ptr = secret.as_mut_ptr() as *mut std::os::raw::c_void;
48        match unsafe { os_memlock::madvise_dontdump(mut_ptr, len) } {
49            Ok(()) => println!("madvise dump-exclusion hint applied"),
50            Err(e) if e.kind() == io::ErrorKind::Unsupported => {
51                println!("madvise dump-exclusion hint unsupported on this platform/build")
52            }
53            Err(e) => eprintln!("madvise failed: {:#}", e),
54        }
55    }
56
57    // Do some work while memory is (hopefully) locked.
58    println!("Working with secret data (simulated)...");
59    // Sleep briefly to simulate lifetime of locked secret. (In real code avoid sleeping.)
60    thread::sleep(Duration::from_millis(250));
61
62    // Before dropping or unmapping the buffer, munlock.
63    match unsafe { os_memlock::munlock(ptr, len) } {
64        Ok(()) => println!("munlock succeeded"),
65        Err(e) if e.kind() == io::ErrorKind::Unsupported => {
66            println!("munlock unsupported (no-op for this platform/build)")
67        }
68        Err(e) => return Err(e),
69    }
70
71    // Zeroize secret before drop as a good hygiene (example only; use a proper zeroize crate in production).
72    for b in &mut secret {
73        *b = 0;
74    }
75
76    println!("Secret zeroized and example complete.");
77    Ok(())
78}