1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_
19
20 #include <string>
21
22 #include "perfetto/base/build_config.h"
23 #include "perfetto/ext/base/string_utils.h"
24 #include "perfetto/base/export.h"
25
26 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
27 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
28 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
29 #include <pthread.h>
30 #include <string.h>
31 #include <algorithm>
32 #endif
33
34 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
35 #include <sys/prctl.h>
36 #endif
37
38 // Internal implementation utils that aren't as widely useful/supported as
39 // base/thread_utils.h.
40
41 namespace perfetto {
42 namespace base {
43
44 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
45 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
46 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
47 // Sets the "comm" of the calling thread to the first 15 chars of the given
48 // string.
MaybeSetThreadName(const std::string & name)49 inline bool MaybeSetThreadName(const std::string& name) {
50 char buf[16] = {};
51 StringCopy(buf, name.c_str(), sizeof(buf));
52
53 #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
54 return pthread_setname_np(buf) == 0;
55 #else
56 return pthread_setname_np(pthread_self(), buf) == 0;
57 #endif
58 }
59
GetThreadName(std::string & out_result)60 inline bool GetThreadName(std::string& out_result) {
61 char buf[16] = {};
62 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
63 if (prctl(PR_GET_NAME, buf) != 0)
64 return false;
65 #else
66 if (pthread_getname_np(pthread_self(), buf, sizeof(buf)) != 0)
67 return false;
68 #endif
69 out_result = std::string(buf);
70 return true;
71 }
72
73 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
74
75 PERFETTO_EXPORT_COMPONENT bool MaybeSetThreadName(const std::string& name);
76 PERFETTO_EXPORT_COMPONENT bool GetThreadName(std::string& out_result);
77
78 #else
79 inline bool MaybeSetThreadName(const std::string&) {
80 return false;
81 }
82 inline bool GetThreadName(std::string&) {
83 return false;
84 }
85 #endif
86
87 } // namespace base
88 } // namespace perfetto
89
90 #endif // INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_
91