Skip to content

Commit 3be83a2

Browse files
committed
sys::prctl: Adding set_addr_name.
to set a name for an `anonymous` region for Linux/Android.
1 parent 08e7849 commit 3be83a2

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/sys/prctl.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@ use crate::errno::Errno;
99
use crate::sys::signal::Signal;
1010
use crate::Result;
1111

12-
use libc::{c_int, c_ulong};
12+
use libc::{c_int, c_ulong, c_void};
1313
use std::convert::TryFrom;
1414
use std::ffi::{CStr, CString};
15+
use std::num::NonZeroUsize;
16+
use std::ptr::NonNull;
1517

1618
libc_enum! {
1719
/// The type of hardware memory corruption kill policy for the thread.
@@ -213,3 +215,10 @@ pub fn set_thp_disable(flag: bool) -> Result<()> {
213215
pub fn get_thp_disable() -> Result<bool> {
214216
prctl_get_bool(libc::PR_GET_THP_DISABLE)
215217
}
218+
219+
/// Set an identifier (or reset it) to the address memory range.
220+
pub fn set_addr_name(addr: NonNull<c_void>, length: NonZeroUsize, name: &CStr) -> Result<()> {
221+
let res = unsafe { libc::prctl(libc::PR_SET_VMA, libc::PR_SET_VMA_ANON_NAME, addr.as_ptr(), length, name.as_ptr()) };
222+
223+
Errno::result(res).map(drop)
224+
}

test/sys/test_prctl.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,41 @@ mod test_prctl {
122122

123123
prctl::set_thp_disable(original).unwrap();
124124
}
125+
126+
#[test]
127+
fn test_set_addr_name() {
128+
use nix::sys::mman;
129+
use std::num::NonZeroUsize;
130+
131+
const ONE_K: libc::size_t = 1024;
132+
let sz = NonZeroUsize::new(ONE_K).unwrap();
133+
let ptr = unsafe {
134+
mman::mmap_anonymous(
135+
None,
136+
sz,
137+
mman::ProtFlags::PROT_READ,
138+
mman::MapFlags::MAP_SHARED,
139+
)
140+
.unwrap()
141+
};
142+
// `CONFIG_ANON_VMA_NAME` kernel config might not be set
143+
prctl::set_addr_name(
144+
ptr,
145+
sz,
146+
CStr::from_bytes_with_nul(b"Nix\0").unwrap(),
147+
)
148+
.unwrap();
149+
prctl::set_addr_name(ptr, sz, unsafe {
150+
CStr::from_ptr(std::ptr::null())
151+
})
152+
.unwrap();
153+
assert_eq!(
154+
prctl::set_addr_name(
155+
ptr,
156+
sz,
157+
CStr::from_bytes_with_nul(b"[\0").unwrap()
158+
),
159+
Err(nix::Error::EINVAL)
160+
);
161+
}
125162
}

0 commit comments

Comments
 (0)