From a41ba2f0bfc4fce1ce8f06a9c289102c440c929d Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Thu, 21 Mar 2013 20:02:35 -0700 Subject: [PATCH] Fix pthread_setname_np's behavior on invalid pthread_ts. Change-Id: I0a154beaab4d164ac812f2564d12e4d79b80a8e8 --- libc/bionic/pthread_setname_np.cpp | 22 +++++++++++++++------- tests/pthread_test.cpp | 2 +- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/libc/bionic/pthread_setname_np.cpp b/libc/bionic/pthread_setname_np.cpp index 6162aea68..e0ecace0b 100644 --- a/libc/bionic/pthread_setname_np.cpp +++ b/libc/bionic/pthread_setname_np.cpp @@ -35,6 +35,7 @@ #include #include +#include "pthread_accessor.h" #include "pthread_internal.h" #include "private/ErrnoRestorer.h" @@ -42,10 +43,10 @@ #define MAX_TASK_COMM_LEN 16 #define TASK_COMM_FMT "/proc/self/task/%d/comm" -int pthread_setname_np(pthread_t thread, const char* thread_name) { +int pthread_setname_np(pthread_t t, const char* thread_name) { ErrnoRestorer errno_restorer; - if (thread == 0 || thread_name == NULL) { + if (thread_name == NULL) { return EINVAL; } @@ -55,14 +56,21 @@ int pthread_setname_np(pthread_t thread, const char* thread_name) { } // Changing our own name is an easy special case. - if (thread == pthread_self()) { + if (t == pthread_self()) { return prctl(PR_SET_NAME, thread_name) ? errno : 0; } - // Have to change another thread's name. - pthread_internal_t* t = reinterpret_cast(thread); + // We have to change another thread's name. + pid_t tid = 0; + { + pthread_accessor thread(t); + if (thread.get() == NULL) { + return ESRCH; + } + tid = thread->tid; + } char comm_name[sizeof(TASK_COMM_FMT) + 8]; - snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, t->tid); + snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, tid); int fd = open(comm_name, O_WRONLY); if (fd == -1) { return errno; @@ -72,7 +80,7 @@ int pthread_setname_np(pthread_t thread, const char* thread_name) { if (n < 0) { return errno; - } else if ((size_t)n != thread_name_len) { + } else if (n != static_cast(thread_name_len)) { return EIO; } return 0; diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp index 98bc4e5a5..a86cadc6b 100644 --- a/tests/pthread_test.cpp +++ b/tests/pthread_test.cpp @@ -239,7 +239,7 @@ TEST(pthread, pthread_setname_np__no_such_thread) { MakeDeadThread(dead_thread); // Call pthread_setname_np after thread has already exited. - ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3")); + ASSERT_EQ(ESRCH, pthread_setname_np(dead_thread, "short 3")); } #endif