port: Add pthread_setname_np FreeBSD compat
[lttng-tools.git] / src / common / compat / pthread.h
1 /*
2 * Copyright (C) 2020 Michael Jeanson <mjeanson@efficios.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 */
7
8 #ifndef _COMPAT_PTHREAD_H
9 #define _COMPAT_PTHREAD_H
10
11 #include <pthread.h>
12 #include <common/compat/errno.h>
13 #include <string.h>
14
15 #define LTTNG_PTHREAD_NAMELEN 16
16
17 #if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
18 static inline
19 int lttng_pthread_setname_np(const char *name)
20 {
21 /*
22 * Some implementations don't error out, replicate this behavior for
23 * consistency.
24 */
25 if (strnlen(name, LTTNG_PTHREAD_NAMELEN) >= LTTNG_PTHREAD_NAMELEN) {
26 return ERANGE;
27 }
28
29 return pthread_setname_np(pthread_self(), name);
30 }
31
32 static inline
33 int lttng_pthread_getname_np(char *name, size_t len)
34 {
35 return pthread_getname_np(pthread_self(), name, len);
36 }
37 #elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
38 static inline
39 int lttng_pthread_setname_np(const char *name)
40 {
41 return pthread_setname_np(name);
42 }
43
44 static inline
45 int lttng_pthread_getname_np(char *name, size_t len)
46 {
47 return pthread_getname_np(name, len);
48 }
49 #elif defined(HAVE_PTHREAD_SET_NAME_NP_WITH_TID)
50
51 #include <pthread_np.h>
52 static inline
53 int lttng_pthread_setname_np(const char *name)
54 {
55 /* Replicate pthread_setname_np's behavior. */
56 if (strnlen(name, LTTNG_PTHREAD_NAMELEN) >= LTTNG_PTHREAD_NAMELEN) {
57 return ERANGE;
58 }
59
60 pthread_set_name_np(pthread_self(), name);
61 return 0;
62 }
63
64 static inline
65 int lttng_pthread_getname_np(char *name, size_t len)
66 {
67 pthread_get_name_np(pthread_self(), name, len);
68 return 0;
69 }
70 #elif defined(__linux__)
71
72 /* Fallback on prtctl on Linux */
73 #include <sys/prctl.h>
74
75 static inline
76 int lttng_pthread_setname_np(const char *name)
77 {
78 /* Replicate pthread_setname_np's behavior. */
79 if (strnlen(name, LTTNG_UST_ABI_PROCNAME_LEN) >= LTTNG_UST_ABI_PROCNAME_LEN) {
80 return ERANGE;
81 }
82 return prctl(PR_SET_NAME, name, 0, 0, 0);
83 }
84
85 static inline
86 int lttng_pthread_getname_np(char *name, size_t len)
87 {
88 return prctl(PR_GET_NAME, name, 0, 0, 0);
89 }
90 #else
91 /*
92 * For platforms without thread name support, do nothing.
93 */
94 static inline
95 int lttng_pthread_setname_np(const char *name)
96 {
97 return -ENOSYS;
98 }
99
100 static inline
101 int lttng_pthread_getname_np(char *name, size_t len)
102 {
103 return -ENOSYS;
104 }
105 #endif
106
107 #endif /* _COMPAT_PTHREAD_H */
This page took 0.042878 seconds and 4 git commands to generate.