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
24 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
25 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
26 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
27 #include <pthread.h>
28 #include <string.h>
29 #include <algorithm>
30 #endif
31
32 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
33 #include <sys/prctl.h>
34 #endif
35
36 // Internal implementation utils that aren't as widely useful/supported as
37 // base/thread_utils.h.
38
39 namespace perfetto {
40 namespace base {
41
42 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
43 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
44 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
45 // Sets the "comm" of the calling thread to the first 15 chars of the given
46 // string.
MaybeSetThreadName(const std::string & name)47 inline bool MaybeSetThreadName(const std::string& name) {
48 char buf[16] = {};
49 size_t sz = std::min(name.size(), static_cast<size_t>(15));
50 strncpy(buf, name.c_str(), sz);
51
52 #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
53 return pthread_setname_np(buf) == 0;
54 #else
55 return pthread_setname_np(pthread_self(), buf) == 0;
56 #endif
57 }
58
GetThreadName(std::string & out_result)59 inline bool GetThreadName(std::string& out_result) {
60 char buf[16] = {};
61 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
62 if (prctl(PR_GET_NAME, buf) != 0)
63 return false;
64 #else
65 if (pthread_getname_np(pthread_self(), buf, sizeof(buf)) != 0)
66 return false;
67 #endif
68 out_result = std::string(buf);
69 return true;
70 }
71
72 #else
73 inline bool MaybeSetThreadName(const std::string&) {
74 return false;
75 }
76 inline bool GetThreadName(std::string&) {
77 return false;
78 }
79 #endif
80
81 } // namespace base
82 } // namespace perfetto
83
84 #endif // INCLUDE_PERFETTO_EXT_BASE_THREAD_UTILS_H_
85