diff --git a/src/sys/prctl.rs b/src/sys/prctl.rs index 42324beab2..1946bdf046 100644 --- a/src/sys/prctl.rs +++ b/src/sys/prctl.rs @@ -9,9 +9,11 @@ use crate::errno::Errno; use crate::sys::signal::Signal; use crate::Result; -use libc::{c_int, c_ulong}; +use libc::{c_int, c_ulong, c_void}; use std::convert::TryFrom; use std::ffi::{CStr, CString}; +use std::num::NonZeroUsize; +use std::ptr::NonNull; libc_enum! { /// The type of hardware memory corruption kill policy for the thread. @@ -213,3 +215,10 @@ pub fn set_thp_disable(flag: bool) -> Result<()> { pub fn get_thp_disable() -> Result { prctl_get_bool(libc::PR_GET_THP_DISABLE) } + +/// Set an identifier (or reset it) to the address memory range. +pub fn set_addr_name(addr: NonNull, length: NonZeroUsize, name: &CStr) -> Result<()> { + let res = unsafe { libc::prctl(libc::PR_SET_VMA, libc::PR_SET_VMA_ANON_NAME, addr.as_ptr(), length, name.as_ptr()) }; + + Errno::result(res).map(drop) +} diff --git a/test/sys/test_prctl.rs b/test/sys/test_prctl.rs index 351213b7ef..000d87df81 100644 --- a/test/sys/test_prctl.rs +++ b/test/sys/test_prctl.rs @@ -122,4 +122,41 @@ mod test_prctl { prctl::set_thp_disable(original).unwrap(); } + + #[test] + fn test_set_addr_map() { + use nix::sys::mman; + use std::num::NonZeroUsize; + + const ONE_K: libc::size_t = 1024; + let sz = NonZeroUsize::new(ONE_K).unwrap(); + let ptr = unsafe { + mman::mmap_anonymous( + None, + sz, + mman::ProtFlags::PROT_READ, + mman::MapFlags::MAP_SHARED, + ) + .unwrap() + }; + // `CONFIG_ANON_VMA_NAME` kernel config might not be set + prctl::set_addr_name( + ptr, + sz, + CStr::from_bytes_with_nul(b"Nix\0").unwrap(), + ) + .unwrap(); + prctl::set_addr_name(ptr, sz, unsafe { + CStr::from_ptr(std::ptr::null()) + }) + .unwrap(); + assert_eq!( + prctl::set_addr_name( + ptr, + sz, + CStr::from_bytes_with_nul(b"[wrong\0").unwrap() + ), + Err(nix::Error::EINVAL) + ); + } }