1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! mlock / munlock

#![cfg(feature = "use_os")]


/// Cross-platform `mlock`.
///
/// * Unix `mlock`.
/// * Windows `VirtualLock`.
pub unsafe fn mlock(addr: *mut u8, len: usize) -> bool {
    #[cfg(unix)] {
        #[cfg(target_os = "linux")]
        libc::madvise(addr as *mut libc::c_void, len, libc::MADV_DONTDUMP);

        #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
        libc::madvise(addr as *mut libc::c_void, len, libc::MADV_NOCORE);

        libc::mlock(addr as *mut libc::c_void, len) == 0
    }

    #[cfg(windows)] {
        winapi::um::memoryapi::VirtualLock(
            addr as winapi::shared::minwindef::LPVOID,
            len as winapi::shared::basetsd::SIZE_T
        ) != 0
    }
}

/// Cross-platform `munlock`.
///
/// * Unix `munlock`.
/// * Windows `VirtualUnlock`.
pub unsafe fn munlock(addr: *mut u8, len: usize) -> bool {
    crate::memzero(addr, len);

    #[cfg(unix)] {
        #[cfg(target_os = "linux")]
        libc::madvise(addr as *mut libc::c_void, len, libc::MADV_DODUMP);

        #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
        libc::madvise(addr as *mut libc::c_void, len, libc::MADV_CORE);

        libc::munlock(addr as *mut libc::c_void, len) == 0
    }

    #[cfg(windows)] {
        winapi::um::memoryapi::VirtualUnlock(
            addr as winapi::shared::minwindef::LPVOID,
            len as winapi::shared::basetsd::SIZE_T
        ) != 0
    }
}