From b9e8e99198a7446a72f65c209a1b1ba3445af276 Mon Sep 17 00:00:00 2001
From: David Carlier <devnexen@gmail.com>
Date: Tue, 6 Aug 2024 19:40:42 +0100
Subject: [PATCH] std::thread: set_name implementation proposal for vxWorks.

---
 library/std/src/sys/pal/unix/thread.rs | 33 +++++++++++++++++++++++---
 1 file changed, 30 insertions(+), 3 deletions(-)

diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs
index 44cb7b7b7ce5b..7d29d9a517210 100644
--- a/library/std/src/sys/pal/unix/thread.rs
+++ b/library/std/src/sys/pal/unix/thread.rs
@@ -3,7 +3,12 @@ use crate::mem::{self, ManuallyDrop};
 use crate::num::NonZero;
 #[cfg(all(target_os = "linux", target_env = "gnu"))]
 use crate::sys::weak::dlsym;
-#[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))]
+#[cfg(any(
+    target_os = "solaris",
+    target_os = "illumos",
+    target_os = "nto",
+    target_os = "vxworks"
+))]
 use crate::sys::weak::weak;
 use crate::sys::{os, stack_overflow};
 use crate::time::Duration;
@@ -212,17 +217,38 @@ impl Thread {
         }
     }
 
+    #[cfg(target_os = "vxworks")]
+    pub fn set_name(name: &CStr) {
+        // FIXME(libc): adding real STATUS, ERROR type eventually.
+        weak! {
+            fn taskNameSet(
+                libc::TASK_ID, *mut libc::c_char
+            ) -> libc::c_int
+        }
+
+        // We can't assume taskNameSet is necessarily available.
+        // VX_TASK_NAME_LEN can be found set to 31,
+        // however older versions can be set to only 10.
+        // FIXME(vxworks): if the minimum supported VxWorks is >= 7, the maximum length can be changed to 31.
+        if let Some(f) = taskNameSet.get() {
+            const VX_TASK_NAME_LEN: usize = 10;
+
+            let name = truncate_cstr::<{ VX_TASK_NAME_LEN }>(name);
+            let status = unsafe { f(libc::taskIdSelf(), name.as_mut_ptr()) };
+            debug_assert_eq!(res, libc::OK);
+        }
+    }
+
     #[cfg(any(
         target_env = "newlib",
         target_os = "l4re",
         target_os = "emscripten",
         target_os = "redox",
-        target_os = "vxworks",
         target_os = "hurd",
         target_os = "aix",
     ))]
     pub fn set_name(_name: &CStr) {
-        // Newlib, Emscripten, and VxWorks have no way to set a thread name.
+        // Newlib and Emscripten have no way to set a thread name.
     }
 
     #[cfg(not(target_os = "espidf"))]
@@ -291,6 +317,7 @@ impl Drop for Thread {
     target_os = "nto",
     target_os = "solaris",
     target_os = "illumos",
+    target_os = "vxworks",
     target_vendor = "apple",
 ))]
 fn truncate_cstr<const MAX_WITH_NUL: usize>(cstr: &CStr) -> [libc::c_char; MAX_WITH_NUL] {