blob: 88b86ec1f49f7952c5bf91489dae2a06a7eae8e6 [file] [log] [blame]
Elliott Hughes3e898472013-02-12 16:40:24 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <pthread.h>
30
31#include <fcntl.h>
32#include <stdio.h> // For snprintf.
33#include <sys/prctl.h>
34#include <sys/stat.h>
35#include <sys/types.h>
36#include <unistd.h>
37
38#include "pthread_internal.h"
39#include "private/ErrnoRestorer.h"
40
41// This value is not exported by kernel headers.
42#define MAX_TASK_COMM_LEN 16
43#define TASK_COMM_FMT "/proc/self/task/%u/comm"
44
45int pthread_setname_np(pthread_t thread, const char* thread_name) {
46 ErrnoRestorer errno_restorer;
47
48 if (thread == 0 || thread_name == NULL) {
49 return EINVAL;
50 }
51
52 size_t thread_name_len = strlen(thread_name);
53 if (thread_name_len >= MAX_TASK_COMM_LEN) {
54 return ERANGE;
55 }
56
57 // Changing our own name is an easy special case.
58 if (thread == pthread_self()) {
59 return prctl(PR_SET_NAME, (unsigned long)thread_name, 0, 0, 0) ? errno : 0;
60 }
61
62 // Have to change another thread's name.
63 pthread_internal_t* t = reinterpret_cast<pthread_internal_t*>(thread);
64 char comm_name[sizeof(TASK_COMM_FMT) + 8];
65 snprintf(comm_name, sizeof(comm_name), TASK_COMM_FMT, (unsigned int) t->kernel_id);
66 int fd = open(comm_name, O_RDWR);
67 if (fd == -1) {
68 return errno;
69 }
70 ssize_t n = TEMP_FAILURE_RETRY(write(fd, thread_name, thread_name_len));
71 close(fd);
72
73 if (n < 0) {
74 return errno;
75 } else if ((size_t)n != thread_name_len) {
76 return EIO;
77 }
78 return 0;
79}