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 namespace art {
35
PointerToLowMemUInt32(const void * p)36 static inline uint32_t PointerToLowMemUInt32(const void* p) {
37 uintptr_t intp = reinterpret_cast<uintptr_t>(p);
38 DCHECK_LE(intp, 0xFFFFFFFFU);
39 return intp & 0xFFFFFFFFU;
40 }
41
42 // Returns a human-readable size string such as "1MB".
43 std::string PrettySize(uint64_t size_in_bytes);
44
45 // Splits a string using the given separator character into a vector of
46 // strings. Empty strings will be omitted.
47 template<typename StrIn, typename Str>
48 void Split(const StrIn& s, char separator, std::vector<Str>* out_result);
49
50 template<typename Str>
51 void Split(const Str& s, char separator, size_t len, Str* out_result);
52
53 template<typename StrIn, typename Str, size_t kLen>
Split(const StrIn & s,char separator,std::array<Str,kLen> * out_result)54 void Split(const StrIn& s, char separator, std::array<Str, kLen>* out_result) {
55 Split<Str>(Str(s), separator, kLen, &((*out_result)[0]));
56 }
57
58 // Returns the calling thread's tid. (The C libraries don't expose this.)
59 uint32_t GetTid();
60
61 // Returns the given thread's name.
62 std::string GetThreadName(pid_t tid);
63
64 // Sets the name of the current thread. The name may be truncated to an
65 // implementation-defined limit.
66 void SetThreadName(const char* thread_name);
67
68 // Reads data from "/proc/self/task/${tid}/stat".
69 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
70
71 class VoidFunctor {
72 public:
73 template <typename A>
operator()74 inline void operator() (A a ATTRIBUTE_UNUSED) const {
75 }
76
77 template <typename A, typename B>
operator()78 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
79 }
80
81 template <typename A, typename B, typename C>
operator()82 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
83 }
84 };
85
TestBitmap(size_t idx,const uint8_t * bitmap)86 inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
87 return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
88 }
89
ValidPointerSize(size_t pointer_size)90 static inline constexpr bool ValidPointerSize(size_t pointer_size) {
91 return pointer_size == 4 || pointer_size == 8;
92 }
93
EntryPointToCodePointer(const void * entry_point)94 static inline const void* EntryPointToCodePointer(const void* entry_point) {
95 uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
96 // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
97 // least 2 byte aligned.
98 code &= ~0x1;
99 return reinterpret_cast<const void*>(code);
100 }
101
102 #if defined(__BIONIC__)
103 struct Arc4RandomGenerator {
104 typedef uint32_t result_type;
minArc4RandomGenerator105 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator106 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator107 uint32_t operator() () { return arc4random(); }
108 };
109 using RNG = Arc4RandomGenerator;
110 #else
111 using RNG = std::random_device;
112 #endif
113
114 template <typename T>
GetRandomNumber(T min,T max)115 static T GetRandomNumber(T min, T max) {
116 CHECK_LT(min, max);
117 std::uniform_int_distribution<T> dist(min, max);
118 RNG rng;
119 return dist(rng);
120 }
121
122 // Sleep forever and never come back.
123 NO_RETURN void SleepForever();
124
125 // Flush CPU caches. Returns true on success, false if flush failed.
126 WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
127
128 // On some old kernels, a cache operation may segfault.
129 WARN_UNUSED bool CacheOperationsMaySegFault();
130
131 template <typename T>
ConvertToPointerSize(T any)132 constexpr PointerSize ConvertToPointerSize(T any) {
133 if (any == 4 || any == 8) {
134 return static_cast<PointerSize>(any);
135 } else {
136 LOG(FATAL);
137 UNREACHABLE();
138 }
139 }
140
141 // Return -1 if <, 0 if ==, 1 if >.
142 template <typename T>
Compare(T lhs,T rhs)143 inline static int32_t Compare(T lhs, T rhs) {
144 return (lhs < rhs) ? -1 : ((lhs == rhs) ? 0 : 1);
145 }
146
147 // Return -1 if < 0, 0 if == 0, 1 if > 0.
148 template <typename T>
Signum(T opnd)149 inline static int32_t Signum(T opnd) {
150 return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
151 }
152
153 template <typename Func, typename... Args>
CheckedCall(const Func & function,const char * what,Args...args)154 static inline void CheckedCall(const Func& function, const char* what, Args... args) {
155 int rc = function(args...);
156 if (UNLIKELY(rc != 0)) {
157 PLOG(FATAL) << "Checked call failed for " << what;
158 }
159 }
160
161 // Lookup value for a given key in /proc/self/status. Keys and values are separated by a ':' in
162 // the status file. Returns value found on success and "<unknown>" if the key is not found or
163 // there is an I/O error.
164 std::string GetProcessStatus(const char* key);
165
166 // Return whether the address is guaranteed to be backed by a file or is shared.
167 // This information can be used to know whether MADV_DONTNEED will make
168 // following accesses repopulate the memory or return zero.
169 bool IsAddressKnownBackedByFileOrShared(const void* addr);
170
171 // Returns the number of threads running.
172 int GetTaskCount();
173
174 } // namespace art
175
176 #endif // ART_LIBARTBASE_BASE_UTILS_H_
177