Skip to content

Commit 15dcd6b

Browse files
authored
sys::prctl: Adding set_vma_anon_name. (#2378)
to set a name for an `anonymous` region for Linux/Android.
1 parent 0a566eb commit 15dcd6b

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

changelog/2378.added.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add prctl function `prctl_set_vma_anon_name` for Linux/Android.

src/sys/prctl.rs

Lines changed: 14 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,14 @@ 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_vma_anon_name(addr: NonNull<c_void>, length: NonZeroUsize, name: Option<&CStr>) -> Result<()> {
221+
let nameref = match name {
222+
Some(n) => n.as_ptr(),
223+
_ => std::ptr::null()
224+
};
225+
let res = unsafe { libc::prctl(libc::PR_SET_VMA, libc::PR_SET_VMA_ANON_NAME, addr.as_ptr(), length, nameref) };
226+
227+
Errno::result(res).map(drop)
228+
}

test/sys/test_prctl.rs

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

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

0 commit comments

Comments
 (0)