blob: 0e8231a92c2ae80ed20b8dfa8110eeb9ed06bbcd [file] [log] [blame]
Martin Stjernholmc15e7e42020-12-02 22:50:53 +00001/*
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
34namespace art {
35
36static 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".
43std::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.
Martin Stjernholmc82f8f02021-02-10 13:23:48 +000047template<typename StrIn, typename Str>
48void Split(const StrIn& s, char separator, std::vector<Str>* out_result);
49
50template<typename Str>
51void Split(const Str& s, char separator, size_t len, Str* out_result);
52
53template<typename StrIn, typename Str, size_t kLen>
54void Split(const StrIn& s, char separator, std::array<Str, kLen>* out_result) {
55 Split<Str>(Str(s), separator, kLen, &((*out_result)[0]));
56}
Martin Stjernholmc15e7e42020-12-02 22:50:53 +000057
58// Returns the calling thread's tid. (The C libraries don't expose this.)
59uint32_t GetTid();
60
61// Returns the given thread's name.
62std::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.
66void SetThreadName(const char* thread_name);
67
68// Reads data from "/proc/self/task/${tid}/stat".
69void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
70
71class VoidFunctor {
72 public:
73 template <typename A>
74 inline void operator() (A a ATTRIBUTE_UNUSED) const {
75 }
76
77 template <typename A, typename B>
78 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
79 }
80
81 template <typename A, typename B, typename C>
82 inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
83 }
84};
85
86inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
87 return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
88}
89
90static inline constexpr bool ValidPointerSize(size_t pointer_size) {
91 return pointer_size == 4 || pointer_size == 8;
92}
93
94static 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__)
103struct Arc4RandomGenerator {
android-t13d2c5b22022-10-12 13:43:18 +0800104 using result_type = uint32_t;
Martin Stjernholmc15e7e42020-12-02 22:50:53 +0000105 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
106 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
107 uint32_t operator() () { return arc4random(); }
108};
109using RNG = Arc4RandomGenerator;
110#else
111using RNG = std::random_device;
112#endif
113
114template <typename T>
115static 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.
123NO_RETURN void SleepForever();
124
125// Flush CPU caches. Returns true on success, false if flush failed.
126WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
127
128// On some old kernels, a cache operation may segfault.
129WARN_UNUSED bool CacheOperationsMaySegFault();
130
131template <typename T>
132constexpr 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 >.
142template <typename T>
143inline 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.
148template <typename T>
149inline static int32_t Signum(T opnd) {
150 return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
151}
152
153template <typename Func, typename... Args>
154static 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.
164std::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.
169bool IsAddressKnownBackedByFileOrShared(const void* addr);
170
171// Returns the number of threads running.
172int GetTaskCount();
173
174} // namespace art
175
176#endif // ART_LIBARTBASE_BASE_UTILS_H_