Skip to content

Commit

Permalink
sys::prctl: Adding set_addr_name.
Browse files Browse the repository at this point in the history
to set a name for an `anonymous` region for Linux/Android.
  • Loading branch information
devnexen committed Apr 20, 2024
1 parent 08e7849 commit 06d6429
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/sys/prctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -213,3 +215,10 @@ pub fn set_thp_disable(flag: bool) -> Result<()> {
pub fn get_thp_disable() -> Result<bool> {
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<c_void>, 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)
}
37 changes: 37 additions & 0 deletions test/sys/test_prctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
);
}
}

0 comments on commit 06d6429

Please sign in to comment.