blob: c8c5b72bf72ea1a4c46c39e95db255dcc132c6c8 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070016
David Sehrc431b9d2018-03-02 12:01:51 -080017#ifndef ART_LIBARTBASE_BASE_UTILS_H_
18#define ART_LIBARTBASE_BASE_UTILS_H_
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070019
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Alex Light15324762015-11-19 11:03:10 -080021#include <stdlib.h>
Elliott Hughese222ee02012-12-13 14:41:43 -080022
Alex Light15324762015-11-19 11:03:10 -080023#include <random>
Elliott Hughes34023802011-08-30 12:06:17 -070024#include <string>
Elliott Hughes34023802011-08-30 12:06:17 -070025
Andreas Gampe57943812017-12-06 21:39:13 -080026#include <android-base/logging.h>
27
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +000028#include "base/casts.h"
David Sehrc431b9d2018-03-02 12:01:51 -080029#include "base/enums.h"
30#include "base/globals.h"
31#include "base/macros.h"
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +000032#include "base/stringpiece.h"
Calin Juravlebb0b53f2014-05-23 17:33:29 +010033
Carl Shapiro6b6b5f02011-06-21 15:05:09 -070034namespace art {
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070035
Alex Light53cb16b2014-06-12 11:26:29 -070036template <typename T>
37bool 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
50template <typename T>
51bool 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
Ian Rogersef7d42f2014-01-06 12:55:46 -080064static 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}
Brian Carlstromdb4d5402011-08-09 12:18:28 -070069
Elliott Hughesc967f782012-04-16 10:23:15 -070070// Returns a human-readable size string such as "1MB".
Mathieu Chartiere6da9af2013-12-16 11:54:42 -080071std::string PrettySize(int64_t size_in_bytes);
Ian Rogers3bb17a62012-01-27 23:56:44 -080072
Elliott Hughes48436bb2012-02-07 15:23:28 -080073// Splits a string using the given separator character into a vector of
Elliott Hughes34023802011-08-30 12:06:17 -070074// strings. Empty strings will be omitted.
Ian Rogers6f3dbba2014-10-14 17:41:57 -070075void Split(const std::string& s, char separator, std::vector<std::string>* result);
Elliott Hughes48436bb2012-02-07 15:23:28 -080076
Elliott Hughes42ee1422011-09-06 12:33:32 -070077// Returns the calling thread's tid. (The C libraries don't expose this.)
78pid_t GetTid();
79
Elliott Hughes289be852012-06-12 13:57:20 -070080// Returns the given thread's name.
81std::string GetThreadName(pid_t tid);
82
Elliott Hughesdcc24742011-09-07 14:02:44 -070083// Sets the name of the current thread. The name may be truncated to an
84// implementation-defined limit.
Elliott Hughes22869a92012-03-27 14:08:24 -070085void SetThreadName(const char* thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -070086
David Sehr891a50e2017-10-27 17:01:07 -070087// Reads data from "/proc/self/task/${tid}/stat".
88void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
David Brazdil7b49e6c2016-09-01 11:06:18 +010089
Mathieu Chartierd22d5482012-11-06 17:14:12 -080090class VoidFunctor {
Mathieu Chartier357e9be2012-08-01 11:00:14 -070091 public:
Mathieu Chartierd22d5482012-11-06 17:14:12 -080092 template <typename A>
Roland Levillain4b8f1ec2015-08-26 18:34:03 +010093 inline void operator() (A a ATTRIBUTE_UNUSED) const {
Mathieu Chartierd22d5482012-11-06 17:14:12 -080094 }
95
96 template <typename A, typename B>
Roland Levillain4b8f1ec2015-08-26 18:34:03 +010097 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
Mathieu Chartierd22d5482012-11-06 17:14:12 -080098 }
99
100 template <typename A, typename B, typename C>
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100101 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800102 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700103};
104
Mathieu Chartier50030ef2015-05-08 14:19:26 -0700105inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
106 return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
107}
108
Mathieu Chartiere401d142015-04-22 13:56:20 -0700109static inline constexpr bool ValidPointerSize(size_t pointer_size) {
110 return pointer_size == 4 || pointer_size == 8;
111}
Mathieu Chartier50030ef2015-05-08 14:19:26 -0700112
Nicolas Geoffray6bc43742015-10-12 18:11:10 +0100113static 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
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000121using UsageFn = void (*)(const char*, ...);
122
123template <typename T>
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000124static void ParseIntOption(const StringPiece& option,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000125 const std::string& option_name,
126 T* out,
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000127 UsageFn usage,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000128 bool is_long_option = true) {
129 std::string option_prefix = option_name + (is_long_option ? "=" : "");
Calin Juravle2e2db782016-02-23 12:00:03 +0000130 DCHECK(option.starts_with(option_prefix)) << option << " " << option_prefix;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000131 const char* value_string = option.substr(option_prefix.size()).data();
Nicolas Geoffrayfca90a12015-10-30 12:05:41 +0000132 int64_t parsed_integer_value = 0;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000133 if (!ParseInt(value_string, &parsed_integer_value)) {
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000134 usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000135 }
136 *out = dchecked_integral_cast<T>(parsed_integer_value);
137}
138
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000139template <typename T>
140static 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
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000152void ParseDouble(const std::string& option,
153 char after_char,
154 double min,
155 double max,
156 double* parsed_value,
157 UsageFn Usage);
158
Alex Light15324762015-11-19 11:03:10 -0800159#if defined(__BIONIC__)
160struct Arc4RandomGenerator {
161 typedef uint32_t result_type;
162 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
163 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
164 uint32_t operator() () { return arc4random(); }
165};
166using RNG = Arc4RandomGenerator;
167#else
168using RNG = std::random_device;
169#endif
170
171template <typename T>
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700172static T GetRandomNumber(T min, T max) {
Alex Light15324762015-11-19 11:03:10 -0800173 CHECK_LT(min, max);
174 std::uniform_int_distribution<T> dist(min, max);
175 RNG rng;
176 return dist(rng);
177}
178
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800179// Sleep forever and never come back.
180NO_RETURN void SleepForever();
181
Roland Levillain32430262016-02-01 15:23:20 +0000182inline void FlushInstructionCache(char* begin, char* end) {
Roland Levillain32430262016-02-01 15:23:20 +0000183 __builtin___clear_cache(begin, end);
Roland Levillain32430262016-02-01 15:23:20 +0000184}
185
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000186inline 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
Andreas Gampebda1d602016-08-29 17:43:45 -0700192template <typename T>
193constexpr 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
Orion Hodsonc069a302017-01-18 09:23:12 +0000202// Returns a type cast pointer if object pointed to is within the provided bounds.
203// Otherwise returns nullptr.
204template <typename T>
205inline 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
221template <typename T, size_t size>
222constexpr size_t ArrayCount(const T (&)[size]) {
223 return size;
224}
225
buzbee31afbec2017-03-14 15:30:19 -0700226// Return -1 if <, 0 if ==, 1 if >.
227template <typename T>
228inline 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.
233template <typename T>
234inline static int32_t Signum(T opnd) {
235 return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
236}
237
Mathieu Chartier3425d022017-10-03 16:22:05 -0700238template <typename Func, typename... Args>
239static 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
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800247// Hash bytes using a relatively fast hash.
248static 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
Carl Shapiro6b6b5f02011-06-21 15:05:09 -0700261} // namespace art
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -0700262
David Sehrc431b9d2018-03-02 12:01:51 -0800263#endif // ART_LIBARTBASE_BASE_UTILS_H_