blob: 5e04cb0074ec57728f7f6ee17ab50d242af633ad [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>
Andreas Gampef9411702018-09-06 17:16:57 -070027#include <android-base/parseint.h>
Andreas Gampe57943812017-12-06 21:39:13 -080028
David Sehr1979c642018-04-26 14:41:18 -070029#include "casts.h"
30#include "enums.h"
31#include "globals.h"
32#include "macros.h"
Calin Juravlebb0b53f2014-05-23 17:33:29 +010033
Lokesh Gidraca5ed9f2022-04-20 01:39:28 +000034#if defined(__linux__)
35#include <sys/utsname.h>
36#endif
37
Carl Shapiro6b6b5f02011-06-21 15:05:09 -070038namespace art {
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -070039
Ian Rogersef7d42f2014-01-06 12:55:46 -080040static 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}
Brian Carlstromdb4d5402011-08-09 12:18:28 -070045
Elliott Hughesc967f782012-04-16 10:23:15 -070046// Returns a human-readable size string such as "1MB".
Eric Holkf1e1dd12020-08-21 15:38:12 -070047std::string PrettySize(uint64_t size_in_bytes);
Ian Rogers3bb17a62012-01-27 23:56:44 -080048
Elliott Hughes48436bb2012-02-07 15:23:28 -080049// Splits a string using the given separator character into a vector of
Elliott Hughes34023802011-08-30 12:06:17 -070050// strings. Empty strings will be omitted.
Alex Light60117ae2021-02-08 17:46:15 -080051template<typename StrIn, typename Str>
52void Split(const StrIn& s, char separator, std::vector<Str>* out_result);
53
54template<typename Str>
55void Split(const Str& s, char separator, size_t len, Str* out_result);
56
57template<typename StrIn, typename Str, size_t kLen>
58void Split(const StrIn& s, char separator, std::array<Str, kLen>* out_result) {
59 Split<Str>(Str(s), separator, kLen, &((*out_result)[0]));
60}
Elliott Hughes48436bb2012-02-07 15:23:28 -080061
Elliott Hughes42ee1422011-09-06 12:33:32 -070062// Returns the calling thread's tid. (The C libraries don't expose this.)
Eric Holkf1e1dd12020-08-21 15:38:12 -070063uint32_t GetTid();
Elliott Hughes42ee1422011-09-06 12:33:32 -070064
Elliott Hughes289be852012-06-12 13:57:20 -070065// Returns the given thread's name.
66std::string GetThreadName(pid_t tid);
67
Elliott Hughesdcc24742011-09-07 14:02:44 -070068// Sets the name of the current thread. The name may be truncated to an
69// implementation-defined limit.
Elliott Hughes22869a92012-03-27 14:08:24 -070070void SetThreadName(const char* thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -070071
David Sehr891a50e2017-10-27 17:01:07 -070072// Reads data from "/proc/self/task/${tid}/stat".
73void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
David Brazdil7b49e6c2016-09-01 11:06:18 +010074
Mathieu Chartierd22d5482012-11-06 17:14:12 -080075class VoidFunctor {
Mathieu Chartier357e9be2012-08-01 11:00:14 -070076 public:
Mathieu Chartierd22d5482012-11-06 17:14:12 -080077 template <typename A>
Stefano Cianciulli78f3c722023-05-16 10:32:54 +000078 inline void operator()([[maybe_unused]] A a) const {}
Mathieu Chartierd22d5482012-11-06 17:14:12 -080079
80 template <typename A, typename B>
Stefano Cianciulli78f3c722023-05-16 10:32:54 +000081 inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b) const {}
Mathieu Chartierd22d5482012-11-06 17:14:12 -080082
83 template <typename A, typename B, typename C>
Stefano Cianciulli78f3c722023-05-16 10:32:54 +000084 inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b, [[maybe_unused]] C c) const {}
Mathieu Chartier357e9be2012-08-01 11:00:14 -070085};
86
Mathieu Chartier50030ef2015-05-08 14:19:26 -070087inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
88 return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
89}
90
Mathieu Chartiere401d142015-04-22 13:56:20 -070091static inline constexpr bool ValidPointerSize(size_t pointer_size) {
92 return pointer_size == 4 || pointer_size == 8;
93}
Mathieu Chartier50030ef2015-05-08 14:19:26 -070094
Nicolas Geoffray6bc43742015-10-12 18:11:10 +010095static inline const void* EntryPointToCodePointer(const void* entry_point) {
96 uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
97 // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
98 // least 2 byte aligned.
99 code &= ~0x1;
100 return reinterpret_cast<const void*>(code);
101}
102
Alex Light15324762015-11-19 11:03:10 -0800103#if defined(__BIONIC__)
104struct Arc4RandomGenerator {
Vladimir Marko4f990712021-07-14 12:45:13 +0100105 using result_type = uint32_t;
Alex Light15324762015-11-19 11:03:10 -0800106 static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
107 static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
108 uint32_t operator() () { return arc4random(); }
109};
110using RNG = Arc4RandomGenerator;
111#else
112using RNG = std::random_device;
113#endif
114
115template <typename T>
Mathieu Chartierdc00f182016-07-14 10:10:44 -0700116static T GetRandomNumber(T min, T max) {
Alex Light15324762015-11-19 11:03:10 -0800117 CHECK_LT(min, max);
118 std::uniform_int_distribution<T> dist(min, max);
119 RNG rng;
120 return dist(rng);
121}
122
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800123// Sleep forever and never come back.
124NO_RETURN void SleepForever();
125
Orion Hodsonaeb02232019-06-25 14:18:18 +0100126// Flush CPU caches. Returns true on success, false if flush failed.
127WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
Orion Hodsonf2331362018-07-11 15:14:10 +0100128
Lokesh Gidraca5ed9f2022-04-20 01:39:28 +0000129#if defined(__linux__)
130bool IsKernelVersionAtLeast(int reqd_major, int reqd_minor);
131#endif
132
Nicolas Geoffray8d6651d2019-07-08 10:03:16 +0100133// On some old kernels, a cache operation may segfault.
134WARN_UNUSED bool CacheOperationsMaySegFault();
135
Andreas Gampebda1d602016-08-29 17:43:45 -0700136template <typename T>
137constexpr PointerSize ConvertToPointerSize(T any) {
138 if (any == 4 || any == 8) {
139 return static_cast<PointerSize>(any);
140 } else {
141 LOG(FATAL);
142 UNREACHABLE();
143 }
144}
145
buzbee31afbec2017-03-14 15:30:19 -0700146// Return -1 if <, 0 if ==, 1 if >.
147template <typename T>
148inline static int32_t Compare(T lhs, T rhs) {
149 return (lhs < rhs) ? -1 : ((lhs == rhs) ? 0 : 1);
150}
151
152// Return -1 if < 0, 0 if == 0, 1 if > 0.
153template <typename T>
154inline static int32_t Signum(T opnd) {
155 return (opnd < 0) ? -1 : ((opnd == 0) ? 0 : 1);
156}
157
Mathieu Chartier3425d022017-10-03 16:22:05 -0700158template <typename Func, typename... Args>
159static inline void CheckedCall(const Func& function, const char* what, Args... args) {
160 int rc = function(args...);
161 if (UNLIKELY(rc != 0)) {
Mathieu Chartier3425d022017-10-03 16:22:05 -0700162 PLOG(FATAL) << "Checked call failed for " << what;
163 }
164}
165
Krzysztof KosiƄski58b1b822022-09-21 01:52:56 +0000166// Forces the compiler to emit a load instruction, but discards the value.
167// Useful when dealing with memory paging.
168template <typename T>
169inline void ForceRead(const T* pointer) {
170 static_cast<void>(*const_cast<volatile T*>(pointer));
171}
172
Wei Li8991ad02018-09-13 16:43:39 +0800173// Lookup value for a given key in /proc/self/status. Keys and values are separated by a ':' in
174// the status file. Returns value found on success and "<unknown>" if the key is not found or
175// there is an I/O error.
176std::string GetProcessStatus(const char* key);
177
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100178// Return whether the address is guaranteed to be backed by a file or is shared.
179// This information can be used to know whether MADV_DONTNEED will make
180// following accesses repopulate the memory or return zero.
181bool IsAddressKnownBackedByFileOrShared(const void* addr);
182
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000183// Returns the number of threads running.
184int GetTaskCount();
185
Carl Shapiro6b6b5f02011-06-21 15:05:09 -0700186} // namespace art
Carl Shapiroa5d5cfd2011-06-21 12:46:59 -0700187
David Sehrc431b9d2018-03-02 12:01:51 -0800188#endif // ART_LIBARTBASE_BASE_UTILS_H_