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 "enums.h"
31 #include "globals.h"
32 #include "macros.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 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 // Reads data from "/proc/self/task/${tid}/stat".
73 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
74
75 class VoidFunctor {
76 public:
77 template <typename A>
operator()78 inline void operator() (A a ATTRIBUTE_UNUSED) const {
79 }
80
81 template <typename A, typename B>
operator()82 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
83 }
84
85 template <typename A, typename B, typename C>
operator()86 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
87 }
88 };
89
TestBitmap(size_t idx,const uint8_t * bitmap)90 inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
91 return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
92 }
93
ValidPointerSize(size_t pointer_size)94 static inline constexpr bool ValidPointerSize(size_t pointer_size) {
95 return pointer_size == 4 || pointer_size == 8;
96 }
97
EntryPointToCodePointer(const void * entry_point)98 static inline const void* EntryPointToCodePointer(const void* entry_point) {
99 uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
100 // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
101 // least 2 byte aligned.
102 code &= ~0x1;
103 return reinterpret_cast<const void*>(code);
104 }
105
106 #if defined(__BIONIC__)
107 struct Arc4RandomGenerator {
108 using result_type = uint32_t;
minArc4RandomGenerator109 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator110 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator111 uint32_t operator() () { return arc4random(); }
112 };
113 using RNG = Arc4RandomGenerator;
114 #else
115 using RNG = std::random_device;
116 #endif
117
118 template <typename T>
GetRandomNumber(T min,T max)119 static T GetRandomNumber(T min, T max) {
120 CHECK_LT(min, max);
121 std::uniform_int_distribution<T> dist(min, max);
122 RNG rng;
123 return dist(rng);
124 }
125
126 // Sleep forever and never come back.
127 NO_RETURN void SleepForever();
128
129 // Flush CPU caches. Returns true on success, false if flush failed.
130 WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
131
132 #if defined(__linux__)
133 bool IsKernelVersionAtLeast(int reqd_major, int reqd_minor);
134 #endif
135
136 // On some old kernels, a cache operation may segfault.
137 WARN_UNUSED bool CacheOperationsMaySegFault();
138
139 template <typename T>
ConvertToPointerSize(T any)140 constexpr PointerSize ConvertToPointerSize(T any) {
141 if (any == 4 || any == 8) {
142 return static_cast<PointerSize>(any);
143 } else {
144 LOG(FATAL);
145 UNREACHABLE();
146 }
147 }
148
149 // Return -1 if <, 0 if ==, 1 if >.
150 template <typename T>
Compare(T lhs,T rhs)151 inline static int32_t Compare(T lhs, T rhs) {
152 return (lhs < rhs) ? -1 : ((lhs == rhs) ? 0 : 1);
153 }
154
155 // Return -1 if < 0, 0 if == 0, 1 if > 0.
156 template <typename T>
Signum(T opnd)157 inline static int32_t Signum(T opnd) {
158 return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
159 }
160
161 template <typename Func, typename... Args>
CheckedCall(const Func & function,const char * what,Args...args)162 static inline void CheckedCall(const Func& function, const char* what, Args... args) {
163 int rc = function(args...);
164 if (UNLIKELY(rc != 0)) {
165 PLOG(FATAL) << "Checked call failed for " << what;
166 }
167 }
168
169 // Forces the compiler to emit a load instruction, but discards the value.
170 // Useful when dealing with memory paging.
171 template <typename T>
ForceRead(const T * pointer)172 inline void ForceRead(const T* pointer) {
173 static_cast<void>(*const_cast<volatile T*>(pointer));
174 }
175
176 // Lookup value for a given key in /proc/self/status. Keys and values are separated by a ':' in
177 // the status file. Returns value found on success and "<unknown>" if the key is not found or
178 // there is an I/O error.
179 std::string GetProcessStatus(const char* key);
180
181 // Return whether the address is guaranteed to be backed by a file or is shared.
182 // This information can be used to know whether MADV_DONTNEED will make
183 // following accesses repopulate the memory or return zero.
184 bool IsAddressKnownBackedByFileOrShared(const void* addr);
185
186 // Returns the number of threads running.
187 int GetTaskCount();
188
189 } // namespace art
190
191 #endif // ART_LIBARTBASE_BASE_UTILS_H_
192