Skip to main content

agent_tools_interface/security/
memory.rs

1/// Secure memory helpers: mlock, madvise, zeroize.
2///
3/// These prevent secrets from being swapped to disk or included in core dumps.
4/// All functions are best-effort on non-Linux platforms.
5
6/// Lock a memory region to prevent it from being swapped to disk.
7/// Returns Ok(()) on success, Err with a warning message on failure.
8#[cfg(target_os = "linux")]
9pub fn mlock(ptr: *const u8, len: usize) -> Result<(), String> {
10    let ret = unsafe { libc::mlock(ptr as *const libc::c_void, len) };
11    if ret == 0 {
12        Ok(())
13    } else {
14        Err(format!(
15            "mlock failed (errno {}): secrets may be swappable",
16            std::io::Error::last_os_error()
17        ))
18    }
19}
20
21#[cfg(not(target_os = "linux"))]
22pub fn mlock(_ptr: *const u8, _len: usize) -> Result<(), String> {
23    // mlock is not critical on non-Linux; warn and continue
24    Ok(())
25}
26
27/// Advise the kernel to exclude this memory from core dumps.
28#[cfg(target_os = "linux")]
29pub fn madvise_dontdump(ptr: *const u8, len: usize) -> Result<(), String> {
30    let ret = unsafe { libc::madvise(ptr as *mut libc::c_void, len, libc::MADV_DONTDUMP) };
31    if ret == 0 {
32        Ok(())
33    } else {
34        Err(format!(
35            "madvise(DONTDUMP) failed: secrets may appear in core dumps"
36        ))
37    }
38}
39
40#[cfg(not(target_os = "linux"))]
41pub fn madvise_dontdump(_ptr: *const u8, _len: usize) -> Result<(), String> {
42    Ok(())
43}
44
45/// Unlock a previously locked memory region.
46#[cfg(target_os = "linux")]
47pub fn munlock(ptr: *const u8, len: usize) {
48    unsafe {
49        libc::munlock(ptr as *const libc::c_void, len);
50    }
51}
52
53#[cfg(not(target_os = "linux"))]
54pub fn munlock(_ptr: *const u8, _len: usize) {}