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 
28 #include "base/casts.h"
29 #include "base/enums.h"
30 #include "base/globals.h"
31 #include "base/macros.h"
32 #include "base/stringpiece.h"
33 
34 namespace art {
35 
36 template <typename T>
ParseUint(const char * in,T * out)37 bool ParseUint(const char *in, T* out) {
38   char* end;
39   unsigned long long int result = strtoull(in, &end, 0);  // NOLINT(runtime/int)
40   if (in == end || *end != '\0') {
41     return false;
42   }
43   if (std::numeric_limits<T>::max() < result) {
44     return false;
45   }
46   *out = static_cast<T>(result);
47   return true;
48 }
49 
50 template <typename T>
ParseInt(const char * in,T * out)51 bool ParseInt(const char* in, T* out) {
52   char* end;
53   long long int result = strtoll(in, &end, 0);  // NOLINT(runtime/int)
54   if (in == end || *end != '\0') {
55     return false;
56   }
57   if (result < std::numeric_limits<T>::min() || std::numeric_limits<T>::max() < result) {
58     return false;
59   }
60   *out = static_cast<T>(result);
61   return true;
62 }
63 
PointerToLowMemUInt32(const void * p)64 static inline uint32_t PointerToLowMemUInt32(const void* p) {
65   uintptr_t intp = reinterpret_cast<uintptr_t>(p);
66   DCHECK_LE(intp, 0xFFFFFFFFU);
67   return intp & 0xFFFFFFFFU;
68 }
69 
70 // Returns a human-readable size string such as "1MB".
71 std::string PrettySize(int64_t size_in_bytes);
72 
73 // Splits a string using the given separator character into a vector of
74 // strings. Empty strings will be omitted.
75 void Split(const std::string& s, char separator, std::vector<std::string>* result);
76 
77 // Returns the calling thread's tid. (The C libraries don't expose this.)
78 pid_t GetTid();
79 
80 // Returns the given thread's name.
81 std::string GetThreadName(pid_t tid);
82 
83 // Sets the name of the current thread. The name may be truncated to an
84 // implementation-defined limit.
85 void SetThreadName(const char* thread_name);
86 
87 // Reads data from "/proc/self/task/${tid}/stat".
88 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
89 
90 class VoidFunctor {
91  public:
92   template <typename A>
operator()93   inline void operator() (A a ATTRIBUTE_UNUSED) const {
94   }
95 
96   template <typename A, typename B>
operator()97   inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
98   }
99 
100   template <typename A, typename B, typename C>
operator()101   inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
102   }
103 };
104 
TestBitmap(size_t idx,const uint8_t * bitmap)105 inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
106   return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
107 }
108 
ValidPointerSize(size_t pointer_size)109 static inline constexpr bool ValidPointerSize(size_t pointer_size) {
110   return pointer_size == 4 || pointer_size == 8;
111 }
112 
EntryPointToCodePointer(const void * entry_point)113 static inline const void* EntryPointToCodePointer(const void* entry_point) {
114   uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
115   // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
116   //       least 2 byte aligned.
117   code &= ~0x1;
118   return reinterpret_cast<const void*>(code);
119 }
120 
121 using UsageFn = void (*)(const char*, ...);
122 
123 template <typename T>
124 static void ParseIntOption(const StringPiece& option,
125                             const std::string& option_name,
126                             T* out,
127                             UsageFn usage,
128                             bool is_long_option = true) {
129   std::string option_prefix = option_name + (is_long_option ? "=" : "");
130   DCHECK(option.starts_with(option_prefix)) << option << " " << option_prefix;
131   const char* value_string = option.substr(option_prefix.size()).data();
132   int64_t parsed_integer_value = 0;
133   if (!ParseInt(value_string, &parsed_integer_value)) {
134     usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
135   }
136   *out = dchecked_integral_cast<T>(parsed_integer_value);
137 }
138 
139 template <typename T>
140 static void ParseUintOption(const StringPiece& option,
141                             const std::string& option_name,
142                             T* out,
143                             UsageFn usage,
144                             bool is_long_option = true) {
145   ParseIntOption(option, option_name, out, usage, is_long_option);
146   if (*out < 0) {
147     usage("%s passed a negative value %d", option_name.c_str(), *out);
148     *out = 0;
149   }
150 }
151 
152 void ParseDouble(const std::string& option,
153                  char after_char,
154                  double min,
155                  double max,
156                  double* parsed_value,
157                  UsageFn Usage);
158 
159 #if defined(__BIONIC__)
160 struct Arc4RandomGenerator {
161   typedef uint32_t result_type;
minArc4RandomGenerator162   static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator163   static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator164   uint32_t operator() () { return arc4random(); }
165 };
166 using RNG = Arc4RandomGenerator;
167 #else
168 using RNG = std::random_device;
169 #endif
170 
171 template <typename T>
GetRandomNumber(T min,T max)172 static T GetRandomNumber(T min, T max) {
173   CHECK_LT(min, max);
174   std::uniform_int_distribution<T> dist(min, max);
175   RNG rng;
176   return dist(rng);
177 }
178 
179 // Sleep forever and never come back.
180 NO_RETURN void SleepForever();
181 
FlushInstructionCache(char * begin,char * end)182 inline void FlushInstructionCache(char* begin, char* end) {
183   __builtin___clear_cache(begin, end);
184 }
185 
FlushDataCache(char * begin,char * end)186 inline void FlushDataCache(char* begin, char* end) {
187   // Same as FlushInstructionCache for lack of other builtin. __builtin___clear_cache
188   // flushes both caches.
189   __builtin___clear_cache(begin, end);
190 }
191 
192 template <typename T>
ConvertToPointerSize(T any)193 constexpr PointerSize ConvertToPointerSize(T any) {
194   if (any == 4 || any == 8) {
195     return static_cast<PointerSize>(any);
196   } else {
197     LOG(FATAL);
198     UNREACHABLE();
199   }
200 }
201 
202 // Returns a type cast pointer if object pointed to is within the provided bounds.
203 // Otherwise returns nullptr.
204 template <typename T>
BoundsCheckedCast(const void * pointer,const void * lower,const void * upper)205 inline static T BoundsCheckedCast(const void* pointer,
206                                   const void* lower,
207                                   const void* upper) {
208   const uint8_t* bound_begin = static_cast<const uint8_t*>(lower);
209   const uint8_t* bound_end = static_cast<const uint8_t*>(upper);
210   DCHECK(bound_begin <= bound_end);
211 
212   T result = reinterpret_cast<T>(pointer);
213   const uint8_t* begin = static_cast<const uint8_t*>(pointer);
214   const uint8_t* end = begin + sizeof(*result);
215   if (begin < bound_begin || end > bound_end || begin > end) {
216     return nullptr;
217   }
218   return result;
219 }
220 
221 template <typename T, size_t size>
ArrayCount(const T (&)[size])222 constexpr size_t ArrayCount(const T (&)[size]) {
223   return size;
224 }
225 
226 // Return -1 if <, 0 if ==, 1 if >.
227 template <typename T>
Compare(T lhs,T rhs)228 inline static int32_t Compare(T lhs, T rhs) {
229   return (lhs < rhs) ? -1 : ((lhs == rhs) ? 0 : 1);
230 }
231 
232 // Return -1 if < 0, 0 if == 0, 1 if > 0.
233 template <typename T>
Signum(T opnd)234 inline static int32_t Signum(T opnd) {
235   return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
236 }
237 
238 template <typename Func, typename... Args>
CheckedCall(const Func & function,const char * what,Args...args)239 static inline void CheckedCall(const Func& function, const char* what, Args... args) {
240   int rc = function(args...);
241   if (UNLIKELY(rc != 0)) {
242     errno = rc;
243     PLOG(FATAL) << "Checked call failed for " << what;
244   }
245 }
246 
247 // Hash bytes using a relatively fast hash.
HashBytes(const uint8_t * data,size_t len)248 static inline size_t HashBytes(const uint8_t* data, size_t len) {
249   size_t hash = 0x811c9dc5;
250   for (uint32_t i = 0; i < len; ++i) {
251     hash = (hash * 16777619) ^ data[i];
252   }
253   hash += hash << 13;
254   hash ^= hash >> 7;
255   hash += hash << 3;
256   hash ^= hash >> 17;
257   hash += hash << 5;
258   return hash;
259 }
260 
261 }  // namespace art
262 
263 #endif  // ART_LIBARTBASE_BASE_UTILS_H_
264