• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
25 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) ||   \
26     PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
27     PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
28 #include <pthread.h>
29 #include <string.h>
30 #include <algorithm>
31 #endif
32 
33 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
34 #include <sys/prctl.h>
35 #endif
36 
37 // Internal implementation utils that aren't as widely useful/supported as
38 // base/thread_utils.h.
39 
40 namespace perfetto {
41 namespace base {
42 
43 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) ||   \
44     PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
45     PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
46 // Sets the "comm" of the calling thread to the first 15 chars of the given
47 // string.
MaybeSetThreadName(const std::string & name)48 inline bool MaybeSetThreadName(const std::string& name) {
49   char buf[16] = {};
50   StringCopy(buf, name.c_str(), sizeof(buf));
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