From 9752f152aefcca2432e29c78599abc511f7f689d Mon Sep 17 00:00:00 2001 From: Yoh Deadfall Date: Tue, 8 Oct 2024 00:56:34 +0300 Subject: [PATCH] Used write_c_str --- src/shims/unix/android/thread.rs | 19 ++++++++----------- tests/pass-dep/libc/threadname.rs | 7 ++++--- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/shims/unix/android/thread.rs b/src/shims/unix/android/thread.rs index d8d688c73c..9239267b16 100644 --- a/src/shims/unix/android/thread.rs +++ b/src/shims/unix/android/thread.rs @@ -1,5 +1,3 @@ -use std::iter; - use rustc_span::Symbol; use rustc_target::spec::abi::Abi; @@ -49,17 +47,16 @@ pub fn prctl<'tcx>( let thread = ThreadId::try_from(thread).unwrap(); // FIXME: we should use the program name if the thread name is not set - let name = this.get_thread_name(thread).unwrap_or(DEFAULT_THREAD_NAME).to_owned(); - let name_len = name.len().max(TASK_COMM_LEN - 1); + let mut name = this.get_thread_name(thread).unwrap_or(DEFAULT_THREAD_NAME).to_owned(); + let name_len = TASK_COMM_LEN - 1; - this.eval_context_mut().write_bytes_ptr( - name_out, - name.iter() - .take(name_len) - .copied() - .chain(iter::repeat_n(0u8, TASK_COMM_LEN.strict_sub(name_len))), - )?; + if name.len() >= name_len { + name.drain(name_len..); + } else { + name.resize(name_len, 0); + } + this.write_c_str(&name, name_out, TASK_COMM_LEN as u64)?; Scalar::from_u32(0) } op => { diff --git a/tests/pass-dep/libc/threadname.rs b/tests/pass-dep/libc/threadname.rs index f76eef679b..99b7713f51 100644 --- a/tests/pass-dep/libc/threadname.rs +++ b/tests/pass-dep/libc/threadname.rs @@ -59,7 +59,8 @@ fn main() { let result = thread::Builder::new().name(name.clone()).spawn(move || { assert_eq!(thread::current().name(), Some(name.as_str())); - let mut buf = vec![0u8; name.len() + 1]; + // POSIX seems to promise at least 15 chars excluding a null terminator. + let mut buf = vec![0u8; 16]; assert_eq!(get_thread_name(&mut buf), 0); let cstr = CStr::from_bytes_until_nul(&buf).unwrap(); if name.len() >= 15 { @@ -67,7 +68,7 @@ fn main() { cstr.to_bytes().len() >= 15, "name is too short: len={}", cstr.to_bytes().len() - ); // POSIX seems to promise at least 15 chars + ); assert!(name.as_bytes().starts_with(cstr.to_bytes())); } else { assert_eq!(name.as_bytes(), cstr.to_bytes()); @@ -80,7 +81,7 @@ fn main() { // But with a too long name it should fail except: // * on FreeBSD where the function has no return, hence cannot indicate failure, // * on Android where prctl silently truncates the string. - #[cfg(not(all(target_os = "freebsd", target_os = "android")))] + #[cfg(not(any(target_os = "freebsd", target_os = "android")))] assert_ne!(set_thread_name(&std::ffi::CString::new(name).unwrap()), 0); } });