Skip to content

Commit

Permalink
Change get/set name to CStrings
Browse files Browse the repository at this point in the history
  • Loading branch information
DOhlsson committed Nov 5, 2022
1 parent c3a8f30 commit 03b5a03
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
9 changes: 3 additions & 6 deletions src/sys/prctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,24 +138,21 @@ pub fn get_pdeathsig() -> Result<Option<Signal>> {
}

/// Set the name of the calling thread. Strings longer than 15 bytes will be truncated.
pub fn set_name(name: &str) -> Result<()> {
let name = CString::new(name.as_bytes()).unwrap();

pub fn set_name(name: &CStr) -> Result<()> {
let res = unsafe { libc::prctl(libc::PR_SET_NAME, name.as_ptr(), 0, 0, 0) };

Errno::result(res).map(drop)
}

/// Return the name of the calling thread
pub fn get_name() -> Result<String> {
pub fn get_name() -> Result<CString> {
// Size of buffer determined by linux/sched.h TASK_COMM_LEN
let buf = [0u8; 16];

let res = unsafe { libc::prctl(libc::PR_GET_NAME, &buf, 0, 0, 0) };

let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
let cstr = CStr::from_bytes_with_nul(&buf[..=len]).map_err(|_| Errno::EINVAL)?;
let name = cstr.to_str().map_err(|_| Errno::EINVAL)?;
let name = CStr::from_bytes_with_nul(&buf[..=len]).map_err(|_| Errno::EINVAL)?;

Errno::result(res).map(|_| name.to_owned())
}
Expand Down
14 changes: 8 additions & 6 deletions test/sys/test_prctl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#[cfg(target_os = "linux")]
#[cfg(feature = "process")]
mod test_prctl {
use std::ffi::CStr;

use nix::sys::prctl;

#[cfg_attr(qemu, ignore)]
Expand Down Expand Up @@ -68,17 +70,17 @@ mod test_prctl {
fn test_get_set_name() {
let original = prctl::get_name().unwrap();

let long_name = String::from("0123456789abcdefghijklmn");
prctl::set_name(&long_name).unwrap();
let long_name = CStr::from_bytes_with_nul(b"0123456789abcdefghijklmn\0").unwrap();
prctl::set_name(long_name).unwrap();
let res = prctl::get_name().unwrap();

// name truncated by kernel to TASK_COMM_LEN
assert_eq!(&long_name[..15], res);
assert_eq!(&long_name.to_str().unwrap()[..15], res.to_str().unwrap());

let short_name = String::from("01234567");
prctl::set_name(&short_name).unwrap();
let short_name = CStr::from_bytes_with_nul(b"01234567\0").unwrap();
prctl::set_name(short_name).unwrap();
let res = prctl::get_name().unwrap();
assert_eq!(short_name, res);
assert_eq!(short_name.to_str().unwrap(), res.to_str().unwrap());

prctl::set_name(&original).unwrap();
}
Expand Down

0 comments on commit 03b5a03

Please sign in to comment.