1 /*
2 * Copyright (C) 2011 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 ART_LIBARTBASE_BASE_UTILS_H_
18 #define ART_LIBARTBASE_BASE_UTILS_H_
19
20 #include <pthread.h>
21 #include <stdlib.h>
22
23 #include <random>
24 #include <string>
25
26 #include <android-base/logging.h>
27 #include <android-base/parseint.h>
28
29 #include "casts.h"
30 #include "globals.h"
31 #include "macros.h"
32 #include "pointer_size.h"
33
34 #if defined(__linux__)
35 #include <sys/utsname.h>
36 #endif
37
38 namespace art {
39
PointerToLowMemUInt32(const void * p)40 static inline uint32_t PointerToLowMemUInt32(const void* p) {
41 uintptr_t intp = reinterpret_cast<uintptr_t>(p);
42 DCHECK_LE(intp, 0xFFFFFFFFU);
43 return intp & 0xFFFFFFFFU;
44 }
45
46 // Returns a human-readable size string such as "1MB".
47 std::string PrettySize(uint64_t size_in_bytes);
48
49 // Splits a string using the given separator character into a vector of
50 // strings. Empty strings will be omitted.
51 template<typename StrIn, typename Str>
52 void Split(const StrIn& s, char separator, std::vector<Str>* out_result);
53
54 template<typename Str>
55 void Split(const Str& s, char separator, size_t len, Str* out_result);
56
57 template<typename StrIn, typename Str, size_t kLen>
Split(const StrIn & s,char separator,std::array<Str,kLen> * out_result)58 void Split(const StrIn& s, char separator, std::array<Str, kLen>* out_result) {
59 Split<Str>(Str(s), separator, kLen, &((*out_result)[0]));
60 }
61
62 // Returns the calling thread's tid. (The C libraries don't expose this.)
63 uint32_t GetTid();
64
65 // Returns the given thread's name.
66 std::string GetThreadName(pid_t tid);
67
68 // Sets the pthread name of the current thread. The name may be truncated to an
69 // implementation-defined limit.
70 void SetThreadName(const char* thread_name);
71
72 // Sets the pthread name of the given thread. The name may be truncated to an
73 // implementation-defined limit. Does nothing if not supported by the OS.
74 void SetThreadName(pthread_t thr, const char* thread_name);
75
76 // Reads data from "/proc/self/task/${tid}/stat".
77 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
78
79 class VoidFunctor {
80 public:
81 template <typename A>
operator()82 inline void operator()([[maybe_unused]] A a) const {}
83
84 template <typename A, typename B>
operator()85 inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b) const {}
86
87 template <typename A, typename B, typename C>
operator()88 inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b, [[maybe_unused]] C c) const {}
89 };
90
EntryPointToCodePointer(const void * entry_point)91 static inline const void* EntryPointToCodePointer(const void* entry_point) {
92 uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
93 // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
94 // least 2 byte aligned.
95 code &= ~0x1;
96 return reinterpret_cast<const void*>(code);
97 }
98
99 #if defined(__BIONIC__)
100 struct Arc4RandomGenerator {
101 using result_type = uint32_t;
minArc4RandomGenerator102 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator103 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator104 uint32_t operator() () { return arc4random(); }
105 };
106 using RNG = Arc4RandomGenerator;
107 #else
108 using RNG = std::random_device;
109 #endif
110
111 template <typename T>
GetRandomNumber(T min,T max)112 static T GetRandomNumber(T min, T max) {
113 CHECK_LT(min, max);
114 std::uniform_int_distribution<T> dist(min, max);
115 RNG rng;
116 return dist(rng);
117 }
118
119 // Sleep forever and never come back.
120 NO_RETURN void SleepForever();
121
122 // Flush CPU caches. Returns true on success, false if flush failed.
123 WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
124
125 #if defined(__linux__)
126 bool IsKernelVersionAtLeast(int reqd_major, int reqd_minor);
127 #endif
128
129 // On some old kernels, a cache operation may segfault.
130 WARN_UNUSED bool CacheOperationsMaySegFault();
131
132 // Is the execution environment on a virtual machine? See ART_TEST_ON_VM.
133 WARN_UNUSED bool RunningOnVM();
134
135 template <typename Func, typename... Args>
CheckedCall(const Func & function,const char * what,Args...args)136 static inline void CheckedCall(const Func& function, const char* what, Args... args) {
137 int rc = function(args...);
138 if (UNLIKELY(rc != 0)) {
139 PLOG(FATAL) << "Checked call failed for " << what;
140 }
141 }
142
143 // Forces the compiler to emit a load instruction, but discards the value.
144 // Useful when dealing with memory paging.
145 template <typename T>
ForceRead(const T * pointer)146 inline void ForceRead(const T* pointer) {
147 static_cast<void>(*const_cast<volatile T*>(pointer));
148 }
149
150 // Lookup value for a given key in /proc/self/status. Keys and values are separated by a ':' in
151 // the status file. Returns value found on success and "<unknown>" if the key is not found or
152 // there is an I/O error.
153 std::string GetProcessStatus(const char* key);
154
155 // Copy a prefix of /proc/tid/stat of the given length into buf. Return the number of bytes
156 // actually read, 0 on error.
157 size_t GetOsThreadStat(pid_t tid, char* buf, size_t len);
158
159 // Return a short prefix of /proc/tid/stat as quickly and robustly as possible. Used for debugging
160 // timing issues and possibly issues with /proc itself. Always atomic.
161 std::string GetOsThreadStatQuick(pid_t tid);
162
163 // Return a concatenation of the output of GetOsThreadStatQuick(tid) for all other tids.
164 // Less robust against concurrent change, but individual stat strings should still always
165 // be consistent. Called only when we are nearly certain to crash anyway.
166 std::string GetOtherThreadOsStats();
167
168 } // namespace art
169
170 #endif // ART_LIBARTBASE_BASE_UTILS_H_
171