#[cfg(windows)]
fn main() -> std::io::Result<()> {
use std::io;
use std::thread;
use std::time::Duration;
let previous_error_mode: io::Result<u32> =
os_memlock::suppress_windows_error_dialogs_for_process();
match &previous_error_mode {
Ok(prev) => println!("Windows error mode adjusted; previous mode: 0x{prev:08x}"),
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
println!(
"suppress_windows_error_dialogs_for_process is unsupported on this platform/build"
)
}
Err(e) => eprintln!("Failed to set Windows error mode: {e}"),
}
const PAGE_LEN: usize = 4096;
let mut secret = vec![0u8; PAGE_LEN];
secret[..16].copy_from_slice(b"super-secret-data");
let ptr = secret.as_ptr() as *const std::os::raw::c_void;
let len = secret.len();
println!("Attempting to mlock {} bytes at {:p}", len, ptr);
match unsafe { os_memlock::mlock(ptr, len) } {
Ok(()) => println!("mlock (VirtualLock) succeeded"),
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
println!("mlock is unsupported on this platform/build; continuing without page-lock")
}
Err(e) => return Err(e),
}
println!("Working with secret data (simulated)...");
thread::sleep(Duration::from_millis(250));
match unsafe { os_memlock::munlock(ptr, len) } {
Ok(()) => println!("munlock (VirtualUnlock) succeeded"),
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
println!("munlock unsupported (no-op for this platform/build)")
}
Err(e) => return Err(e),
}
for b in &mut secret {
*b = 0;
}
println!("Secret zeroized.");
if let Ok(prev) = previous_error_mode {
match os_memlock::set_windows_error_mode(prev) {
Ok(_old) => println!("Windows error mode restored to 0x{prev:08x}"),
Err(e) => eprintln!("Failed to restore Windows error mode: {e}"),
}
}
println!("Windows example complete.");
Ok(())
}
#[cfg(not(windows))]
fn main() {
println!("This example is Windows-specific. Build and run it on Windows.");
}